mindfork 0.18.3

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

use std::time::Duration;

use anyhow::Result;
use futures_util::StreamExt;
use tokio_util::sync::CancellationToken;

use crate::entities::attachment::{Attachment, decide_mode, inline_tokens_excluding};
use crate::entities::profile::ToolId;
use crate::entities::sampling::SamplingConfig;
use crate::shared::api::contract::Prefill;
use crate::shared::api::{ApiMessage, ChatChunk, ChatRequest};
use crate::shared::http_text::MAX_INFLATED_MB;
use crate::shared::net::{self, AddressPolicy, GuardedClient};

use super::web::{ACCEPT_HTML, ACCEPT_LANGUAGE, USER_AGENT, extract_rich, truncate_chars};
use super::{ChatEffect, Tool, ToolContext, ToolOutcome};

/// Page-fetch timeout.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
/// Hard ceiling on the extracted text of one page (characters) — a bound on what
/// a single page may put into a chat. Far above the attachment budget: beyond
/// that budget the text is attached rather than cut, so this only fires on a
/// genuinely enormous page, and when it does the result **says so** (unlike the
/// silent 12 000-character cut this replaced — see the plan doc, P2), and so does
/// the attachment, with where the text stops.
///
/// Raised from 400 000 when the project's own `spec.md` (448 525 characters) came
/// back without its last five chapters (docs/research/attachment-birth-turn.md F4):
/// a model-initiated fetch stays bounded well below `/file attach`'s 32 MB, but a
/// long specification fits.
const MAX_EXTRACT_CHARS: usize = 1_000_000;
/// How much of the text goes into the summarizer: it is a single-turn subagent
/// with its own context, so a 250 000-character page cannot be handed over
/// whole. When the page exceeds this the summary covers its head, and the full
/// text travels as the attachment.
const SUMMARY_INPUT_CHARS: usize = 12_000;
/// Ceiling on the page title used as the attachment's display name.
const NAME_TITLE_CHARS: usize = 60;
/// Token limit for the summary reply.
const SUMMARY_MAX_TOKENS: usize = 768;
/// Summarization timeout (a model call).
const SUMMARY_TIMEOUT: Duration = Duration::from_secs(90);

/// `fetch_url` — fetch a page and (by default) summarize it.
pub struct FetchUrl {
    /// Which addresses this tool may reach is the client's business, not the tool's: the
    /// model picks the URL, and the default refuses local and private ones (`shared::net`,
    /// docs/research/fetch-url-address-policy.md).
    http: GuardedClient,
}

impl Default for FetchUrl {
    fn default() -> Self {
        Self::new(AddressPolicy::PublicOnly)
    }
}

impl FetchUrl {
    pub fn new(policy: AddressPolicy) -> Self {
        Self {
            http: GuardedClient::new(policy, REQUEST_TIMEOUT),
        }
    }

    /// Fetches the page and extracts readable text. An error → a clear message
    /// (in the scaffold language `loc` — goes to the model in the `fetch_url` result).
    async fn fetch_text(&self, url: &str, loc: &crate::shared::i18n::Locale) -> Result<PageText> {
        let resp = self
            .http
            .get(url)
            // A blocked literal is refused here, before a request exists.
            .map_err(|_| anyhow::anyhow!(loc.t("tool.fetch_url.err.address_blocked").to_string()))?
            .header(reqwest::header::USER_AGENT, USER_AGENT)
            .header(reqwest::header::ACCEPT, ACCEPT_HTML)
            .header(reqwest::header::ACCEPT_LANGUAGE, ACCEPT_LANGUAGE)
            .send()
            .await
            .map_err(|e| {
                // A refusal by the address policy is not a network failure, and must not
                // read as one: "the site is down" invites a retry, and this one can only
                // fail again (lessons §4).
                if net::was_blocked(&e) {
                    anyhow::anyhow!(loc.t("tool.fetch_url.err.address_blocked").to_string())
                } else {
                    anyhow::Error::new(e)
                        .context(loc.tf("tool.fetch_url.err.request", &[("url", url)]))
                }
            })?;
        let status = resp.status();
        if !status.is_success() {
            anyhow::bail!(loc.tf(
                "tool.fetch_url.err.status",
                &[("status", &status.to_string())]
            ));
        }
        // Not `resp.text()`: that reads the bytes as UTF-8 whatever the page declares, and
        // a windows-1251 page came back as U+FFFD (docs/research/page-charset.md §1).
        let body =
            crate::shared::http_text::read(resp)
                .await
                .map_err(|err| match err.coding() {
                    _ if err.too_large() => anyhow::anyhow!(loc.tf(
                        "tool.fetch_url.err.too_large",
                        &[("max", &format!("{} MB", MAX_INFLATED_MB))]
                    )),
                    Some(coding) => {
                        anyhow::anyhow!(
                            loc.tf("tool.fetch_url.err.compressed", &[("coding", coding)])
                        )
                    }
                    None => anyhow::Error::new(err)
                        .context(loc.tf("tool.fetch_url.err.read", &[("url", url)])),
                })?;
        tracing::debug!(
            url,
            encoding = body.encoding.name(),
            source = ?body.source,
            "fetch_url: the page's encoding"
        );
        body_to_text(&body.content_type, &body.text)
            .ok_or_else(|| anyhow::anyhow!(loc.t("tool.fetch_url.err.no_text").to_string()))
    }
}

/// The page's extracted text plus what the caller has to be honest about.
#[derive(Default)]
pub(crate) struct PageText {
    pub text: String,
    /// The text hit [`MAX_EXTRACT_CHARS`] — this is not the whole page.
    pub truncated: bool,
    /// The page's name, when it states one ([`page_name`]) — the attachment's display name.
    pub title: Option<String>,
    /// The body was text (plain, Markdown, JSON, CSV, JavaScript) and is given as served, not
    /// extracted from HTML — the attachment header must not claim markup was removed
    /// (docs/research/attachment-birth-turn.md F5).
    pub verbatim: bool,
    /// How many characters the cut left out, when that is known: only for a verbatim
    /// body, which is in hand whole. Extraction stops at the ceiling, so an HTML page's
    /// remainder is never counted — and the note does not guess it.
    pub dropped_chars: Option<usize>,
}

/// Picks the text to return from the response body. Non-HTML **text** responses
/// (JSON/text/csv/JS — detected by `Content-Type`, or by the body's JSON shape
/// when it's absent) are returned as-is: this is API data, readability
/// doesn't apply to it (no `<p>`/`<li>`) — this is exactly why the JSON Steam API used to
/// give "failed to extract readable text". HTML → rich extraction
/// (`web::extract_rich`: prose **plus headings and code blocks**).
/// `None` — nothing to extract (empty). A pure function — testable without a network.
///
/// Any `text/*` that is not HTML or XML counts as text: `text/markdown` went down the
/// HTML path, found no `<p>` in a Markdown body and answered "no readable text" for a
/// page that is nothing but (found while testing F5 of
/// docs/research/attachment-birth-turn.md).
fn body_to_text(content_type: &str, body: &str) -> Option<PageText> {
    let ct = content_type.to_ascii_lowercase();
    let is_html = ct.contains("html") || ct.contains("xml");
    let is_texty = ct.contains("json")
        || ct.contains("javascript")
        || (ct.trim_start().starts_with("text/") && !is_html);
    let looks_json = {
        let t = body.trim_start();
        t.starts_with('{') || t.starts_with('[')
    };
    if is_texty || (looks_json && !is_html) {
        let trimmed = body.trim();
        if !trimmed.is_empty() {
            let total = trimmed.chars().count();
            return Some(PageText {
                text: truncate_chars(trimmed, MAX_EXTRACT_CHARS),
                truncated: total > MAX_EXTRACT_CHARS,
                title: None,
                verbatim: true,
                dropped_chars: (total > MAX_EXTRACT_CHARS).then(|| total - MAX_EXTRACT_CHARS),
            });
        }
    }
    let text = extract_rich(body, MAX_EXTRACT_CHARS);
    (!text.is_empty()).then(|| PageText {
        truncated: text.chars().count() >= MAX_EXTRACT_CHARS,
        text,
        title: page_name(body),
        verbatim: false,
        dropped_chars: None,
    })
}

/// The last Markdown heading of `text` — a line of one to six `#` and a space, at
/// most three spaces in, outside a fenced code block — with its byte offset: where a
/// cut text says it stops (docs/research/attachment-birth-turn.md F3). Rich extraction
/// writes headings this way (`## …`) and so does a plain `.md` page; a text with none
/// (JSON, unstructured prose) has no answer, and the note then says less rather than
/// guessing. A shell comment inside a fence is not a heading, which is what the fence
/// tracking is for.
fn last_heading(text: &str) -> Option<(usize, String)> {
    /// Long enough for any real section title; a "heading" past it is a paragraph.
    const MAX_HEADING_CHARS: usize = 120;
    let mut fence: Option<char> = None;
    let mut found = None;
    let mut offset = 0;
    for line in text.split_inclusive('\n') {
        let start = offset;
        offset += line.len();
        let body = line.trim_start_matches(' ');
        if line.len() - body.len() > 3 {
            continue; // an indented code block, not a heading or a fence
        }
        let marker = body.chars().next();
        if let Some(open) = fence {
            if marker == Some(open) && body.starts_with(&open.to_string().repeat(3)) {
                fence = None;
            }
            continue;
        }
        if body.starts_with("```") || body.starts_with("~~~") {
            fence = marker;
            continue;
        }
        let level = body.chars().take_while(|&c| c == '#').count();
        if !(1..=6).contains(&level) {
            continue;
        }
        let rest = &body[level..];
        if !rest.starts_with([' ', '\t']) {
            continue; // `#hashtag`, `#[derive]`
        }
        // A closing run of `#` is decoration (CommonMark), not part of the title.
        let title = rest.trim().trim_end_matches('#').trim_end();
        if title.is_empty() {
            continue;
        }
        let title = if title.chars().count() > MAX_HEADING_CHARS {
            format!("{}…", truncate_chars(title, MAX_HEADING_CHARS))
        } else {
            title.to_string()
        };
        found = Some((start, title));
    }
    found
}

/// What a result says about a page that hit the ceiling (docs/research/attachment-birth-turn.md
/// F3): the limit; where the received text stops, when the caller can place it; how much
/// was left out, when that is known; and that no route reaches the rest — a note that
/// stopped at "this is not the whole page" left the model hunting the end of the
/// attachment for a chapter that was never in it.
fn cut_note(
    loc: &crate::shared::i18n::Locale,
    page: &PageText,
    ends_in: Option<(&str, usize, usize)>,
) -> String {
    let limit = MAX_EXTRACT_CHARS.to_string();
    let mut parts = vec![loc.tf("tool.fetch_url.result.truncated", &[("limit", &limit)])];
    if let Some((heading, at, pages)) = ends_in {
        parts.push(loc.tf(
            "tool.fetch_url.result.cut_at_heading",
            &[
                ("heading", heading),
                ("page", &at.to_string()),
                ("pages", &pages.to_string()),
            ],
        ));
    }
    if let Some(n) = page.dropped_chars {
        parts.push(loc.tf(
            "tool.fetch_url.result.cut_dropped",
            &[("n", &n.to_string())],
        ));
    }
    parts.push(loc.t("tool.fetch_url.result.cut_door").to_string());
    parts.join(" ")
}

/// The page's name for the attachment: the name a second field confirms
/// (docs/research/page-attachment-name.md §4). A page states its name in up to three
/// places — `og:title`, an `<h1>`, the `<title>` — and its site's name in some of the
/// same ones: `docs.vlang.io` gives every page one `<title>` ("V Documentation"),
/// `sector.biz.ua` every article one `<h1>` (the archive's banner). Taking either field
/// first names every page of one of them after the site — measured, six sites of 43
/// under the `<h1>`-first rule this replaces.
fn page_name(body: &str) -> Option<String> {
    let doc = scraper::Html::parse_document(body);
    let fields = NameFields::read(&doc);
    let clipped: String = fields.name()?.chars().take(NAME_TITLE_CHARS).collect();
    let name = clipped.trim();
    (!name.is_empty()).then(|| name.to_string())
}

/// What a page says about its own name, each field as [`clean_field`] leaves it.
struct NameFields {
    title: String,
    h1s: Vec<String>,
    og_title: Option<String>,
    og_site_name: Option<String>,
}

impl NameFields {
    fn read(doc: &scraper::Html) -> Self {
        let texts = |selector: &str| -> Vec<String> {
            scraper::Selector::parse(selector)
                .map(|sel| {
                    doc.select(&sel)
                        .map(|e| clean_field(&e.text().collect::<String>()))
                        .filter(|t| !t.is_empty())
                        .collect()
                })
                .unwrap_or_default()
        };
        let meta = |property: &str| -> Option<String> {
            let sel = scraper::Selector::parse(&format!(r#"meta[property="{property}"]"#)).ok()?;
            doc.select(&sel)
                .find_map(|e| e.value().attr("content"))
                .map(clean_field)
                .filter(|c| !c.is_empty())
        };
        Self {
            title: texts("title").into_iter().next().unwrap_or_default(),
            h1s: texts("h1"),
            og_title: meta("og:title"),
            og_site_name: meta("og:site_name"),
        }
    }

    /// First match wins:
    /// 1. `og:title`, unless it is the site's own name — without a trailing segment it
    ///    shares with the `<title>` ("Moon - Wikipedia" → "Moon");
    /// 2. an `<h1>` the `<title>` begins with, as the `<title>` spells it — any `<h1>`, a
    ///    blog's banner often being the first;
    /// 3. the `<title>` without its last segment, which is where a title puts its site;
    /// 4. the first `<h1>` — a `<title>` that is the site's name alone;
    /// 5. the `<title>`.
    fn name(&self) -> Option<&str> {
        let title = self.title.as_str();
        let site = split_last_segment(title).map(|(_, site)| site);
        let is_site = |text: &str| {
            site.is_some_and(|site| same_text(text, site))
                || self
                    .og_site_name
                    .as_deref()
                    .is_some_and(|name| same_text(text, name))
        };
        if let Some(og) = self.og_title.as_deref().filter(|og| !is_site(og)) {
            return Some(match split_last_segment(og) {
                Some((head, tail)) if site.is_some_and(|site| same_text(tail, site)) => head,
                _ => og,
            });
        }
        if let Some(head) = self.h1s.iter().find_map(|h1| title_begins_with(title, h1)) {
            return Some(head);
        }
        split_last_segment(title)
            .map(|(head, _)| head)
            .or_else(|| self.h1s.first().map(String::as_str))
            .or_else(|| (!title.is_empty()).then_some(title))
    }
}

/// The spaced separators a `<title>` puts between a page and its site — every one the
/// research corpus uses (§2).
const TITLE_SEPARATORS: [&str; 10] = [
    " | ", " — ", " – ", " - ", " -> ", " :: ", " · ", " » ", " / ", " : ",
];

/// `text` split at its last spaced separator: everything before it — a page's own name
/// may hold a separator ("json — JSON encoder and decoder") — and the last segment.
fn split_last_segment(text: &str) -> Option<(&str, &str)> {
    let (at, len) = TITLE_SEPARATORS
        .iter()
        .filter_map(|sep| text.rfind(sep).map(|at| (at, sep.len())))
        .max_by_key(|&(at, _)| at)?;
    let head = text[..at].trim();
    (!head.is_empty()).then(|| (head, text[at + len..].trim()))
}

/// The start of `title` that reads as `h1` ignoring case, spelled as `title` spells it —
/// and only at a word's end, so an `<h1>` "Go" does not name "Google Search".
fn title_begins_with<'a>(title: &'a str, h1: &str) -> Option<&'a str> {
    let n = h1.chars().count();
    let end = title
        .char_indices()
        .nth(n)
        .map_or(title.len(), |(at, _)| at);
    let head = &title[..end];
    let word_ends = title[end..]
        .chars()
        .next()
        .is_none_or(|c| !c.is_alphanumeric());
    (n > 0 && word_ends && head.chars().count() == n && same_text(head, h1)).then_some(head)
}

fn same_text(a: &str, b: &str) -> bool {
    a.to_lowercase() == b.to_lowercase()
}

/// Whitespace collapsed, and a heading's permalink mark trimmed from its ends — Sphinx's
/// `¶`, the zero-width space VitePress anchors with — so a field compares as it reads.
fn clean_field(raw: &str) -> String {
    let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" ");
    collapsed
        .trim_matches(|c: char| {
            c.is_whitespace()
                || c == ''
                || matches!(c, '\u{200b}'..='\u{200d}' | '\u{2060}' | '\u{feff}')
        })
        .to_string()
}

/// Keeps the display name unique within the chat: a page whose every field names
/// its site would still collide (docs/research/page-attachment-name.md §5), so a
/// name already taken by a **different** page gets the URL's last segment appended. Deterministic (no
/// counters), so re-fetching the same page produces the same name and replaces
/// its own attachment rather than piling up copies.
fn unique_name(base: &str, url: &str, existing: &[Attachment]) -> String {
    let taken = existing
        .iter()
        .any(|a| a.name.eq_ignore_ascii_case(base) && !a.source.eq_ignore_ascii_case(url));
    match taken.then(|| url_segment(url)).flatten() {
        Some(seg) => format!("{base} — {seg}"),
        None => base.to_string(),
    }
}

/// The URL's last non-empty path segment, else its host — the shortest thing
/// that still tells two pages of one site apart.
fn url_segment(url: &str) -> Option<String> {
    let without_scheme = url.split_once("://").map(|(_, r)| r).unwrap_or(url);
    let path = without_scheme.split(['?', '#']).next().unwrap_or("");
    let mut parts = path.split('/').filter(|s| !s.is_empty());
    let host = parts.next()?;
    Some(parts.next_back().unwrap_or(host).to_string())
}

#[async_trait::async_trait]
impl Tool for FetchUrl {
    fn id(&self) -> ToolId {
        super::FETCH_URL_ID.into()
    }
    /// A page fetch changes nothing and holds nothing: three pages from three
    /// hosts are three unrelated connections — the largest win a concurrent
    /// round has (docs/research/concurrent-tools.md §2.3). The summary request
    /// it may make takes a session permit of its own (§4.5).
    fn concurrent(&self) -> bool {
        true
    }
    fn group(&self) -> crate::features::tools::meta::ToolGroup {
        crate::features::tools::meta::ToolGroup::ExternalWorld
    }
    fn ui_label(&self) -> &'static str {
        "fetch page"
    }
    fn gate(&self) -> Option<crate::features::tools::meta::ToolGate> {
        Some(crate::features::tools::meta::ToolGate::Web)
    }
    fn description(&self, loc: &crate::shared::i18n::Locale) -> String {
        loc.t("tool.fetch_url.desc").into()
    }
    fn parameters(&self, loc: &crate::shared::i18n::Locale) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "url": {"type": "string", "description": loc.t("tool.fetch_url.param.url")},
                "focus": {
                    "type": "string",
                    "description": loc.t("tool.fetch_url.param.focus")
                },
                "summarize": {
                    "type": "boolean",
                    "description": loc.t("tool.fetch_url.param.summarize")
                }
            },
            "required": ["url"]
        })
    }
    async fn invoke(&self, ctx: &ToolContext, args: serde_json::Value) -> Result<ToolOutcome> {
        let url = args
            .get("url")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| anyhow::anyhow!(ctx.loc.t("tool.fetch_url.err.url_empty")))?;
        if !(url.starts_with("http://") || url.starts_with("https://")) {
            anyhow::bail!(ctx.loc.t("tool.fetch_url.err.url_scheme"));
        }
        // A YouTube watch page is a JavaScript shell: measured, it has zero
        // paragraphs and zero list items, so readability extracts nothing and
        // this used to answer "failed to extract readable text" — a dead end the
        // model cannot reason its way out of. Hand back what the free paths know
        // and point at the tool that can actually watch it (fork R6,
        // docs/research/youtube-integration.md §1).
        if super::youtube::is_youtube_url(url)
            && let Some(id) = super::youtube::video_id(url)
        {
            let meta = super::youtube::fetch_meta(self.http.unchecked_inner(), &id)
                .await
                .unwrap_or_default();
            let mut out = super::youtube::YoutubeWatch::meta_block(
                &meta,
                &super::youtube::watch_url(&id),
                ctx.loc,
            );
            out.push('\n');
            out.push_str(ctx.loc.t("tool.fetch_url.result.youtube"));
            return Ok(ToolOutcome::text(out));
        }
        let focus = args
            .get("focus")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty());
        let summarize = args
            .get("summarize")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let page = match self.fetch_text(url, ctx.loc).await {
            Ok(t) => t,
            Err(err) => {
                return Ok(ToolOutcome::text(ctx.loc.tf(
                    "tool.fetch_url.result.fetch_failed",
                    &[("url", url), ("err", &err.to_string())],
                )));
            }
        };

        // Small enough to read at once → straight into the result: the model
        // needs no second call, and attaching would put the same text in the
        // pinned block *and* in the history. The threshold is the attachment
        // budget itself (sub-decision S1), which is also why an attached page is
        // always by reference: inline requires `est <= max_file_tokens`, and this
        // branch is exactly the other side of it.
        let est = crate::shared::tokens::estimate_text(&page.text) as usize;
        if est <= ctx.attachment_cfg.max_file_tokens {
            return Ok(self.inline_result(ctx, url, focus, summarize, &page).await);
        }
        Ok(self.attached_result(ctx, url, focus, summarize, page).await)
    }
}

impl FetchUrl {
    /// The page fits the budget: previous behaviour — a summary, or the text
    /// itself when `summarize=false` (or when summarization failed).
    async fn inline_result(
        &self,
        ctx: &ToolContext,
        url: &str,
        focus: Option<&str>,
        summarize: bool,
        page: &PageText,
    ) -> ToolOutcome {
        let summary = if summarize {
            summarize_text(ctx, url, focus, &page.text).await.ok()
        } else {
            None
        };
        // The engine's timing of the summary's prompt rides the outcome
        // whatever the text made of it (page-summary-usage §3.2).
        let prefill = summary.as_ref().and_then(|s| s.prefill);
        let mut out = match (summarize, summary) {
            (true, Some(s)) if !s.text.trim().is_empty() => s.text,
            // Summarization failed/came back empty → return the extracted text
            // (graceful degradation: the model still gets the page's content).
            (true, _) => format!(
                "{}\n{}",
                ctx.loc
                    .tf("tool.fetch_url.result.content_no_summary", &[("url", url)]),
                page.text
            ),
            (false, _) => format!(
                "{}\n{}",
                ctx.loc.tf("tool.fetch_url.result.content", &[("url", url)]),
                page.text
            ),
        };
        if page.truncated {
            // The text is right here in the result, so there is no page to place
            // its end on — the limit, the remainder and the door still apply.
            out.push('\n');
            out.push_str(&cut_note(ctx.loc, page, None));
        }
        ToolOutcome::text(out).with_prefill(prefill)
    }

    /// The page is over the attachment budget: attach it whole (spec §9.7) and
    /// return a summary of its head plus how to reach the rest. The alternative —
    /// cutting the text into the result — is what made a long documentation page
    /// indistinguishable from a complete one (the plan doc, P2).
    async fn attached_result(
        &self,
        ctx: &ToolContext,
        url: &str,
        focus: Option<&str>,
        summarize: bool,
        page: PageText,
    ) -> ToolOutcome {
        let base = page.title.clone().unwrap_or_else(|| url.to_string());
        let name = unique_name(&base, url, &ctx.attachments);
        let header_key = if page.verbatim {
            "tool.fetch_url.attachment.header_verbatim"
        } else {
            "tool.fetch_url.attachment.header"
        };
        let mut header = ctx.loc.tf(header_key, &[("name", &name), ("url", url)]);
        // A cut is stated **in the attachment**, twice (F3): in the header — which the
        // pinned excerpt shows on every later turn, when this result is long gone from
        // view — and where the text stops, so the last page ends on the marker rather
        // than on half a word.
        let limit = MAX_EXTRACT_CHARS.to_string();
        let ends_in = page.truncated.then(|| last_heading(&page.text)).flatten();
        if page.truncated {
            header.push('\n');
            header.push_str(&match &ends_in {
                Some((_, heading)) => ctx.loc.tf(
                    "tool.fetch_url.attachment.truncated_heading",
                    &[("limit", &limit), ("heading", heading)],
                ),
                None => ctx
                    .loc
                    .tf("tool.fetch_url.attachment.truncated", &[("limit", &limit)]),
            });
        }
        let mut text = format!("{header}\n\n{}", page.text);
        if page.truncated {
            text.push_str("\n\n");
            text.push_str(
                &ctx.loc
                    .tf("tool.fetch_url.attachment.cut_marker", &[("limit", &limit)]),
            );
        }
        // The heading's place in the attachment, past the header and its blank line.
        let ends_in = ends_in.map(|(at, heading)| (header.len() + 2 + at, heading));
        // Through the shared rule rather than hardcoding `ByReference`: that is a
        // *consequence* of the threshold above, and the orchestrator decides
        // `/file attach` the same way, so the two cannot drift.
        let used = inline_tokens_excluding(&ctx.attachments, url);
        let est = crate::shared::tokens::estimate_text(&text) as usize;
        let mode = decide_mode(est, used, &ctx.attachment_cfg);
        let bytes = text.len();
        let attachment = Attachment::new(name.clone(), url.to_string(), text, bytes, mode);
        let pages = attachment.page_count(ctx.attachment_cfg.page_tokens);

        let mut out = String::new();
        let mut prefill = None;
        if summarize {
            // The head only: the summarizer is a single-turn subagent with its
            // own context. The result says the whole page is attached, so a
            // partial summary is a starting point rather than the only access.
            let head = truncate_chars(&page.text, SUMMARY_INPUT_CHARS);
            if let Ok(s) = summarize_text(ctx, url, focus, &head).await {
                prefill = s.prefill;
                if !s.text.trim().is_empty() {
                    out.push_str(s.text.trim());
                    out.push('\n');
                }
            }
        }
        // "The whole page" only when it is: a cut page is attached as what was received.
        let attached_key = if page.truncated {
            "tool.fetch_url.result.attached_cut"
        } else {
            "tool.fetch_url.result.attached"
        };
        out.push_str(&ctx.loc.tf(
            attached_key,
            &[("name", &name), ("pages", &pages.to_string())],
        ));
        // Search is offered only where an index is coming (G4): it is being built
        // from the end of this round, and a search waits for it.
        out.push(' ');
        out.push_str(super::attachment::search_route(ctx));
        if page.truncated {
            let ends_in = ends_in.as_ref().map(|(at, heading)| {
                (
                    heading.as_str(),
                    attachment.page_at(ctx.attachment_cfg.page_tokens, *at),
                    pages,
                )
            });
            out.push('\n');
            out.push_str(&cut_note(ctx.loc, &page, ends_in));
        }
        ToolOutcome::with_effects(out, vec![ChatEffect::AddAttachment(Box::new(attachment))])
            .with_prefill(prefill)
    }
}

/// What a summary's stream left: the text, and the engine's timing of the
/// prompt (`None` from every provider but llama.cpp, and from a stream that
/// ended before its usage chunk).
struct Summarized {
    text: String,
    prefill: Option<Prefill>,
}

/// Summarizes the page text via an independent single-turn request to the model
/// (like `call_subagent`: no history/tools, with a token/time limit).
async fn summarize_text(
    ctx: &ToolContext,
    url: &str,
    focus: Option<&str>,
    text: &str,
) -> Result<Summarized> {
    let system = ctx.loc.t("tool.fetch_url.summarize.system").to_string();
    let task = match focus {
        Some(f) => ctx.loc.tf(
            "tool.fetch_url.summarize.task_focus",
            &[("url", url), ("f", f), ("text", text)],
        ),
        None => ctx.loc.tf(
            "tool.fetch_url.summarize.task",
            &[("url", url), ("text", text)],
        ),
    };

    let max_tokens = ctx
        .effective_sampling
        .max_tokens
        .map_or(SUMMARY_MAX_TOKENS, |m| m.min(SUMMARY_MAX_TOKENS));
    // What the stream will occupy of a shared KV pool: the request's estimate
    // (no earlier round of its own to floor it) plus its reply cap
    // (docs/research/admission-by-budget.md §4.2).
    let estimate = crate::shared::tokens::estimate_prompt(Some(&system), [task.as_str()]);
    // Reasoning muted the way the title's and the roll's is (`title.rs`): a
    // one-shot retelling of a page, whose reply cap a thinking model spent
    // whole on thoughts and answered with nothing — both pages tried on the
    // gate model, `finish = Length` (docs/research/page-summary-usage.md
    // §2.1, fork F3).
    let sampling = SamplingConfig {
        max_tokens: Some(max_tokens),
        reasoning_budget: Some(0),
        ..ctx.effective_sampling.clone()
    };
    let request = ChatRequest {
        continue_final: false,
        system: Some(system),
        messages: vec![ApiMessage::user(task)],
        sampling,
        tools: Vec::new(), // no tools (a nesting ban)
    };

    // A permit of the turn's session budget, held for the stream and for
    // nothing else (docs/research/concurrent-tools.md §4.5): the summary is a
    // request stream like the loops' own, so with `sessions = 1` three pages
    // fetched at once are summarised one after another — and under a shared
    // KV pool as many at once as the pool holds, not as many as the permits
    // allow (admission-by-budget §4.5). Taken before the timeout starts —
    // waiting behind a sibling's stream is not this summary's slowness. A
    // background task has no budget to take (`None`).
    let _permit = match ctx.sessions.as_deref() {
        Some(budget) => {
            let need = budget.price(
                crate::shared::session_budget::Shape::Summary,
                estimate,
                0,
                Some(max_tokens as u64),
            );
            // A silent loop's summary takes the silent lane: one of the
            // app's own requests at a time (silent-tasks-budget §4.2).
            let reservation = if ctx.silent_lane {
                // One tool call inside a round that already dropped its own
                // reservation: it holds (silent-preemption §4.3).
                budget
                    .acquire_silent(need, &ctx.cancel, "summary", false)
                    .await
            } else {
                budget.acquire(need, &ctx.cancel).await
            };
            match reservation {
                Some(reservation) => Some(reservation),
                None => anyhow::bail!(ctx.loc.t("tool.fetch_url.err.summary_cancelled")),
            }
        }
        None => None,
    };
    let cancel = CancellationToken::new();
    let engine = ctx.engine.clone();
    let collect = async {
        let mut stream = engine.chat_stream(request, cancel.clone()).await?;
        let mut out = String::new();
        let mut prefill = None;
        while let Some(chunk) = stream.next().await {
            match chunk {
                ChatChunk::Text(t) => out.push_str(&t),
                ChatChunk::Finished(_) => break,
                // A background turn: the retry is worth a log line (a flaky provider is
                // otherwise invisible here) but has nothing to show — these turns have no
                // chip of their own.
                ChatChunk::Retry {
                    attempt,
                    max,
                    delay,
                } => {
                    tracing::info!(attempt, max, ?delay, "retrying a a page-summary turn");
                }
                ChatChunk::Error { message, .. } => {
                    tracing::warn!(error = %message, "engine error while summarizing a page");
                }
                // The server's exact count beside the estimate the reservation
                // was priced from, under the summary's own kind — a page's
                // text under-counts on four pages of five, the one kind that
                // does as a rule (docs/research/page-summary-usage.md §3.1) —
                // and the engine's timing of the prompt for the outcome (§3.2).
                // Taken here: the collect breaks at `Finished`.
                ChatChunk::Usage(u) => {
                    if let Some(budget) = ctx.sessions.as_deref() {
                        budget.record_usage(
                            crate::shared::session_budget::Shape::Summary,
                            estimate,
                            u.prompt_tokens as u64,
                        );
                    }
                    prefill = u.prefill;
                }
                ChatChunk::Thoughts(_)
                | ChatChunk::ThoughtsSignature(_)
                | ChatChunk::ToolCall(_)
                | ChatChunk::Served(_) => {}
            }
        }
        Ok::<Summarized, anyhow::Error>(Summarized { text: out, prefill })
    };

    match tokio::time::timeout(SUMMARY_TIMEOUT, collect).await {
        Ok(res) => res,
        Err(_) => {
            cancel.cancel();
            anyhow::bail!(ctx.loc.t("tool.fetch_url.err.summary_timeout"));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shared::api::Embedder;
    use crate::shared::api::contract::{ChatStream, EngineBackend, FinishReason};
    use crate::shared::api::mock::{MockBackend, MockEmbedder};
    use std::sync::{Arc, Mutex};
    use uuid::Uuid;

    /// An engine that remembers the last request and returns a fixed reply.
    struct CapturingBackend {
        last: Mutex<Option<ChatRequest>>,
        reply: String,
    }

    #[async_trait::async_trait]
    impl EngineBackend for CapturingBackend {
        async fn chat_stream(
            &self,
            req: ChatRequest,
            _cancel: CancellationToken,
        ) -> Result<ChatStream> {
            *self.last.lock().unwrap() = Some(req);
            let reply = self.reply.clone();
            let s = async_stream::stream! {
                yield ChatChunk::Text(reply);
                yield ChatChunk::Finished(FinishReason::Stop);
            };
            Ok(Box::pin(s))
        }
    }

    fn ctx_with_engine(engine: Arc<dyn EngineBackend>) -> (tempfile::TempDir, ToolContext) {
        let embedder: Arc<dyn Embedder> = Arc::new(MockEmbedder::new(16));
        let (dir, _storage, ctx) =
            super::super::testkit::ctx_with_backends(Uuid::new_v4(), engine, embedder);
        (dir, ctx)
    }

    /// A page big enough to be over the attachment budget.
    fn big_page(title: Option<&str>) -> PageText {
        // Deliberately long enough that `estimate_text` clears
        // `max_file_tokens` (4000 by default) several times over.
        let body = "Абзац с содержательным текстом страницы. ".repeat(2000);
        PageText {
            text: format!("НАЧАЛО\n{body}\nКОНЕЦ"),
            title: title.map(str::to_string),
            ..PageText::default()
        }
    }

    /// The defect this closes (plan doc, P2): a long page used to be cut at
    /// 12 000 characters, mid-word, with nothing saying so and no way to reach
    /// the rest. Now it arrives whole as an attachment.
    #[tokio::test]
    async fn a_page_over_the_budget_is_attached_whole() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let page = big_page(Some("Управление памятью в V"));
        let full = page.text.clone();
        let out = FetchUrl::default()
            .attached_result(&ctx, "https://docs.vlang.io/x.html", None, false, page)
            .await;

        let [ChatEffect::AddAttachment(att)] = out.effects.as_slice() else {
            panic!("no attachment effect: {:?}", out.effects);
        };
        assert!(
            att.text.contains("НАЧАЛО") && att.text.contains("КОНЕЦ"),
            "the text is not whole"
        );
        assert!(att.text.contains(&full), "the extracted text was altered");
        assert_eq!(
            att.name, "Управление памятью в V",
            "the page title names it"
        );
        assert_eq!(att.source, "https://docs.vlang.io/x.html");
        // Over `max_file_tokens` by construction — the other side of the same
        // threshold, so an attachment made this way is never inline.
        assert_eq!(
            att.mode,
            crate::entities::attachment::AttachMode::ByReference
        );
        // The attachment carries its own header, so the file still says what it
        // is when it is read page by page much later.
        assert!(
            att.text.contains("https://docs.vlang.io/x.html"),
            "no source in the header"
        );

        // And the result must say where the text went and how to reach it —
        // otherwise this repeats P2 in a politer form.
        let pages = att.page_count(ctx.attachment_cfg.page_tokens).to_string();
        assert!(
            out.result.contains("attachment_read"),
            "got: {}",
            out.result
        );
        assert!(out.result.contains(&pages), "no page count: {}", out.result);
        // Search is offered as the index being built for it — with an embedder
        // configured, as the test context has — and a search waits for it
        // (docs/research/attachment-birth-turn.md G4).
        let route = super::super::attachment::search_route(&ctx);
        assert_eq!(route, ctx.loc.t("tool.attachment.search_indexing"));
        assert!(out.result.contains(route), "got: {}", out.result);
        // Without one, the same page is offered for reading only.
        let mut bare = ctx.clone();
        bare.embed_configured = false;
        let out = FetchUrl::default()
            .attached_result(
                &bare,
                "https://docs.vlang.io/x.html",
                None,
                false,
                big_page(None),
            )
            .await;
        assert!(
            out.result
                .contains(bare.loc.t("tool.attachment.search_none")),
            "got: {}",
            out.result
        );
        // Nothing was cut, so nothing says so.
        let limit = MAX_EXTRACT_CHARS.to_string();
        let marker = ctx
            .loc
            .tf("tool.fetch_url.attachment.cut_marker", &[("limit", &limit)]);
        assert!(!att.text.contains(&marker), "a whole page marked as cut");
    }

    #[tokio::test]
    async fn a_titleless_page_is_named_by_its_url() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let out = FetchUrl::default()
            .attached_result(&ctx, "https://example.com/a", None, false, big_page(None))
            .await;
        let [ChatEffect::AddAttachment(att)] = out.effects.as_slice() else {
            panic!("no attachment effect");
        };
        assert_eq!(att.name, "https://example.com/a");
    }

    /// `summarize=true` still summarizes — from the head, since the summarizer is
    /// a single-turn subagent — and still attaches, so a partial summary is a
    /// starting point rather than the only access to the page.
    #[tokio::test]
    async fn an_attached_page_is_still_summarized_from_its_head() {
        let backend = Arc::new(CapturingBackend {
            last: Mutex::new(None),
            reply: "краткое содержание".into(),
        });
        let (_d, ctx) = ctx_with_engine(backend.clone());
        let out = FetchUrl::default()
            .attached_result(&ctx, "https://example.com", None, true, big_page(None))
            .await;
        assert!(
            out.result.contains("краткое содержание"),
            "got: {}",
            out.result
        );
        assert!(
            out.result.contains("attachment_read"),
            "got: {}",
            out.result
        );
        assert_eq!(
            out.effects.len(),
            1,
            "the page is attached as well as summarized"
        );

        let req = backend.last.lock().unwrap().take().unwrap();
        let sent = format!("{:?}", req.messages[0]);
        assert!(
            sent.chars().count() < SUMMARY_INPUT_CHARS * 2,
            "the whole page went to the summarizer ({} chars)",
            sent.chars().count()
        );
    }

    /// The size ceiling stays, but it is announced — the other half of P2 — in the
    /// result **and** in the attachment, with the door closed: nothing fetches the rest
    /// (docs/research/attachment-birth-turn.md F3).
    #[tokio::test]
    async fn hitting_the_size_ceiling_is_announced() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let limit = MAX_EXTRACT_CHARS.to_string();
        let note = ctx
            .loc
            .tf("tool.fetch_url.result.truncated", &[("limit", &limit)]);
        let door = ctx.loc.t("tool.fetch_url.result.cut_door");
        let mut page = big_page(None);
        page.truncated = true;
        let out = FetchUrl::default()
            .attached_result(&ctx, "https://example.com", None, false, page)
            .await;
        assert!(out.result.contains(&note), "got: {}", out.result);
        assert!(out.result.contains(door), "got: {}", out.result);
        // A cut page is not "the whole page".
        assert!(
            !out.result.contains(
                ctx.loc
                    .t("tool.fetch_url.result.attached")
                    .split('«')
                    .next()
                    .unwrap()
            ),
            "a cut page announced as whole: {}",
            out.result
        );
        let [ChatEffect::AddAttachment(att)] = out.effects.as_slice() else {
            panic!("no attachment effect: {:?}", out.effects);
        };
        // The attachment says it too — its header is what the pinned excerpt shows on
        // every later turn — and its last page ends on the marker, not mid-word.
        let header_note = ctx
            .loc
            .tf("tool.fetch_url.attachment.truncated", &[("limit", &limit)]);
        let excerpt = att.excerpt(ctx.attachment_cfg.excerpt_tokens);
        assert!(excerpt.contains(&header_note), "{excerpt}");
        let marker = ctx
            .loc
            .tf("tool.fetch_url.attachment.cut_marker", &[("limit", &limit)]);
        let pages = att.page_count(ctx.attachment_cfg.page_tokens);
        let last = att.page(ctx.attachment_cfg.page_tokens, pages).unwrap();
        assert!(last.trim_end().ends_with(&marker), "{last}");

        // The same on the path where the page fits and is returned inline.
        let small = PageText {
            text: "короткий текст".into(),
            truncated: true,
            ..PageText::default()
        };
        let inline = FetchUrl::default()
            .inline_result(&ctx, "https://example.com", None, false, &small)
            .await;
        assert!(inline.result.contains(&note), "got: {}", inline.result);
        assert!(inline.result.contains(door), "got: {}", inline.result);
    }

    /// The transcript that prompted F3: the model was told "not the whole page" and
    /// went hunting the end of the attachment for a chapter the cut had removed. The
    /// note now names the section the text stops in, the page that section starts
    /// on — the one `attachment_read` returns it on — and, for a body taken verbatim,
    /// how much never arrived.
    #[tokio::test]
    async fn a_cut_page_says_where_it_ends() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let filler = "Строка содержательного текста спецификации.\n".repeat(400);
        let text = format!(
            "# Спецификация\n\n## 1. Обзор\n\n{filler}\n```sh\n# не заголовок, а комментарий\n```\n\n\
             ### 12.3. Резервное копирование\n\n{filler}и оборв"
        );
        let page = PageText {
            text,
            truncated: true,
            verbatim: true,
            dropped_chars: Some(48_564),
            ..PageText::default()
        };
        let out = FetchUrl::default()
            .attached_result(&ctx, "https://example.com/spec.md", None, false, page)
            .await;
        let [ChatEffect::AddAttachment(att)] = out.effects.as_slice() else {
            panic!("no attachment effect: {:?}", out.effects);
        };
        let heading = "12.3. Резервное копирование";
        let tokens = ctx.attachment_cfg.page_tokens;
        let pages = att.page_count(tokens);
        let at = (1..=pages)
            .find(|&n| att.page(tokens, n).unwrap().contains("### 12.3."))
            .expect("the heading is on some page");
        assert!(at > 1, "the fixture must put the heading past page 1");
        let expected = ctx.loc.tf(
            "tool.fetch_url.result.cut_at_heading",
            &[
                ("heading", heading),
                ("page", &at.to_string()),
                ("pages", &pages.to_string()),
            ],
        );
        assert!(out.result.contains(&expected), "got: {}", out.result);
        assert!(
            out.result.contains(
                &ctx.loc
                    .tf("tool.fetch_url.result.cut_dropped", &[("n", "48564")])
            ),
            "got: {}",
            out.result
        );
        // The fenced shell comment came later in the fixture's first half and must not
        // win; the section named in the header is the real one.
        let header_note = ctx.loc.tf(
            "tool.fetch_url.attachment.truncated_heading",
            &[
                ("limit", &MAX_EXTRACT_CHARS.to_string()),
                ("heading", heading),
            ],
        );
        assert!(att.text.contains(&header_note), "{}", att.text);
        // A verbatim body is not described as extracted from HTML (F5).
        let verbatim = ctx.loc.tf(
            "tool.fetch_url.attachment.header_verbatim",
            &[("name", &att.name), ("url", "https://example.com/spec.md")],
        );
        assert!(att.text.starts_with(&verbatim), "{}", att.text);
    }

    /// An HTML page's remainder is never counted — extraction stops at the ceiling —
    /// so its note gives no figure rather than a guessed one; its header keeps the
    /// "extracted from HTML" line, which is true there.
    #[tokio::test]
    async fn an_html_cut_gives_no_remainder_figure() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let mut page = big_page(Some("Страница"));
        page.truncated = true;
        let out = FetchUrl::default()
            .attached_result(&ctx, "https://example.com/p", None, false, page)
            .await;
        let dropped = ctx.loc.t("tool.fetch_url.result.cut_dropped");
        let (dropped_head, _) = dropped.split_once("{n}").unwrap();
        assert!(!out.result.contains(dropped_head), "got: {}", out.result);
        let [ChatEffect::AddAttachment(att)] = out.effects.as_slice() else {
            panic!("no attachment effect: {:?}", out.effects);
        };
        let html = ctx.loc.tf(
            "tool.fetch_url.attachment.header",
            &[("name", "Страница"), ("url", "https://example.com/p")],
        );
        assert!(att.text.starts_with(&html), "{}", att.text);
    }

    /// What counts as the heading a cut text stops in: Markdown ATX headings, outside
    /// fences, at most three spaces in; not `#[derive]`, not `#tag`, not an empty `#`.
    #[test]
    fn last_heading_reads_markdown_headings_outside_fences() {
        let last = |t: &str| last_heading(t).map(|(_, h)| h);
        assert_eq!(last("# A\ntext\n## B ##\nmore"), Some("B".into()));
        assert_eq!(last("## A\n```sh\n# comment\n```\n"), Some("A".into()));
        assert_eq!(last("## A\n~~~\n# comment\n~~~\n"), Some("A".into()));
        // A fence opened with backticks is not closed by tildes.
        assert_eq!(last("## A\n```\n~~~\n# still code\n"), Some("A".into()));
        assert_eq!(last("#[derive(Debug)]\n#tag\n#\n####### seven"), None);
        assert_eq!(
            last("    # indented code\n   ### three spaces"),
            Some("three spaces".into())
        );
        assert_eq!(last("plain prose, no structure"), None);
        // The offset is the heading line's own start.
        let text = "intro\n## Here\nbody";
        let (at, _) = last_heading(text).unwrap();
        assert!(text[at..].starts_with("## Here"));
        // A paragraph-long "heading" is clipped.
        let long = format!("# {}", "слово ".repeat(60));
        let got = last(&long).unwrap();
        assert!(got.chars().count() <= 121 && got.ends_with('…'), "{got}");
    }

    /// A verbatim body over the ceiling knows how much it lost; an HTML body does not
    /// pretend to (F3, F5).
    #[test]
    fn a_verbatim_body_reports_what_the_cut_left_out() {
        let body = "x".repeat(MAX_EXTRACT_CHARS + 1234);
        let page = body_to_text("text/plain; charset=utf-8", &body).unwrap();
        assert!(page.verbatim && page.truncated);
        assert_eq!(page.dropped_chars, Some(1234));
        assert_eq!(page.text.chars().count(), MAX_EXTRACT_CHARS);

        let small = body_to_text("text/plain", "# Title\n\ntext").unwrap();
        assert!(small.verbatim && !small.truncated && small.dropped_chars.is_none());

        // A Markdown page is text too: on the HTML path it had no `<p>` to extract
        // and came back as "no readable text".
        for ct in [
            "text/markdown; charset=utf-8",
            "text/x-markdown",
            "text/csv",
        ] {
            let md = body_to_text(ct, "# Title\n\nA paragraph.\n\n## Next\n\nMore.")
                .unwrap_or_else(|| panic!("{ct}: no text"));
            assert!(md.verbatim, "{ct}");
            assert!(md.text.contains("## Next"), "{ct}: {}", md.text);
        }

        let html = body_to_text(
            "text/html",
            "<html><body><p>Достаточно длинный абзац, чтобы пройти порог отсева.</p></body></html>",
        )
        .unwrap();
        assert!(!html.verbatim && html.dropped_chars.is_none());
    }

    /// A page within the budget keeps the previous behaviour: the text itself,
    /// in the result, with no attachment.
    #[tokio::test]
    async fn a_small_page_comes_back_in_the_result() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let page = PageText {
            text: "Небольшая страница целиком.".into(),
            title: Some("t".into()),
            ..PageText::default()
        };
        let out = FetchUrl::default()
            .inline_result(&ctx, "https://example.com", None, false, &page)
            .await;
        assert!(
            out.result.contains("Небольшая страница целиком."),
            "got: {}",
            out.result
        );
    }

    /// One fixture per shape the corpus measured (docs/research/page-attachment-name.md
    /// §2), each pinning the step of the rule (§4) that has to name it.
    #[test]
    fn the_attachment_is_named_by_what_a_second_field_confirms() {
        let name = |head: &str, body: &str| {
            let page = body_to_text(
                "text/html",
                &format!(
                    "<html><head>{head}</head><body>{body}\
                     <p>Достаточно длинный абзац, чтобы пройти порог отсева фрагментов.</p>\
                     </body></html>"
                ),
            )
            .unwrap();
            assert!(!page.truncated);
            page.title
        };
        // (shape, <head>, <body>, the name)
        let cases: &[(&str, &str, &str, &str)] = &[
            (
                "og:title, without the site suffix it shares with the title",
                r#"<title>Moon - Wikipedia</title><meta property="og:title" content="Moon - Wikipedia">"#,
                "<h1>Moon</h1>",
                "Moon",
            ),
            (
                "og:title over a blog's banner <h1>",
                r#"<title>Any Nix package, live in your browser</title>
                   <meta property="og:title" content="Any Nix package, live in your browser">"#,
                "<h1>Simon Willison’s Weblog</h1>",
                "Any Nix package, live in your browser",
            ),
            (
                "an og:title that is the title's site segment is the site",
                r#"<title>Pods | Kubernetes</title><meta property="og:title" content="Kubernetes">"#,
                "<h1>Pods</h1>",
                "Pods",
            ),
            (
                "an og:title that is og:site_name is the site",
                r#"<title>Pods | Kubernetes</title><meta property="og:title" content="Kubernetes Docs">
                   <meta property="og:site_name" content="Kubernetes Docs">"#,
                "<h1>Pods</h1>",
                "Pods",
            ),
            (
                "an <h1> the title begins with",
                "<title>Array.prototype.map() - JavaScript | MDN</title>",
                "<h1>Array.prototype.map()</h1>",
                "Array.prototype.map()",
            ),
            (
                "an <h1> agrees ignoring case and its permalink mark, and reads as the title spells it",
                "<title>Getting Started - Guide | Vite</title>",
                "<h1>Getting started <a class=\"header-anchor\" href=\"#getting-started\">\u{200b}</a></h1>",
                "Getting Started",
            ),
            (
                "the post's <h1> after a banner <h1>",
                "<title>Learning a few things about running SQLite</title>",
                "<h1>Julia Evans</h1><h1>Learning a few things about running SQLite</h1>",
                "Learning a few things about running SQLite",
            ),
            (
                "an <h1> that is only a word's start does not agree",
                "<title>Google Search Central | Blog</title>",
                "<h1>Go</h1>",
                "Google Search Central",
            ),
            (
                "the archive's banner <h1> over an article-first title (the reported page)",
                "<title>Попьем чайку? Петр 'roxton' Семилетов | Архив журнала «Мой компьютер» №32/203 `2002</title>",
                "<h1>АРХИВ СТАТЕЙ ЖУРНАЛА «МОЙ КОМПЬЮТЕР» ЗА 2002 ГОД</h1>",
                "Попьем чайку? Петр 'roxton' Семилетов",
            ),
            (
                "mdBook: the banner <h1> is the title's own suffix",
                "<title>What is Ownership? - The Rust Programming Language</title>",
                "<h1 class=\"menu-title\">The Rust Programming Language</h1>",
                "What is Ownership?",
            ),
            (
                "rustdoc: the <h1> carries a button's text",
                "<title>serde - Rust</title>",
                "<h1>Crate <span>serde</span><button>Copy item path</button></h1>",
                "serde",
            ),
            (
                "a page's own name keeps its separator",
                "<title>The Qualcomm DSP Driver - Unexpectedly Excavating an Exploit - Project Zero</title>",
                "",
                "The Qualcomm DSP Driver - Unexpectedly Excavating an Exploit",
            ),
            (
                "docs.vlang.io: a title that is the site alone, over the page's <h1>",
                "<title>V Documentation</title>",
                "<h1>Memory management<a href=\"#memory-management\">¶</a></h1>",
                "Memory management",
            ),
            (
                "no <h1> and no separator: the title, collapsed",
                "<title>  Memory\n management  </title>",
                "",
                "Memory management",
            ),
        ];
        for (shape, head, body, expected) in cases {
            assert_eq!(name(head, body).as_deref(), Some(*expected), "{shape}");
        }
    }

    #[test]
    fn a_title_is_split_at_its_last_spaced_separator() {
        for sep in [
            " | ", " — ", " – ", " - ", " -> ", " :: ", " · ", " » ", " / ", " : ",
        ] {
            let head = format!("Page{sep}Section");
            let title = format!("{head}{sep}Site");
            assert_eq!(
                split_last_segment(&title),
                Some((head.as_str(), "Site")),
                "{sep:?}"
            );
        }
        // Unspaced, a separator belongs to a name: "PostgreSQL: Documentation", a path.
        assert_eq!(
            split_last_segment("PostgreSQL: Documentation: 18: SELECT"),
            None
        );
        assert_eq!(split_last_segment("Lib.ru/Classics|poems-A-Z"), None);
    }

    /// The reported defect through the tool (docs/research/page-attachment-name.md §1):
    /// two articles of one windows-1251 archive, each under the archive's banner `<h1>`,
    /// attached as the banner and as the banner plus a file name. Each is named by its
    /// article now, and the second needs no URL segment to differ.
    #[tokio::test]
    async fn two_articles_of_one_archive_are_named_by_their_articles() {
        let archive_page = |article: &str| -> Vec<u8> {
            let prose =
                "Абзац статьи из архива журнала, достаточно длинный для порога. ".repeat(1500);
            let html = format!(
                "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1251\">\
                 <title>{article} | Архив журнала «Мой компьютер» №32/203 `2002</title></head>\
                 <body><h1>АРХИВ СТАТЕЙ ЖУРНАЛА «МОЙ КОМПЬЮТЕР» ЗА 2002 ГОД</h1><p>{prose}</p></body></html>"
            );
            let body = encoding_rs::WINDOWS_1251.encode(&html).0;
            let mut out = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\
                 Connection: close\r\n\r\n",
                body.len()
            )
            .into_bytes();
            out.extend_from_slice(&body);
            out
        };
        let articles = [
            "Попьем чайку? Петр 'roxton' Семилетов",
            "ВодВАRить на место. Геннадий Осипенко",
        ];
        let (base, _h) =
            crate::features::image_fetch::stub::serve(articles.map(archive_page).to_vec());
        let tool = FetchUrl::new(AddressPolicy::Unrestricted);
        let (_d, mut ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let mut names = Vec::new();
        for path in ["mycomp/mid203/aid5.html", "mycomp/mid199/aid2.html"] {
            let url = format!("{base}/{path}");
            let out = tool
                .invoke(&ctx, serde_json::json!({"url": url, "summarize": false}))
                .await
                .unwrap();
            let [ChatEffect::AddAttachment(att)] = out.effects.as_slice() else {
                panic!("not attached: {}", out.result);
            };
            names.push(att.name.clone());
            ctx.attachments = Arc::from(vec![(**att).clone()]);
        }
        assert_eq!(names, articles);
    }

    #[test]
    fn a_name_already_taken_by_another_page_gets_the_url_segment() {
        use crate::entities::attachment::AttachMode;
        let mine = "https://docs.example.io/memory-management.html";
        let other = Attachment::new(
            "V Documentation",
            "https://docs.example.io/concurrency.html",
            "x".into(),
            1,
            AttachMode::ByReference,
        );
        assert_eq!(
            unique_name("V Documentation", mine, std::slice::from_ref(&other)),
            "V Documentation — memory-management.html"
        );
        // Re-fetching the *same* page keeps the plain name: the attachment it
        // replaces is its own, so nothing collides and the name stays stable.
        let same = Attachment::new(
            "V Documentation",
            mine,
            "x".into(),
            1,
            AttachMode::ByReference,
        );
        assert_eq!(
            unique_name("V Documentation", mine, &[same]),
            "V Documentation"
        );
        assert_eq!(unique_name("V Documentation", mine, &[]), "V Documentation");
    }

    #[test]
    fn url_segment_falls_back_to_the_host() {
        assert_eq!(
            url_segment("https://a.io/x/y.html?q=1").as_deref(),
            Some("y.html")
        );
        assert_eq!(url_segment("https://a.io/").as_deref(), Some("a.io"));
        assert_eq!(url_segment("https://a.io").as_deref(), Some("a.io"));
    }

    #[test]
    fn fetch_url_description_and_summary_system_localized() {
        // The description and the summarization system prompt are localized (en≠ru,
        // no Cyrillic). §3.5 docs/history/i18n.md.
        use crate::shared::i18n::{Lang, locale};
        let tool = FetchUrl::default();
        let (ru, en) = (locale(Lang::Ru), locale(Lang::En));
        let no_cyr = |s: &str| {
            !s.chars()
                .any(|c| ('а'..='я').contains(&c) || ('А'..='Я').contains(&c))
        };
        assert_ne!(tool.description(ru), tool.description(en));
        assert!(no_cyr(&tool.description(en)));
        assert_ne!(
            ru.t("tool.fetch_url.summarize.system"),
            en.t("tool.fetch_url.summarize.system")
        );
        assert!(no_cyr(en.t("tool.fetch_url.summarize.system")));
    }

    #[tokio::test]
    async fn rejects_non_http_url() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        assert!(
            FetchUrl::default()
                .invoke(&ctx, serde_json::json!({"url": "ftp://x/y"}))
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn rejects_empty_url() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        assert!(
            FetchUrl::default()
                .invoke(&ctx, serde_json::json!({"url": "  "}))
                .await
                .is_err()
        );
    }

    /// Summarization builds a request with no tools, with a token limit, and includes
    /// focus in the task. Checks the pure function `summarize_text` directly.
    #[tokio::test]
    async fn summarize_builds_single_turn_request_with_focus() {
        let backend = Arc::new(CapturingBackend {
            last: Mutex::new(None),
            reply: "краткое содержание".into(),
        });
        let (_d, ctx) = ctx_with_engine(backend.clone());
        let summary = summarize_text(
            &ctx,
            "https://example.com",
            Some("какова цена?"),
            "Длинный текст страницы про цены и условия.",
        )
        .await
        .unwrap();
        assert_eq!(summary.text, "краткое содержание");
        assert!(summary.prefill.is_none(), "no usage chunk, no timing");

        let req = backend.last.lock().unwrap().take().unwrap();
        assert!(req.system.is_some());
        assert_eq!(req.messages.len(), 1);
        assert!(req.tools.is_empty(), "no tools (a nesting ban)");
        assert!(req.sampling.max_tokens.unwrap() <= SUMMARY_MAX_TOKENS);
        assert_eq!(
            req.sampling.reasoning_budget,
            Some(0),
            "reasoning muted, the title's shape (page-summary-usage §3.3)"
        );
        // focus made it into the task.
        let msg = format!("{:?}", req.messages[0]);
        assert!(msg.contains("какова цена"), "focus in the task: {msg}");
    }

    /// An engine whose streams report how many are open at once, each one
    /// slow enough that two summaries could overlap if nothing stopped them.
    struct CountingBackend {
        in_flight: Arc<std::sync::atomic::AtomicUsize>,
        max_in_flight: Arc<std::sync::atomic::AtomicUsize>,
    }

    struct Open(Arc<std::sync::atomic::AtomicUsize>);

    impl Drop for Open {
        fn drop(&mut self) {
            self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
        }
    }

    #[async_trait::async_trait]
    impl EngineBackend for CountingBackend {
        async fn chat_stream(
            &self,
            _req: ChatRequest,
            _cancel: CancellationToken,
        ) -> Result<ChatStream> {
            use std::sync::atomic::Ordering::SeqCst;
            let open = self.in_flight.fetch_add(1, SeqCst) + 1;
            self.max_in_flight.fetch_max(open, SeqCst);
            let guard = Open(self.in_flight.clone());
            let s = async_stream::stream! {
                let _open = guard;
                tokio::time::sleep(Duration::from_millis(40)).await;
                yield ChatChunk::Text("summary".into());
                yield ChatChunk::Finished(FinishReason::Stop);
            };
            Ok(Box::pin(s))
        }
    }

    /// The summary's stream takes a permit of the turn's session budget and
    /// releases it with the stream (docs/research/concurrent-tools.md §4.5):
    /// with one session two summaries never overlap, and with no budget —
    /// a background task's context — both run at once.
    #[tokio::test]
    async fn summary_takes_a_session_permit_for_its_stream() {
        let counting = Arc::new(CountingBackend {
            in_flight: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            max_in_flight: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        });
        let (_d, mut ctx) = ctx_with_engine(counting.clone());
        let sessions = Arc::new(crate::shared::session_budget::SessionBudget::new(1, None));
        ctx.sessions = Some(sessions.clone());
        let (a, b) = tokio::join!(
            summarize_text(&ctx, "https://a.example", None, "text a"),
            summarize_text(&ctx, "https://b.example", None, "text b"),
        );
        assert_eq!(
            (a.unwrap().text, b.unwrap().text),
            ("summary".to_string(), "summary".to_string())
        );
        assert_eq!(
            counting
                .max_in_flight
                .load(std::sync::atomic::Ordering::SeqCst),
            1,
            "one session: the summaries streamed one after another"
        );
        assert_eq!(sessions.available_sessions(), 1, "the permit came back");

        ctx.sessions = None;
        counting
            .max_in_flight
            .store(0, std::sync::atomic::Ordering::SeqCst);
        let (a, b) = tokio::join!(
            summarize_text(&ctx, "https://a.example", None, "text a"),
            summarize_text(&ctx, "https://b.example", None, "text b"),
        );
        assert!(a.is_ok() && b.is_ok());
        assert_eq!(
            counting
                .max_in_flight
                .load(std::sync::atomic::Ordering::SeqCst),
            2,
            "no budget: nothing holds the second summary back"
        );
    }

    /// An engine whose one stream ends with the server's usage: an exact
    /// count far above any estimate of the short texts here, and the
    /// engine's timing of the prompt — the shape of a `llama-server` stream.
    struct UsageBackend;

    const EXACT: u32 = 50_000;

    #[async_trait::async_trait]
    impl EngineBackend for UsageBackend {
        async fn chat_stream(
            &self,
            _req: ChatRequest,
            _cancel: CancellationToken,
        ) -> Result<ChatStream> {
            let s = async_stream::stream! {
                yield ChatChunk::Text("summary".into());
                yield ChatChunk::Usage(crate::shared::api::contract::TokenUsage {
                    prompt_tokens: EXACT,
                    completion_tokens: 1,
                    reasoning_tokens: 0,
                    prefill: Some(Prefill {
                        tokens: EXACT,
                        ms: 1000,
                    }),
                });
                yield ChatChunk::Finished(FinishReason::Stop);
            };
            Ok(Box::pin(s))
        }
    }

    /// The summary records its exact count under its own kind
    /// (docs/research/page-summary-usage.md §3.1): the ratio the next
    /// summary prices with, and no other kind's — the turn's stays at 1.0.
    #[tokio::test]
    async fn summary_records_its_usage_under_its_own_kind() {
        use crate::shared::session_budget::{SessionBudget, Shape};
        let (_d, mut ctx) = ctx_with_engine(Arc::new(UsageBackend));
        let budget = Arc::new(SessionBudget::new(2, Some(100_000)));
        ctx.sessions = Some(budget.clone());
        let s = summarize_text(&ctx, "https://a.example", None, "text a")
            .await
            .unwrap();
        assert_eq!(s.text, "summary");
        assert!(budget.density(Shape::Summary) > 1.0, "{budget:?}");
        assert_eq!(budget.density(Shape::Turn), 1.0, "no other kind touched");
        assert_eq!(budget.in_flight(), 0, "the reservation came back");
    }

    /// The engine's timing of the summary's prompt rides the outcome on both
    /// paths (§3.2) — a page under the attachment budget and one over it —
    /// and only where a summary was made: `summarize=false` asks nothing of
    /// the engine, and an engine that sends no usage leaves `None`.
    #[tokio::test]
    async fn the_outcome_carries_the_summarys_sample() {
        let (_d, ctx) = ctx_with_engine(Arc::new(UsageBackend));
        let small = PageText {
            text: "A small page.".into(),
            ..PageText::default()
        };
        let inline = FetchUrl::default()
            .inline_result(&ctx, "https://example.com", None, true, &small)
            .await;
        assert_eq!(inline.prefill.map(|p| p.tokens), Some(EXACT));
        assert!(inline.result.contains("summary"), "{}", inline.result);
        let attached = FetchUrl::default()
            .attached_result(&ctx, "https://example.com", None, true, big_page(None))
            .await;
        assert_eq!(attached.prefill.map(|p| p.tokens), Some(EXACT));
        assert_eq!(attached.effects.len(), 1, "the page attached as before");

        let plain = FetchUrl::default()
            .inline_result(&ctx, "https://example.com", None, false, &small)
            .await;
        assert!(
            plain.prefill.is_none(),
            "no summary asked, nothing to report"
        );

        let (_d, ctx) = ctx_with_engine(Arc::new(CapturingBackend {
            last: Mutex::new(None),
            reply: "summary".into(),
        }));
        let no_usage = FetchUrl::default()
            .inline_result(&ctx, "https://example.com", None, true, &small)
            .await;
        assert!(no_usage.prefill.is_none(), "a stream without a usage chunk");
    }

    /// Under a shared KV pool the summary reserves its prompt plus its reply
    /// cap (docs/research/admission-by-budget.md §4.5): with two sessions
    /// over a pool two summaries do not fit in, they stream one after the
    /// other; over a roomy pool, together.
    #[tokio::test]
    async fn summary_reserves_room_in_a_shared_pool() {
        use crate::shared::session_budget::SessionBudget;
        let counting = Arc::new(CountingBackend {
            in_flight: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            max_in_flight: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        });
        let (_d, mut ctx) = ctx_with_engine(counting.clone());
        // Each reservation is at least the 768-token cap, so two exceed 1000.
        ctx.sessions = Some(Arc::new(SessionBudget::new(2, Some(1000))));
        let (a, b) = tokio::join!(
            summarize_text(&ctx, "https://a.example", None, "text a"),
            summarize_text(&ctx, "https://b.example", None, "text b"),
        );
        assert!(a.is_ok() && b.is_ok());
        assert_eq!(
            counting
                .max_in_flight
                .load(std::sync::atomic::Ordering::SeqCst),
            1,
            "two sessions, one pool too small for both: one at a time"
        );
        let budget = ctx.sessions.as_deref().unwrap();
        assert_eq!(
            (budget.in_flight(), budget.available_sessions()),
            (0, 2),
            "both reservations and both permits came back"
        );

        ctx.sessions = Some(Arc::new(SessionBudget::new(2, Some(100_000))));
        counting
            .max_in_flight
            .store(0, std::sync::atomic::Ordering::SeqCst);
        let (a, b) = tokio::join!(
            summarize_text(&ctx, "https://a.example", None, "text a"),
            summarize_text(&ctx, "https://b.example", None, "text b"),
        );
        assert!(a.is_ok() && b.is_ok());
        assert_eq!(
            counting
                .max_in_flight
                .load(std::sync::atomic::Ordering::SeqCst),
            2,
            "a pool with room for both: together"
        );
    }

    #[test]
    fn json_body_returned_as_is_not_extracted() {
        // A JSON API response (by Content-Type) is returned as-is — readability used to
        // return empty → "failed to extract readable text" (Steam appreviews).
        let body = r#"{"success":1,"query_summary":{"total_positive":200,"total_negative":30}}"#;
        let out = body_to_text("application/json; charset=utf-8", body)
            .unwrap()
            .text;
        assert!(out.contains("total_positive"), "got: {out}");
    }

    #[test]
    fn json_shaped_body_returned_when_content_type_missing() {
        // No Content-Type, but the body has a JSON shape (starts with `{`) → return as-is.
        let out = body_to_text("", r#"  {"a":1}"#).unwrap().text;
        assert!(out.contains("\"a\":1"), "got: {out}");
    }

    #[test]
    fn html_without_readable_text_yields_none() {
        // HTML with no readable text (only scripts) → nothing to extract.
        assert!(body_to_text("text/html", "<html><script>var x=1;</script></html>").is_none());
    }

    #[test]
    fn html_with_paragraph_is_extracted() {
        let out = body_to_text(
            "text/html; charset=utf-8",
            "<html><body><p>Реальный читаемый абзац страницы, достаточно длинный, \
             чтобы пройти порог отсева коротких фрагментов.</p></body></html>",
        )
        .unwrap()
        .text;
        assert!(out.contains("читаемый абзац"), "got: {out}");
    }

    /// The defect this closes (docs/research/page-charset.md §1): a windows-1251 page
    /// came back as U+FFFD, because `resp.text()` read its bytes as UTF-8 whatever they
    /// declared. Through the tool's own request path, in the two shapes the old path
    /// could not read at all — the encoding declared only in `<meta>`, and a body
    /// gzipped though nothing asked for it.
    #[tokio::test]
    async fn a_legacy_page_is_read_in_its_own_encoding() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let prose =
            "Попьем чайку? Текстовый редактор, написанный для себя, вырос в программу для всех.";
        let (base, _h) = crate::features::image_fetch::stub::serve(vec![
            crate::shared::http_text::testkit::legacy_page_response("Архив статей", prose),
        ]);
        let page = FetchUrl::new(AddressPolicy::Unrestricted)
            .fetch_text(&format!("{base}/mycomp/aid5.html"), ctx.loc)
            .await
            .unwrap();
        assert!(page.text.contains(prose), "{}", page.text);
        assert_eq!(page.title.as_deref(), Some("Архив статей"));
    }

    /// A body past the ceiling is refused **as it arrives** — the bound is the bytes
    /// read, not the `Content-Length` a server may omit or misstate — and the refusal
    /// says so rather than reading as a transport failure worth retrying
    /// (docs/research/safe-defaults.md N3). The cap is 32 MB, so the stub lies about a
    /// small body to exercise the header half, and sends more than it promised to
    /// exercise the streaming half.
    #[tokio::test]
    async fn a_page_past_the_ceiling_is_refused_and_says_so() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let huge = 40 * 1024 * 1024usize;
        let mut claimed = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {huge}\r\nConnection: close\r\n\r\n"
        )
        .into_bytes();
        claimed.extend(std::iter::repeat_n(b'a', 64));
        let (base, _h) = crate::features::image_fetch::stub::serve(vec![claimed]);
        let refusal = FetchUrl::new(AddressPolicy::Unrestricted)
            .fetch_text(&format!("{base}/huge.html"), ctx.loc)
            .await
            .err()
            .expect("a body past the ceiling must be refused");
        let refusal = format!("{refusal:#}");
        assert!(refusal.contains("32 MB"), "{refusal}");

        // The same page under the ceiling still reads, so the cap is what refused it.
        let body = "<html><head><title>Small</title></head><body><h1>Small</h1><p>This page is small enough to be read whole, and long enough to be readable text rather than a fragment the extractor discards.</p></body></html>";
        let ok = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        )
        .into_bytes();
        let (base, _h) = crate::features::image_fetch::stub::serve(vec![ok]);
        let page = FetchUrl::new(AddressPolicy::Unrestricted)
            .fetch_text(&format!("{base}/small.html"), ctx.loc)
            .await
            .unwrap();
        assert!(page.text.contains("small enough"), "{}", page.text);
    }

    /// The page from the chat that reported the defect (docs/research/page-charset.md
    /// §1), fetched the way the assistant fetched it: a windows-1251 page over the
    /// attachment budget, which had become an attachment named and filled with U+FFFD.
    /// Needs no key — only network.
    #[tokio::test]
    #[ignore = "requires network access"]
    async fn live_windows_1251_page_is_readable() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let url = "https://sector.biz.ua/mycomp/mid203/aid5.html";
        let out = FetchUrl::default()
            .invoke(&ctx, serde_json::json!({"url": url, "summarize": false}))
            .await
            .unwrap();
        let (name, text) = match out.effects.as_slice() {
            [ChatEffect::AddAttachment(att)] => (att.name.clone(), att.text.clone()),
            _ => (String::new(), out.result.clone()),
        };
        eprintln!(
            "--- fetch_url on {url}: attached as {name:?}, {} chars ---",
            text.chars().count()
        );
        assert!(
            text.contains("Попьем чайку"),
            "the article is missing: {text}"
        );
        assert!(
            !text.contains('\u{FFFD}') && !name.contains('\u{FFFD}'),
            "replacement characters are back: {name:?}"
        );
        // Named by the article, not by the banner `<h1>` every article of the archive
        // repeats (docs/research/page-attachment-name.md §1).
        assert_eq!(name, "Попьем чайку? Петр 'roxton' Семилетов");
    }

    /// A YouTube link used to be a dead end here — the watch page is a
    /// JavaScript shell, so readability extracted nothing and the answer was
    /// "failed to extract readable text". Now it hands back what the free paths
    /// know and points at `youtube_watch` (fork R6). Needs no key — only network.
    #[tokio::test]
    #[ignore = "requires network access"]
    async fn live_youtube_link_returns_metadata_not_a_dead_end() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let out = FetchUrl::default()
            .invoke(
                &ctx,
                serde_json::json!({"url": "https://youtu.be/dQw4w9WgXcQ"}),
            )
            .await
            .unwrap();
        eprintln!("--- fetch_url on a YouTube link ---\n{}", out.result);
        assert!(
            out.result.contains("Never Gonna Give You Up"),
            "the live watch page's title is missing: {}",
            out.result
        );
        assert!(
            out.result.contains(super::super::YOUTUBE_WATCH_ID),
            "the answer must point at the tool that can watch it: {}",
            out.result
        );
    }

    /// The page from the transcript that prompted this work
    /// (docs/history/fetch-url-fidelity.md). Two claims that only a live fetch
    /// can settle, because both depend on the real markup: the code examples
    /// come back (P1 — VitePress wraps them in a bare `div.language-v`, which
    /// prose extraction dropped), and a documentation page of this size arrives
    /// as an attachment rather than cut mid-word (P2). Needs no key — only network.
    #[tokio::test]
    #[ignore = "requires network access"]
    async fn live_documentation_page_keeps_its_code() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let out = FetchUrl::default()
            .invoke(
                &ctx,
                serde_json::json!({
                    "url": "https://docs.vlang.io/memory-management.html",
                    "summarize": false
                }),
            )
            .await
            .unwrap();

        // The text is wherever the size rule put it — that is the point of the
        // rule, so the test asks for the content, not for a particular branch.
        let attached = match out.effects.as_slice() {
            [ChatEffect::AddAttachment(a)] => Some(a.clone()),
            [] => None,
            other => panic!("unexpected effects: {other:?}"),
        };
        let text = attached
            .as_ref()
            .map(|a| a.text.clone())
            .unwrap_or_else(|| out.result.clone());
        eprintln!(
            "--- fetch_url on the V docs page: {} chars, attached={} ---",
            text.chars().count(),
            attached.is_some()
        );

        assert!(
            text.contains("fn (data &MyType) free()"),
            "the code example is missing — prose-only extraction is back: {text}"
        );
        assert!(text.contains("```"), "code is not fenced: {text}");
        assert!(
            text.contains("## Control") || text.contains("# Control"),
            "section headings are missing: {text}"
        );
        assert!(
            text.contains("Arena allocation is available"),
            "the prose is missing: {text}"
        );
        if let Some(att) = attached {
            let pages = att.page_count(ctx.attachment_cfg.page_tokens);
            eprintln!(
                "attached as {:?}, {pages} page(s), mode {:?}",
                att.name, att.mode
            );
            // Every page of the site shares one `<title>`; its `<h1>` is the page
            // (docs/research/page-attachment-name.md §1).
            assert_eq!(att.name, "Memory management");
            assert!(
                out.result.contains("attachment_read"),
                "the result must say how to reach the attached page: {}",
                out.result
            );
        }
    }

    /// A real network smoke (manual: `cargo test -- --ignored`).
    #[tokio::test]
    #[ignore = "requires network access"]
    async fn live_fetch_without_summarize() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let out = FetchUrl::default()
            .invoke(
                &ctx,
                serde_json::json!({"url": "https://example.com", "summarize": false}),
            )
            .await
            .unwrap();
        assert!(out.result.contains("Содержимое"), "got: {}", out.result);
    }

    /// The page behind docs/research/attachment-birth-turn.md, for real: under the old
    /// 400 000-character ceiling it lost §13–§17; under the new one it arrives whole,
    /// described as the text it is, and the result offers no search in its birth turn.
    #[tokio::test]
    #[ignore = "requires network access"]
    async fn live_the_spec_arrives_whole() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let url = "https://raw.githubusercontent.com/vshylov/mindfork-rs/main/spec.md";
        let out = FetchUrl::default()
            .invoke(&ctx, serde_json::json!({"url": url, "summarize": false}))
            .await
            .unwrap();
        let [ChatEffect::AddAttachment(att)] = out.effects.as_slice() else {
            panic!("not attached: {}", out.result);
        };
        eprintln!(
            "spec: {} chars, {} pages\n--- result ---\n{}",
            att.text.chars().count(),
            att.page_count(ctx.attachment_cfg.page_tokens),
            out.result
        );
        assert!(
            att.text.contains("## 17. Self-model"),
            "the last chapter is missing"
        );
        let limit = MAX_EXTRACT_CHARS.to_string();
        assert!(
            !out.result.contains(
                &ctx.loc
                    .tf("tool.fetch_url.result.truncated", &[("limit", &limit)])
            ),
            "{}",
            out.result
        );
        let verbatim = ctx.loc.tf(
            "tool.fetch_url.attachment.header_verbatim",
            &[("name", url), ("url", url)],
        );
        assert!(att.text.starts_with(&verbatim), "{}", &att.text[..400]);
        assert!(
            out.result
                .contains(super::super::attachment::search_route(&ctx)),
            "{}",
            out.result
        );
    }

    /// Two real pages over the new ceiling: a plain-text book (verbatim — the note
    /// counts what was left out, and there is no Markdown heading to name) and a long
    /// HTML book (extracted — a heading to name, no remainder figure). Both
    /// attachments open with the cut and end on the marker.
    #[tokio::test]
    #[ignore = "requires network access"]
    async fn live_pages_over_the_ceiling_say_where_they_end() {
        let (_d, ctx) = ctx_with_engine(Arc::new(MockBackend::scripted(vec![])));
        let limit = MAX_EXTRACT_CHARS.to_string();
        let marker = ctx
            .loc
            .tf("tool.fetch_url.attachment.cut_marker", &[("limit", &limit)]);
        let dropped = ctx.loc.t("tool.fetch_url.result.cut_dropped");
        let (dropped_head, _) = dropped.split_once("{n}").unwrap();
        let (heading_head, _) = ctx
            .loc
            .t("tool.fetch_url.result.cut_at_heading")
            .split_once("{heading}")
            .unwrap();
        for (url, verbatim) in [
            ("https://www.gutenberg.org/cache/epub/2600/pg2600.txt", true),
            ("https://doc.rust-lang.org/book/print.html", false),
        ] {
            let out = FetchUrl::default()
                .invoke(&ctx, serde_json::json!({"url": url, "summarize": false}))
                .await
                .unwrap();
            let [ChatEffect::AddAttachment(att)] = out.effects.as_slice() else {
                panic!("{url}: not attached: {}", out.result);
            };
            let tokens = ctx.attachment_cfg.page_tokens;
            let pages = att.page_count(tokens);
            let last = att.page(tokens, pages).unwrap();
            eprintln!(
                "{url}: {} chars, {pages} pages\n--- result ---\n{}\n--- header ---\n{}\n--- last page tail ---\n{}",
                att.text.chars().count(),
                out.result,
                att.text.lines().take(4).collect::<Vec<_>>().join("\n"),
                last.chars()
                    .rev()
                    .take(300)
                    .collect::<Vec<_>>()
                    .into_iter()
                    .rev()
                    .collect::<String>()
            );
            assert!(last.trim_end().ends_with(&marker), "{url}");
            assert!(
                out.result
                    .contains(ctx.loc.t("tool.fetch_url.result.cut_door")),
                "{url}"
            );
            assert_eq!(out.result.contains(dropped_head), verbatim, "{url}");
            if !verbatim {
                assert!(out.result.contains(heading_head), "{url}: no heading named");
            }
        }
    }
}

#[cfg(test)]
#[path = "fetch/tests/live.rs"]
mod live_tests;