mindfork 0.11.0

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok 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
//! Contract for the tool system (`features/tools`): the [`Tool`] trait, the
//! [`ToolContext`] snapshot, the [`ToolOutcome`] result with [`ChatEffect`] effects,
//! and the [`ToolRegistry`] registry. See spec §9.2, §6.3.
//!
//! Tools **don't** mutate `Chat` directly: mutating ones return `effects`, which the
//! orchestrator applies (sole owner of `Chat`, spec §4.4.2). Memory/knowledge tools
//! must filter by `ctx.profile_id` (isolation, a repository invariant, spec §9.5).

#[cfg(test)]
mod embed_roles_tests;

pub mod attachment;
pub mod calc;
pub mod chats;
pub mod code;
pub mod confirm;
pub mod control;
pub mod datetime;
pub mod dialogue;
pub mod fetch;
pub mod fs;
pub mod history;
pub mod introspection;
pub mod llm;
pub mod mcp;
pub mod meta;
pub mod notes;
pub mod present;
pub mod python;
pub mod rag;
mod reach;
pub mod self_model;
pub mod subagent;
pub mod web;
pub mod youtube;

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};
use std::time::Duration;

use anyhow::Result;
use chrono::{DateTime, Utc};
use uuid::Uuid;

use crate::entities::profile::ToolId;
use crate::entities::sampling::SamplingConfig;
use crate::entities::self_model::SelfModelParams;
use crate::shared::api::{Embedder, EngineBackend, ToolSchema};
use crate::shared::config::{AppConfig, CloudProvider, PythonMode};
use crate::shared::sandbox::WasmerSandbox;
use crate::shared::storage::Storage;

pub use introspection::{GET_SAMPLING_ID, SET_SAMPLING_ID};

/// Immutable snapshot of turn state (no shared locks). See spec §9.2.
#[derive(Clone)]
pub struct ToolContext {
    pub profile_id: Uuid,
    /// Id of the current chat (part of the turn snapshot). Scopes the attachment
    /// index — `attachment_search` never reaches another conversation's files.
    pub chat_id: Uuid,
    /// Snapshot of `Chat.system_message` at the start of the turn.
    pub system_message: String,
    /// Effective sampling (after the priority resolution, §8.3).
    pub effective_sampling: SamplingConfig,
    /// Timestamp of the last user message (if any).
    pub last_user_message_at: Option<DateTime<Utc>>,
    pub storage: Arc<Storage>,
    /// Chat engine (for `fetch_url`'s summarizer and the like).
    pub engine: Arc<dyn EngineBackend>,
    /// Embedding source (RAG); a dedicated server — see ADR 0002.
    pub embedder: Arc<dyn Embedder>,
    /// RAG chunking parameters from settings (`config.rag`, spec §9.3).
    pub chunk_params: rag::ChunkParams,
    /// Render/storage parameters for the "self-model" from settings
    /// (`config.self_model`). A snapshot of the model itself is **not** put into the
    /// context: SelfModel tools read/write fresh state directly through `storage`
    /// (to see edits made within the turn), while injecting the model into the
    /// prompt is a separate path in the orchestrator.
    pub self_model_params: SelfModelParams,
    /// Whether to show self-notes (`@self`) in the general `note_recall` (Tier 3,
    /// Path 2). From `config.notes.recall_includes_self`; `false` by default (self
    /// hidden).
    pub recall_includes_self: bool,
    /// Language of the **agent scaffold** for this turn (from `Profile.language`,
    /// axis A, docs/history/i18n.md). Text the model reads (the "self-model"
    /// scaffold, tool results) is localized through it. `&'static` — a built-in
    /// bundle.
    pub loc: &'static crate::shared::i18n::Locale,
    /// The TLD that hints the encoding detector on the user's own files — the
    /// interface language's (`text_decode::tld_hint`, docs/research/local-file-encoding.md
    /// fork F2c): a file belongs to its user, not to a profile's prompt language.
    pub file_hint: Option<&'static str>,
    /// Files attached to the chat (`/file attach`) — a turn snapshot, like
    /// `system_message`. `Arc` because [`ToolContext`] is `Clone` and an
    /// attachment's text can be hundreds of KB. Read by `attachment_read`; empty
    /// for background tasks (they have no chat). See spec §9.7.
    pub attachments: std::sync::Arc<[crate::entities::attachment::Attachment]>,
    /// Attachment budget and page size (`config.attachments`): the page size for
    /// `attachment_read`, and — for a tool that produces an attachment of its own
    /// — the same thresholds the orchestrator decides the mode with.
    pub attachment_cfg: crate::shared::config::AttachmentSettings,
    /// The compacted-away part of the conversation, rendered for reading back
    /// (`history_read`/`history_search`, spec §6.7). A turn snapshot like
    /// `attachments`, and for the same reason: the orchestrator stays the sole
    /// owner of `Chat`, and a roll that lands mid-turn must not change what this
    /// turn's tools describe — they have to agree with the summary block the
    /// model was actually shown. `None` when nothing is folded away (or
    /// compression is off), which is also when the two tools are not offered at
    /// all (see [`effective_tool_ids`]).
    pub history: Option<Arc<crate::features::compaction::HistoryView>>,
    /// Page size for `history_read`, in estimated tokens (`config.compaction`).
    pub history_page_tokens: usize,
    /// The *other* chats of the current profile — the whole world of
    /// `chat_search`/`chat_read` (spec §9.11). A turn snapshot like
    /// `attachments`, and the scope boundary in one place: the full-text index
    /// is profile-blind and includes the current chat, so whatever is absent
    /// from this list does not exist for either tool. Built already filtered
    /// (current profile, current chat excluded, hidden dropped), and empty
    /// when the pair is not in the turn's tool set or for background tasks.
    pub other_chats: std::sync::Arc<[chats::ChatRef]>,
    /// Whether an image returned by an MCP tool may be shown to the model
    /// (`config.tools.mcp_images`, fork F3 of docs/research/mcp-tool-images.md).
    /// Off means the result keeps its `[image content omitted]` placeholder — the
    /// server and its text results keep working, which is the point of the switch
    /// being separate from enabling the server.
    pub mcp_images: bool,
    /// Whether a `python_exec` call in this turn can reach the network
    /// (`config.tools.python_net_enabled`). The tool applies it; the confirmation popup
    /// **states** it, because network access and the files going in are the two halves of
    /// what the user is consenting to (docs/history/sandbox-file-exchange.md §12 T6). In **Local**
    /// mode it is always `true`, and that is not a default: the code runs on the machine
    /// with the user's own reach, and a popup saying otherwise would be a lie (§14 V5).
    pub python_net: bool,
    /// The Python mode this turn runs in — which folders a call reads and writes
    /// (`PythonMode::dirs`, §14 V2). A sub-agent builds its own pinned block from it.
    pub python_mode: crate::shared::config::PythonMode,
    /// Where this chat's change journal lives (`data/workspace/<chat-id>/`,
    /// spec §9.12). `None` — no project, or a background turn; the editing tools
    /// then refuse rather than change a file they cannot record the original of.
    pub workspace_journal: Option<std::path::PathBuf>,
    /// Where this chat's stored files live (`data/files/<chat-id>/`,
    /// docs/history/sandbox-file-exchange.md §11 S5): `python_exec` writes what the code saved to
    /// `/w/out` here. A sub-agent's or a background run's context is a clone of its
    /// parent turn's, so their files land in the parent's folder. `None` — a background
    /// task, which has no chat; the tool then keeps nothing and says so.
    pub files_dir: Option<std::path::PathBuf>,
    /// The chat's one numbered list as **this turn** numbers it (fork F12,
    /// docs/history/sandbox-file-exchange.md §12 T2): what the pinned block told the model
    /// it may name, re-derived every round but carrying the `#N` and the `/w/in` name it
    /// promised. `python_exec` resolves `files` against this and nothing else — deriving
    /// it again here would renumber the list under a model that is still reading the
    /// block. Empty when the turn stages no files.
    pub inputs: std::sync::Arc<[crate::features::chat_inputs::ChatInput]>,
    /// The chat's stored files as of this round — a turn snapshot like `attachments`,
    /// mirrored from `AddChatFile` every round, so a turn's second call versions its
    /// names against the first's (§11 S5).
    pub files: std::sync::Arc<[crate::entities::chat_file::ChatFile]>,
    /// The images the chat's messages carry, prepared as the model was shown them — what
    /// `python_exec` stages into `/w/in` when a call names one (§12 T4). Built **only**
    /// when the turn offers the tool in Wasmer mode: with it off, which is the default, a
    /// chat's images are not copied into a context with no use for them. Empty otherwise.
    pub images: std::sync::Arc<[crate::entities::message_image::MessageImage]>,
    /// Whether this turn can hand the chat's files to the code: `python_exec` offered, in
    /// the Wasmer mode that has a job directory to copy them into
    /// (docs/history/sandbox-file-exchange.md §12 T5). Decided once per turn by the orchestrator
    /// and carried here so a sub-agent's own request repeats the decision rather than
    /// guessing it (§12 T13).
    pub stages_files: bool,
    /// The code project attached to this chat (`/project attach`, spec §9.12),
    /// as of the start of the turn. `None` — no project, and then the `code_*`
    /// tools are not offered at all (see [`effective_tool_ids`]); they refuse
    /// rather than widen to the file system, which is the opposite of what
    /// `fs_read` does without `tools.fs_root`.
    pub workspace: Option<crate::entities::workspace::Workspace>,
    /// Command-execution limits and the project round budget
    /// (`config.workspace`, spec §9.12). A per-turn snapshot like every other
    /// config here, so a settings edit mid-turn cannot change the timeout a
    /// running command was started with.
    pub workspace_cfg: crate::shared::config::WorkspaceSettings,
    /// See [`ToolParams::named_secrets`]: the variables a workspace command does not
    /// inherit, because the model may have edited what that command runs.
    pub named_secrets: std::sync::Arc<[String]>,
    /// Cancellation token for the turn (user Esc / background-task timeout): a
    /// long-running tool (MCP `tools/call`, network) must break on it rather than
    /// block cancellation. The agentic loop additionally wraps `invoke` in a
    /// `select!` with the same token — a safety net for tools that don't read the
    /// token. See docs/research/plugin-system.md §4.4 ("Cancellation").
    pub cancel: tokio_util::sync::CancellationToken,
    /// The turn's language-model name — the same single `effective_model_name`
    /// read that names the live bubble's header and the stored
    /// `MessageMetadata.model`, so `get_llm_name` cannot disagree with either
    /// (spec §9.14). `None` — the engine does not say (an external server with
    /// no typed name and no discovery answer). Deliberately **not** asked of
    /// `ctx.engine` from inside a tool: the orchestrator-side resolver owns the
    /// typed-name-wins precedence.
    pub model_name: Option<String>,
    /// The turn's engine mode (`config.engine.mode` snapshot) — the context
    /// half of `get_llm_name`'s answer and of an `llm_history` record.
    pub engine_mode: crate::shared::config::ServerMode,
    /// The turn's session budget (the engine section's `sessions`, spec §11.6)
    /// — the same budget the turn's loops stream under. A tool that makes an
    /// engine request of its own (`fetch_url`'s page summary) takes a permit
    /// and a token reservation around that stream and around nothing else, so
    /// the request counts like every other stream of the turn
    /// (docs/research/concurrent-tools.md §4.5; the reservation —
    /// docs/research/admission-by-budget.md §4.5).
    pub sessions: Option<Arc<crate::shared::session_budget::SessionBudget>>,
    /// The turn is one of the app's own background tasks (reflection, a
    /// consolidation): a request a tool makes takes the budget's **silent
    /// lane** — one such stream at a time beside the interactive ones —
    /// rather than an interactive permit (docs/research/silent-tasks-budget.md
    /// §4.2). `false` on a user's turn and on every run.
    pub silent_lane: bool,
}

/// Long-lived shared tool dependencies (an `Arc` bundle; changes on server
/// restart, not turn to turn). Gathered into one block so a new dependency doesn't
/// touch every [`ToolContext`] build site. See docs/history/refactoring-solid.md §3.
#[derive(Clone)]
pub struct ToolDeps {
    pub storage: Arc<Storage>,
    pub engine: Arc<dyn EngineBackend>,
    pub embedder: Arc<dyn Embedder>,
}

/// Tool parameters from config (a per-turn snapshot). The single place that maps
/// `AppConfig` → tool parameters — [`ToolParams::from_config`].
#[derive(Clone)]
pub struct ToolParams {
    pub chunk_params: rag::ChunkParams,
    pub self_model_params: SelfModelParams,
    pub recall_includes_self: bool,
    /// Attachment budget and page size (`config.attachments`). A tool that
    /// produces an attachment of its own needs the same numbers the orchestrator
    /// uses, or it would describe to the model something other than what gets
    /// stored.
    pub attachments: crate::shared::config::AttachmentSettings,
    /// Page size for `history_read` (`config.compaction.page_tokens`). Only the
    /// page size, not the whole `CompactionSettings`: whether to compact and
    /// against what window are decisions already taken by the time a tool runs,
    /// and the turn snapshot encodes their outcome.
    pub history_page_tokens: usize,
    /// Whether an MCP tool's image blocks may reach the model
    /// (`config.tools.mcp_images`). See [`ToolContext::mcp_images`].
    pub mcp_images: bool,
    /// Whether the Python sandbox has the network this turn
    /// (`config.tools.python_net_enabled`, or always in Local mode).
    /// See [`ToolContext::python_net`].
    pub python_net: bool,
    /// The Python mode (`config.tools.python_mode`). See [`ToolContext::python_mode`].
    pub python_mode: crate::shared::config::PythonMode,
    /// Command-execution limits for the code workspace (`config.workspace`).
    /// See [`ToolContext::workspace_cfg`].
    pub workspace: crate::shared::config::WorkspaceSettings,
    /// The encoding detector's hint for local files. See [`ToolContext::file_hint`].
    pub file_hint: Option<&'static str>,
    /// See [`ToolConfig::named_secrets`] — the workspace commands' half of it, since the
    /// model may have edited the build script they run.
    pub named_secrets: std::sync::Arc<[String]>,
}

impl ToolParams {
    /// Snapshots tool parameters from the application configuration.
    pub fn from_config(cfg: &AppConfig) -> Self {
        Self {
            chunk_params: rag::ChunkParams::from_settings(&cfg.rag),
            self_model_params: SelfModelParams::from_settings(&cfg.self_model),
            recall_includes_self: cfg.notes.recall_includes_self,
            attachments: cfg.attachments,
            history_page_tokens: cfg.compaction.page_tokens,
            mcp_images: cfg.tools.mcp_images,
            // Local has no network switch to honour: the code reaches what the user
            // reaches, so "on" is what the popup must say there (§14 V5).
            python_net: cfg.tools.python_net_enabled
                || matches!(
                    cfg.tools.python_mode,
                    crate::shared::config::PythonMode::Local
                ),
            python_mode: cfg.tools.python_mode,
            workspace: cfg.workspace,
            file_hint: crate::shared::text_decode::tld_hint(cfg.interface.language),
            named_secrets: crate::shared::config::named_key_env_vars(cfg).into(),
        }
    }
}

/// Turn snapshot: what a tool sees about the current chat (identity + `Chat` snapshot).
pub struct TurnInfo {
    pub profile_id: Uuid,
    pub chat_id: Uuid,
    pub system_message: String,
    pub effective_sampling: SamplingConfig,
    pub last_user_message_at: Option<DateTime<Utc>>,
    /// Files attached to the chat (a `Chat` snapshot; empty for background tasks).
    pub attachments: std::sync::Arc<[crate::entities::attachment::Attachment]>,
    /// The compacted-away part of the conversation, rendered (a `Chat` snapshot;
    /// `None` when nothing is folded, and for background tasks — they have no
    /// chat). See [`ToolContext::history`].
    pub history: Option<Arc<crate::features::compaction::HistoryView>>,
    /// The other chats of the profile, pre-scoped (empty for background tasks
    /// and when the cross-chat tools are not offered). See
    /// [`ToolContext::other_chats`].
    pub other_chats: std::sync::Arc<[chats::ChatRef]>,
    /// The chat's attached code project (spec §9.12). See
    /// [`ToolContext::workspace`]; `None` for background turns, which have no
    /// chat and therefore no project.
    pub workspace: Option<crate::entities::workspace::Workspace>,
    /// This chat's change-journal directory. See
    /// [`ToolContext::workspace_journal`].
    pub workspace_journal: Option<std::path::PathBuf>,
    /// This chat's stored-files folder. See [`ToolContext::files_dir`].
    pub files_dir: Option<std::path::PathBuf>,
    /// The chat's stored files (a `Chat` snapshot). See [`ToolContext::files`].
    pub files: std::sync::Arc<[crate::entities::chat_file::ChatFile]>,
    /// The turn's numbered list — see [`ToolContext::inputs`].
    pub inputs: std::sync::Arc<[crate::features::chat_inputs::ChatInput]>,
    /// The images the chat's messages carry (a `Chat` snapshot, and only when the turn
    /// offers `python_exec` in Wasmer mode). See [`ToolContext::images`].
    pub images: std::sync::Arc<[crate::entities::message_image::MessageImage]>,
    /// Whether this turn can stage the chat's files into the sandbox. See
    /// [`ToolContext::stages_files`].
    pub stages_files: bool,
    /// Language of the turn's agent scaffold (from `Profile.language`, axis A).
    pub lang: crate::shared::i18n::Lang,
    /// Cancellation token for the turn (a clone of the generation task's /
    /// background loop's token).
    pub cancel: tokio_util::sync::CancellationToken,
    /// The turn's language-model name. See [`ToolContext::model_name`].
    pub model_name: Option<String>,
    /// The turn's engine mode. See [`ToolContext::engine_mode`].
    pub engine_mode: crate::shared::config::ServerMode,
    /// The turn's session budget. See [`ToolContext::sessions`].
    pub sessions: Option<Arc<crate::shared::session_budget::SessionBudget>>,
    /// Which lane of the budget the turn streams on. See
    /// [`ToolContext::silent_lane`].
    pub silent_lane: bool,
}

impl ToolContext {
    /// Unpacks the building blocks into the former flat fields. The flat shape is
    /// kept deliberately — tool code (`ctx.storage`, `ctx.chunk_params`, …) doesn't
    /// change. See docs/history/refactoring-solid.md §3.
    pub fn new(deps: ToolDeps, params: ToolParams, turn: TurnInfo) -> Self {
        Self {
            profile_id: turn.profile_id,
            chat_id: turn.chat_id,
            system_message: turn.system_message,
            effective_sampling: turn.effective_sampling,
            last_user_message_at: turn.last_user_message_at,
            attachments: turn.attachments,
            attachment_cfg: params.attachments,
            history: turn.history,
            history_page_tokens: params.history_page_tokens,
            other_chats: turn.other_chats,
            workspace: turn.workspace,
            workspace_journal: turn.workspace_journal,
            files_dir: turn.files_dir,
            files: turn.files,
            inputs: turn.inputs,
            images: turn.images,
            stages_files: turn.stages_files,
            workspace_cfg: params.workspace,
            named_secrets: params.named_secrets,
            mcp_images: params.mcp_images,
            python_net: params.python_net,
            python_mode: params.python_mode,
            storage: deps.storage,
            engine: deps.engine,
            embedder: deps.embedder,
            chunk_params: params.chunk_params,
            self_model_params: params.self_model_params,
            recall_includes_self: params.recall_includes_self,
            loc: crate::shared::i18n::locale(turn.lang),
            file_hint: params.file_hint,
            cancel: turn.cancel,
            model_name: turn.model_name,
            engine_mode: turn.engine_mode,
            sessions: turn.sessions,
            silent_lane: turn.silent_lane,
        }
    }

    /// Re-derives [`Self::inputs`] from the context's own snapshots, carrying the `#N` and
    /// the `/w/in` name the turn has already promised (fork F12,
    /// docs/history/sandbox-file-exchange.md §12 T2–T3).
    ///
    /// The orchestrator calls this once a round, after mirroring the round's effects into
    /// `attachments` and `files`; a test that sets those snapshots by hand calls it for the
    /// same reason. Unconditional — the caller decides whether this turn has a list at all.
    pub fn sync_inputs(&mut self) {
        let dir = self.files_dir.clone().unwrap_or_default();
        self.inputs = crate::features::chat_inputs::reconcile(
            &self.inputs,
            &self.attachments,
            &self.files,
            &self.images.iter().collect::<Vec<_>>(),
            &dir,
        )
        .into();
    }
}

/// The JSON schema of a **search tool**: a required `query` plus an optional
/// `top_k`.
///
/// Shared by `attachment_search` and `history_search`, which take the same
/// arguments for the same reason — one names *where* to look, a reader then
/// fetches it. One definition so the two contracts cannot drift apart, the rule
/// this codebase already applies to the FTS escaper.
///
/// The two bundle keys are passed **whole** rather than built from a prefix:
/// a key assembled with `format!` is invisible to the i18n gates
/// (`all_bundle_key_references_in_code_exist` / `bundle_keys_are_not_dead`),
/// which is exactly why the dynamic `ui.tool.label.*` family needs a gate test
/// of its own. Keeping the literals at the call site also shows, in the tool's
/// own file, which text it presents.
pub(crate) fn search_parameters(
    loc: &crate::shared::i18n::Locale,
    query_key: &str,
    top_k_key: &str,
) -> serde_json::Value {
    serde_json::json!({
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": loc.t(query_key)
            },
            "top_k": {
                "type": "integer",
                "minimum": 1,
                "description": loc.t(top_k_key)
            }
        },
        "required": ["query"]
    })
}

/// The JSON schema of a **paged reader**: a required string naming the target
/// (an attachment for `attachment_read`, a conversation for `chat_read`) plus
/// an optional 1-based `page`.
///
/// Shared for the same reason [`search_parameters`] is shared by the search
/// half of each pair: one definition, so the reader contracts cannot drift
/// apart. The bundle keys are passed whole (the i18n-gate rule above).
pub(crate) fn paged_read_parameters(
    loc: &crate::shared::i18n::Locale,
    target: &str,
    target_key: &str,
    page_key: &str,
) -> serde_json::Value {
    let mut properties = serde_json::Map::new();
    properties.insert(
        target.to_string(),
        serde_json::json!({
            "type": "string",
            "description": loc.t(target_key)
        }),
    );
    properties.insert(
        "page".to_string(),
        serde_json::json!({
            "type": "integer",
            "minimum": 1,
            "description": loc.t(page_key)
        }),
    );
    serde_json::json!({
        "type": "object",
        "properties": properties,
        "required": [target]
    })
}

/// Reads the arguments [`search_parameters`] describes: a trimmed, non-empty
/// `query` and `top_k` (falling back to `default_k`).
///
/// An empty query is a usage error rather than an empty result — the tool was
/// called wrong, and saying so is what lets the next call succeed. `err_key`
/// names the tool's own message.
pub(crate) fn search_args<'a>(
    args: &'a serde_json::Value,
    loc: &crate::shared::i18n::Locale,
    err_key: &str,
    default_k: usize,
) -> Result<(&'a str, usize)> {
    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .ok_or_else(|| anyhow::anyhow!(loc.t(err_key).to_string()))?;
    let k = args
        .get("top_k")
        .and_then(|v| v.as_u64())
        .map(|n| n as usize)
        .unwrap_or(default_k);
    Ok((query, k))
}

/// An effect that mutates `Chat`; returned by a tool, applied by the orchestrator.
#[derive(Debug, Clone, PartialEq)]
pub enum ChatEffect {
    /// Replace the chat's system message (takes effect from the next request build).
    SetSystemMessage(String),
    /// Replace the chat's sampling override (takes effect from the next turn).
    /// `Box`, since `SamplingConfig` is larger than the other variants (clippy
    /// `large_enum_variant`).
    SetSamplingOverride(Box<SamplingConfig>),
    /// Attach text the tool produced to the chat (spec §9.7), replacing any
    /// attachment with the same `source`. A video transcript is the first user
    /// (spec §9.9), and the variant is deliberately generic — it is the natural
    /// home for any later "this tool produced too much text to hand back inline".
    ///
    /// The attachment arrives **already built**, mode included: the tool has
    /// told the model what it did, and the object described has to be the object
    /// stored — down to the `id`, which is the key the background index is
    /// written under. The agentic loop additionally mirrors it into the turn's
    /// `ToolContext` snapshot, so `attachment_read` finds it in the very next
    /// round rather than only in the next turn (docs/history/youtube-transcript.md §3 F1).
    AddAttachment(Box<crate::entities::attachment::Attachment>),
    /// List a file `python_exec` stored in the chat's folder
    /// (docs/history/sandbox-file-exchange.md §11 S7). The bytes are already on disk — the tool
    /// wrote them where the listing points, as the code tools write their journal — so
    /// the effect only adds the listing, and the orchestrator stays `Chat`'s sole owner.
    /// The loop mirrors it into the turn's snapshot, as it does an attachment.
    AddChatFile(Box<crate::entities::chat_file::ChatFile>),
}

/// Result of a tool call: text for the model + effects for the orchestrator.
#[derive(Debug, Clone, PartialEq)]
pub struct ToolOutcome {
    pub result: String,
    pub effects: Vec<ChatEffect>,
    /// Images the tool produced, to be shown to the model alongside `result`
    /// (spec §9.10, docs/research/mcp-tool-images.md). Raw base64 + MIME as the tool
    /// handed them over; the orchestrator downscales, normalizes and caps them on the
    /// same path a user's `/image attach` takes.
    ///
    /// The field sits on the contract rather than inside the MCP branch (fork F5), so a
    /// built-in tool with a picture to return needed no rework: the MCP adapter fills it,
    /// and so does `python_exec` with the images its code saved
    /// (docs/history/sandbox-file-exchange.md §11 S8).
    pub images: Vec<ToolImage>,
    /// **This call changed the profile's stored memory** — the self-model or
    /// a note. Set by a memory writer on the success path that returns after
    /// its storage call; a refusal (a missing id, nothing to change) reports
    /// nothing. The silent loops read it to decide whether a stopped or quit
    /// task had acted on the window its spawn advanced
    /// (docs/research/acted-by-effect.md §3.1); the turn's loop ignores it.
    pub wrote: bool,
    /// **The engine's timing of a request this call made on its own** — the
    /// page summary's stream inside `fetch_url`, the one such request today:
    /// `llama-server`'s `timings` off its `Usage` chunk, `None` from every
    /// other provider and from a stream that ended short. A stream of the
    /// turn by spec §9.3.1, so the loop that called the tool folds it into
    /// the largest prefill sample it keeps for the slow-prefill note — the
    /// turn's into its usage, a silent loop's onto its landing
    /// (docs/research/page-summary-usage.md §3.2).
    pub prefill: Option<crate::shared::api::contract::Prefill>,
}

/// An image a tool returned: base64 payload plus the MIME type it declared.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolImage {
    pub mime: String,
    pub data: String,
    /// The line of the result that names this image's file, exactly as the tool wrote it
    /// — `python_exec`'s `files:` entry — or `None` for an image no line names (MCP's).
    ///
    /// **The tool does not say whether the image is shown**: only the loop knows that,
    /// once it has asked the engine whether it takes images and prepared the pixels, so
    /// the loop ends this line with what became of the image, and says it in a note of its
    /// own for an image without one. A tool that wrote "shown to you below" itself was
    /// contradicted by the loop's "not shown to you" on an engine without vision, in the
    /// same result (spec §9.10).
    pub entry: Option<String>,
}

impl ToolOutcome {
    /// A result with no effects (a pure tool).
    pub fn text(result: impl Into<String>) -> Self {
        Self {
            result: result.into(),
            effects: Vec::new(),
            images: Vec::new(),
            wrote: false,
            prefill: None,
        }
    }

    /// A result with effects (a mutating tool).
    pub fn with_effects(result: impl Into<String>, effects: Vec<ChatEffect>) -> Self {
        Self {
            result: result.into(),
            effects,
            images: Vec::new(),
            wrote: false,
            prefill: None,
        }
    }

    /// Attaches images the tool produced (builder-style).
    pub fn with_images(mut self, images: Vec<ToolImage>) -> Self {
        self.images = images;
        self
    }

    /// Says the call changed the profile's stored memory (builder-style; on
    /// the line that returns after the storage call succeeded).
    pub fn wrote(self) -> Self {
        self.wrote_if(true)
    }

    /// [`Self::wrote`] under a condition — a link or a citation that already
    /// existed changed nothing.
    pub fn wrote_if(mut self, wrote: bool) -> Self {
        self.wrote = wrote;
        self
    }

    /// Attaches the engine's timing of a request the call made on its own
    /// (builder-style; `None` leaves the outcome as it was).
    pub fn with_prefill(mut self, prefill: Option<crate::shared::api::contract::Prefill>) -> Self {
        self.prefill = prefill;
        self
    }
}

/// A tool executed by the client-side agentic loop. See spec §9.2.
#[async_trait::async_trait]
pub trait Tool: Send + Sync {
    /// Unique name (matches the function name in the OpenAI schema).
    fn id(&self) -> ToolId;
    /// Human-readable description for the model **in the agent-scaffold language**
    /// `loc` (axis A, docs/history/i18n.md). Tools not yet translated (Tier 2 rolls
    /// out by group) return Russian text regardless of `loc`.
    fn description(&self, loc: &crate::shared::i18n::Locale) -> String;
    /// JSON Schema of the parameter object (field descriptions — in the language `loc`).
    fn parameters(&self, loc: &crate::shared::i18n::Locale) -> serde_json::Value;
    /// Executes the call. `args` — the model's parsed argument JSON.
    async fn invoke(&self, ctx: &ToolContext, args: serde_json::Value) -> Result<ToolOutcome>;

    /// Schema to hand to the server (built from `id`/`description`/`parameters` by
    /// default) in the language `loc`.
    fn schema(&self, loc: &crate::shared::i18n::Locale) -> ToolSchema {
        ToolSchema {
            name: self.id(),
            description: self.description(loc),
            parameters: self.parameters(loc),
        }
    }

    /// Semantic group for profile toggles (settings UI).
    fn group(&self) -> meta::ToolGroup;

    /// Short (2-4 word) label for the profile toggle (unlike the LLM-oriented
    /// [`Tool::description`]).
    fn ui_label(&self) -> &'static str;

    /// Global switch gating the tool (`None` — not gated). See
    /// [`effective_tool_ids`].
    fn gate(&self) -> Option<meta::ToolGate> {
        None
    }

    /// Whether a call to this tool changes something **outside the application**
    /// and should therefore be shown to the user first, when
    /// `tools.confirm_dangerous` is on (spec §9.8, fork F1 of
    /// docs/history/tool-confirmation.md).
    ///
    /// The default is `false` — safe — so a new tool is only asked about when its
    /// author says so. That is the right default here precisely because the
    /// switch is opt-in: a wrong `false` costs the user a confirmation they
    /// wanted, while a wrong `true` on, say, `current_time` would train them to
    /// press `Enter` without reading, which is worse than not asking.
    ///
    /// Writes to **our own** storage (notes, the self-model, RAG, attachments)
    /// are deliberately not dangerous: they are visible in the UI, scoped to the
    /// profile, and reversible by the same tools that wrote them.
    fn danger(&self) -> bool {
        false
    }

    /// Whether the tool is enabled in the profile by default (`false` — optional,
    /// enabled manually). See [`default_tool_ids`]/[`all_tool_ids`].
    fn enabled_by_default(&self) -> bool {
        true
    }

    /// Whether a round containing this call spends the `max_tool_rounds` budget
    /// (spec §9.12).
    ///
    /// `true` for every tool but the code workspace. The limit exists to stop a
    /// model looping on *external* work — searches, fetches, subagents — where
    /// each round costs a request and possibly money. Reading and editing an
    /// attached project is the opposite: a fix is a walk of read → change →
    /// check, and a budget of eight rounds ends it in the middle. The user asked
    /// for the exemption explicitly, and what bounds these calls instead is that
    /// they are local, fast, and interruptible by `Esc`.
    fn counts_toward_round_limit(&self) -> bool {
        true
    }

    /// Whether a call to this tool may run **at the same time as its
    /// neighbours** in a round (spec §6.3, docs/research/concurrent-tools.md
    /// §4.1). `true` is a claim by the tool's author: the call has no effect a
    /// sibling call of the same round could observe, changes nothing outside
    /// the application, holds no exclusive resource (a process, a sidecar, a
    /// socket to a stateful peer), needs no cleanup if its future is dropped,
    /// and is never [`Tool::danger`] — so a confirmation popup can never be
    /// part of a concurrent group.
    ///
    /// Default `false`: a new tool runs alone until someone says otherwise —
    /// the right default for the same reason `danger()` defaults the other
    /// way. A wrong `false` costs a user some seconds; a wrong `true` could
    /// interleave a read with the write it was meant to follow.
    fn concurrent(&self) -> bool {
        false
    }
}

/// Name of the web tool (gated by the global switch `tools.web_enabled`).
pub const WEB_SEARCH_ID: &str = "web_search";
/// Name of the URL-fetch tool (gated by `tools.web_enabled` — network access).
pub const FETCH_URL_ID: &str = "fetch_url";
/// Name of the Python tool (gated by `tools.python_enabled`).
pub const PYTHON_EXEC_ID: &str = "python_exec";
/// Name of the video tool (gated by `tools.web_enabled` — network access).
pub const YOUTUBE_WATCH_ID: &str = "youtube_watch";

/// Metadata snapshot of all tools (a single source — the tools themselves via the
/// [`Tool`] trait). Metadata (group/label/gate/default) doesn't depend on
/// [`ToolConfig`], so the catalog is built once on the default config — this avoids
/// rebuilding the registry in the hot [`effective_tool_ids`] (called on every
/// agentic-loop round).
static CATALOG: LazyLock<Vec<meta::ToolInfo>> =
    LazyLock::new(|| standard_registry(&ToolConfig::default()).infos());

/// Catalog of metadata for all known tools (a snapshot of [`CATALOG`]). Order —
/// alphabetical by id (the registry is a `BTreeMap`). Consumers use the id by value
/// (membership/iteration), not by position.
pub fn tool_catalog() -> Vec<meta::ToolInfo> {
    CATALOG.clone()
}

/// Ids of tools enabled in a profile by default (M5-M7). External ones
/// (`web_search`/`python_exec`) are additionally gated by global switches — see
/// [`effective_tool_ids`]. Conversation-control tools and the "self-model" are
/// optional (off by default, `Tool::enabled_by_default`), see [`all_tool_ids`].
/// Derived from [`CATALOG`] (a single source — the tools themselves).
pub fn default_tool_ids() -> Vec<ToolId> {
    CATALOG
        .iter()
        .filter(|i| i.enabled_by_default)
        .map(|i| i.id.clone())
        .collect()
}

/// Full catalog of tool ids for profile toggles: default + optional (off by
/// default — conversation-control tools and the "self-model"). Unlike
/// [`default_tool_ids`], this includes the optional ones — so the user sees them in
/// profile settings and can enable them, but `reconcile_tools` does **not** enable
/// them automatically. Derived from [`CATALOG`]. See spec §9.3.
// The profile-toggle catalog pulls metadata via [`tool_catalog`]; this id helper is
// currently used by tests (fixtures/catalog) — kept as public API.
#[allow(dead_code)]
pub fn all_tool_ids() -> Vec<ToolId> {
    CATALOG.iter().map(|i| i.id.clone()).collect()
}

/// Effective tool set: `enabled` minus external ones disabled by global switches
/// (spec §9.4). `enabled`'s order is preserved. `web_enabled` gates both
/// `web_search` and `fetch_url` (both — network access); `fs_enabled` — the file
/// tools `fs_read`/`fs_write`/`fs_list` (the gate is taken from the tool's
/// metadata, [`Tool::gate`]). Sampling tools (`get_sampling`/`set_sampling`) are
/// disabled if the current engine mode has no available parameter at all
/// (`sampling_provider`, see [`supported_sampling_fields`]) — that's a dynamic gate
/// by provider, so it's handled separately from the static [`meta::ToolGate`].
/// MCP-server tools (id with the `mcp__` prefix) are gated by `mcp_enabled` **by
/// prefix**: they're dynamic and absent from the static [`CATALOG`].
///
/// The history read-back tools are gated the same dynamic way, by
/// `history_available` — whether **this chat** actually has a compacted-away
/// range (sub-decision S12). Two schemas cost prompt on every single turn, and
/// this feature's audience is people already fighting a context ceiling; more
/// importantly it earns an invariant, since the same `compaction_view` decides
/// both this and whether the summary block is in the prompt — so the block can
/// name the tools without ever promising one that is absent.
// No longer `Copy`: `sampling_endpoint` carries the endpoint's published list
// behind an `Arc`, and the gates are read by reference anyway.
#[derive(Debug, Clone, Default)]
pub struct ToolGates {
    /// `tools.web_enabled` — `web_search` and `fetch_url`.
    pub web: bool,
    /// `tools.python_enabled` — `python_exec`.
    pub python: bool,
    /// `tools.fs_enabled` — the `fs_*` family. Deliberately **not** the code
    /// workspace: that is a different capability, narrowed to one directory.
    pub fs: bool,
    /// `mcp.enabled` — every `mcp__…` tool.
    pub mcp: bool,
    /// `tools.subagent_background` — `start_subagent` (spec §9.3.2).
    pub background: bool,
    /// Whether **this chat** has a compacted-away range (spec §6.7, S12).
    pub history: bool,
    /// Whether **this chat** has a code project attached (spec §9.12).
    pub workspace: bool,
    /// Which of that project's three command slots carry a line. A slot with
    /// none means its tool is not offered — the same S12 rule as the pair above,
    /// one level finer.
    pub workspace_commands: code::WorkspaceCommands,
    /// The chat engine's cloud provider, deciding which sampling parameters
    /// exist at all (ADR 0004).
    pub sampling_provider: Option<CloudProvider>,
    /// The sampling fields the **endpoint** published for the configured model,
    /// when it published any (`external` only, docs/history/gateway-capabilities.md): it
    /// narrows the same offer, so the pair of tools is also withdrawn when a
    /// catalogue leaves nothing at all. `None` — silence, nothing narrows.
    pub sampling_endpoint: Option<std::sync::Arc<[String]>>,
}

pub fn effective_tool_ids(enabled: &[ToolId], gates: &ToolGates) -> Vec<ToolId> {
    let sampling_available = !crate::entities::sampling::available_sampling_fields(
        gates.sampling_provider,
        gates.sampling_endpoint.as_deref(),
    )
    .is_empty();
    let gate_of = |id: &str| CATALOG.iter().find(|i| i.id == id).and_then(|i| i.gate);
    enabled
        .iter()
        .filter(|id| {
            if id.as_str() == GET_SAMPLING_ID || id.as_str() == SET_SAMPLING_ID {
                return sampling_available;
            }
            if id.as_str() == history::HISTORY_READ_ID || id.as_str() == history::HISTORY_SEARCH_ID
            {
                return gates.history;
            }
            // The workspace family is gated by the *project*, not by a switch:
            // attaching one is the consent, so there is no second toggle to
            // forget, and with nothing attached the schemas never reach the
            // prompt (the S12 rationale, spec §9.12). The family owns the rule,
            // because a command tool also needs a line in its slot.
            if let Some(offered) = code::offered(id, gates.workspace, gates.workspace_commands) {
                return offered;
            }
            if id.starts_with(mcp::MCP_TOOL_PREFIX) {
                return gates.mcp;
            }
            match gate_of(id) {
                Some(meta::ToolGate::Web) => gates.web,
                Some(meta::ToolGate::Python) => gates.python,
                Some(meta::ToolGate::Fs) => gates.fs,
                Some(meta::ToolGate::Mcp) => gates.mcp,
                Some(meta::ToolGate::Background) => gates.background,
                None => true,
            }
        })
        .cloned()
        .collect()
}

/// Parameters for building the tool registry from configuration (`config.tools`,
/// spec §11.6). Let the registry be rebuilt on live settings edits.
#[derive(Debug, Clone)]
pub struct ToolConfig {
    /// Execution mode for `python_exec` (Wasmer sandbox / local interpreter).
    pub python_mode: PythonMode,
    /// Path to the Python interpreter for `python_exec` (`None` → system, Local mode).
    pub python_path: Option<String>,
    /// Allow network in the Wasmer sandbox (`--net`).
    pub python_net: bool,
    /// Execution timeout in the Wasmer sandbox.
    pub python_wasm_timeout: Duration,
    /// Hard sandbox memory limit (MB; `None` — no limit). Windows only.
    pub python_wasm_memory_mb: Option<u64>,
    /// Hard memory limit per local interpreter process (MB; `None` — no limit). Windows only.
    pub python_local_memory_mb: Option<u64>,
    /// Show the model the images `python_exec` saved (`config.tools.python_images`).
    pub python_images: bool,
    /// Sandbox directory (`data/sandbox/`) with the `wasmer` binary and assets
    /// (`None` — no directory, sandbox only via the env override).
    pub sandbox_dir: Option<PathBuf>,
    /// Default for `web_search.fetch_content` (fetching/reranking pages,
    /// `config.tools.web_fetch_content`). The call argument overrides it.
    pub web_fetch_content: bool,
    /// Whether model-chosen URLs may reach local/private addresses
    /// (`config.tools.web_allow_private`). Off by default; see `shared::net`.
    pub web_allow_private: bool,
    /// Which `web_search` backend to prefer (`config.tools.web_provider`).
    pub web_provider: crate::shared::config::WebProvider,
    /// Resolved keys for the keyed search providers, in preference order —
    /// already through "stored key beats the named env variable", so the tool
    /// never reads a secret store or the environment itself. Empty (the
    /// default) → the keyless chain alone, exactly as before keyed providers.
    pub web_search_keys: Vec<(crate::shared::secrets::SearchSlot, String)>,
    /// "Sandbox" directory for file tools (`None` → no restriction).
    pub fs_root: Option<String>,
    /// Environment variables the settings name as key sources
    /// (`config::named_key_env_vars`): removed from the environment of the children the
    /// model drives, along with the credential-shaped names
    /// (docs/research/safe-defaults.md D5).
    pub named_secrets: Vec<String>,
    /// `config.tools.subagent_parallel` — how many of one reply's sub-agents
    /// run at once; `call_subagent`'s description says so above 1.
    pub subagent_parallel: u32,
    /// Resolved video-understanding slot for `youtube_watch` (`None` — not
    /// configured; the tool then degrades to metadata). Independent of the chat
    /// engine — see `shared::video`.
    pub video: Option<crate::shared::video::VideoConfig>,
    /// Cloud provider of the chat engine (`None` — local/external). Determines
    /// which sampling parameters `get_sampling`/`set_sampling` see/change (schema
    /// and result filtering) — a mirror of the wire dialect. See ADR 0004.
    pub sampling_provider: Option<CloudProvider>,
    /// What the endpoint's catalogue published for the configured model, which
    /// narrows that same set one step further on a gateway
    /// (docs/history/gateway-capabilities.md). `None` — it said nothing.
    pub sampling_endpoint: Option<std::sync::Arc<[String]>>,
}

impl Default for ToolConfig {
    fn default() -> Self {
        Self {
            python_mode: PythonMode::default(),
            python_path: None,
            python_net: true,
            python_wasm_timeout: Duration::from_secs(
                crate::shared::config::DEFAULT_PYTHON_WASM_TIMEOUT_SECS,
            ),
            python_wasm_memory_mb: None,
            python_local_memory_mb: None,
            python_images: true,
            sandbox_dir: None,
            web_fetch_content: true,
            web_allow_private: false,
            web_provider: crate::shared::config::WebProvider::default(),
            web_search_keys: Vec::new(),
            fs_root: None,
            named_secrets: Vec::new(),
            subagent_parallel: 1,
            video: None,
            sampling_provider: None,
            sampling_endpoint: None,
        }
    }
}

/// Registry with all tools (M5-M7) per [`ToolConfig`] parameters. Global switches
/// aren't applied here, but when selecting the effective set (see
/// [`effective_tool_ids`]).
pub fn standard_registry(cfg: &ToolConfig) -> ToolRegistry {
    let mut reg = ToolRegistry::new();
    reg.register(Arc::new(introspection::GetSampling::new(
        cfg.sampling_provider,
        cfg.sampling_endpoint.clone(),
    )));
    reg.register(Arc::new(introspection::SetSampling::new(
        cfg.sampling_provider,
        cfg.sampling_endpoint.clone(),
    )));
    reg.register(Arc::new(introspection::GetSystemMessage));
    reg.register(Arc::new(introspection::SetSystemMessage));
    reg.register(Arc::new(introspection::GetLastUserMessageTime));
    // Language-model introspection (spec §9.14): the LLM's name and the
    // profile's history of model changes — deliberately named `llm_*`, the
    // counterpart of the `self_model` family it must never be confused with.
    reg.register(Arc::new(llm::GetLlmName));
    reg.register(Arc::new(llm::GetLlmHistory));
    reg.register(Arc::new(notes::NoteSave));
    reg.register(Arc::new(notes::NoteRecall));
    reg.register(Arc::new(notes::NoteRevise));
    reg.register(Arc::new(notes::NoteLink));
    reg.register(Arc::new(notes::NoteNeighbors));
    reg.register(Arc::new(notes::NoteSupersede));
    reg.register(Arc::new(notes::NoteMerge));
    reg.register(Arc::new(notes::ConsolidateNotes));
    reg.register(Arc::new(notes::NoteCiteSource));
    reg.register(Arc::new(rag::RagAdd));
    reg.register(Arc::new(rag::RagSearch));
    // A loop-executed tool (spec §9.3.2): registered for its schema and the
    // profile toggle; the agentic loop runs it, with the limits it reads from
    // `config.tools` itself. The one thing parameterized here is what the
    // *description* says about parallel delegation (fork F5 of
    // docs/research/parallel-subagents.md).
    reg.register(Arc::new(subagent::CallSubagent {
        parallel: cfg.subagent_parallel,
    }));
    // The background twin (spec §9.3.2, docs/research/background-subagents.md
    // §4.1): in the catalog and the profile's toggles like any tool, and
    // gated by `tools.subagent_background` in `effective_tool_ids` — at the
    // default it never reaches a request.
    reg.register(Arc::new(subagent::StartSubagent));
    reg.register(Arc::new(dialogue::RunDialogue));
    reg.register(Arc::new(dialogue::StartDialogue));
    // Both tools follow addresses the model picked, so both are built on a client that
    // refuses local and private ones (docs/research/fetch-url-address-policy.md, fork F1).
    let policy = crate::shared::net::AddressPolicy::from_allow_private(cfg.web_allow_private);
    reg.register(Arc::new(web::WebSearch::new(
        cfg.web_fetch_content,
        policy,
        web::keyed_backends(cfg.web_provider, &cfg.web_search_keys),
    )));
    reg.register(Arc::new(fetch::FetchUrl::new(policy)));
    // Video understanding is a slot of its own (only Gemini takes video at all),
    // so the tool gets a client built from `cfg.video` rather than `ctx.engine`.
    // Unconfigured → registered anyway, degrading to metadata (fork R5a).
    reg.register(Arc::new(youtube::YoutubeWatch::new(
        cfg.video.clone().map(|c| {
            Arc::new(crate::shared::video::gemini::GeminiVideo::new(c))
                as Arc<dyn crate::shared::video::VideoUnderstanding>
        }),
        cfg.video
            .as_ref()
            .map_or(crate::shared::config::DEFAULT_VIDEO_MAX_MINUTES, |c| {
                c.max_minutes
            }),
    )));
    // One contract, one call path: the mode picks the runner, not a second branch inside
    // the tool (docs/history/sandbox-file-exchange.md §14 V1).
    let runner: Arc<dyn crate::shared::sandbox::SandboxRunner> = match cfg.python_mode {
        crate::shared::config::PythonMode::Wasmer => Arc::new(
            WasmerSandbox::new(cfg.sandbox_dir.clone())
                .with_memory_limit(cfg.python_wasm_memory_mb)
                // The same switch the web tools read: "the model may reach private
                // addresses" is one decision, not one per tool (safe-defaults.md D4).
                .with_private_network(cfg.web_allow_private),
        ),
        crate::shared::config::PythonMode::Local => Arc::new(
            crate::shared::sandbox::LocalSandbox::new(cfg.python_path.clone())
                .with_memory_limit(cfg.python_local_memory_mb)
                .with_named_secrets(cfg.named_secrets.clone()),
        ),
    };
    reg.register(Arc::new(
        python::PythonExec::new(
            cfg.python_mode,
            runner,
            cfg.python_net,
            cfg.python_wasm_timeout,
        )
        .with_images(cfg.python_images)
        .with_private_network(cfg.web_allow_private),
    ));
    reg.register(Arc::new(calc::Calculate));
    reg.register(Arc::new(datetime::CurrentTime));
    reg.register(Arc::new(fs::FsRead::new(cfg.fs_root.clone())));
    reg.register(Arc::new(fs::FsWrite::new(cfg.fs_root.clone())));
    reg.register(Arc::new(fs::FsList::new(cfg.fs_root.clone())));
    // The code workspace (spec §9.12): reading, listing and searching the project
    // the user attached to this chat. Stateless - the root is per chat and comes
    // from the turn snapshot, not from config - and gated by the project's
    // presence rather than by a global switch.
    for tool in code::ALL {
        reg.register(Arc::new(tool));
    }
    // Reading/searching files the user attached to the chat (`/file attach`). Not
    // gated: unlike fs_read they can only reach what the user explicitly attached.
    reg.register(Arc::new(attachment::AttachmentRead));
    reg.register(Arc::new(attachment::AttachmentSearch));
    // Reading back the part of *this* conversation that compression folded into
    // the summary (spec §6.7). Not gated by a switch — narrower still than the
    // attachment tools, since they reach only this chat's own older messages,
    // which the user is looking at in the feed. They are, however, offered to the
    // model only while there is a folded range at all (see `effective_tool_ids`).
    reg.register(Arc::new(history::HistoryRead));
    reg.register(Arc::new(history::HistorySearch));
    // Searching/reading the *other* chats of the current profile (spec §9.11).
    // No gate, but off by default (`enabled_by_default = false`): crossing
    // conversation boundaries is a deliberate per-profile opt-in, and while it
    // is off the pair is not advertised to the model at all. The turn snapshot
    // (`ToolContext::other_chats`) is their whole world — profile-scoped, with
    // the current chat excluded.
    reg.register(Arc::new(chats::ChatSearch));
    reg.register(Arc::new(chats::ChatRead));
    // Conversation-control tools (optional, gated by the profile's set).
    reg.register(Arc::new(control::SendFollowupMessage));
    reg.register(Arc::new(control::RewriteCurrentMessage));
    // "Self-model" tools (optional, DB-only, gated by the profile's set).
    reg.register(Arc::new(self_model::GetSelfModel));
    reg.register(Arc::new(self_model::Reflect));
    reg.register(Arc::new(self_model::UpdateSelfModel));
    reg.register(Arc::new(self_model::UpdateUserModel));
    reg.register(Arc::new(self_model::AddInsight));
    reg
}

/// Tool registry: maps names to implementations, hands schemas to the engine.
#[derive(Default)]
pub struct ToolRegistry {
    tools: BTreeMap<ToolId, Arc<dyn Tool>>,
}

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

    /// Registers a tool (overwrites on a matching id).
    pub fn register(&mut self, tool: Arc<dyn Tool>) {
        self.tools.insert(tool.id(), tool);
    }

    /// Tool by name (used by registry tests).
    #[allow(dead_code)]
    pub fn get(&self, id: &str) -> Option<&Arc<dyn Tool>> {
        self.tools.get(id)
    }

    /// Metadata snapshot of all registered tools (for the UI catalog).
    pub fn infos(&self) -> Vec<meta::ToolInfo> {
        self.tools
            .values()
            .map(|t| meta::ToolInfo {
                id: t.id(),
                group: t.group(),
                label: t.ui_label(),
                gate: t.gate(),
                enabled_by_default: t.enabled_by_default(),
                concurrent: t.concurrent(),
                description: None,
            })
            .collect()
    }

    /// Whether the registered tool `id` may run alongside its neighbours in a
    /// round ([`Tool::concurrent`]). An unknown name runs alone — it is about
    /// to be refused anyway, and a refusal is not a member of any group.
    pub fn is_concurrent(&self, id: &str) -> bool {
        self.tools.get(id).is_some_and(|t| t.concurrent())
    }

    /// Schemas for a subset of enabled tools (profile ∩ global), preserving
    /// `enabled`'s order. Unknown names are ignored.
    pub fn schemas_for(
        &self,
        enabled: &[ToolId],
        loc: &crate::shared::i18n::Locale,
    ) -> Vec<ToolSchema> {
        enabled
            .iter()
            .filter_map(|id| self.tools.get(id))
            .map(|t| t.schema(loc))
            .collect()
    }

    /// Executes a tool by name. Errors if the tool is unknown.
    pub async fn invoke(
        &self,
        id: &str,
        ctx: &ToolContext,
        args: serde_json::Value,
    ) -> Result<ToolOutcome> {
        match self.tools.get(id) {
            Some(tool) => tool.invoke(ctx, args).await,
            None => anyhow::bail!("unknown tool: {id}"),
        }
    }
}

#[cfg(test)]
pub(crate) mod testkit {
    //! Utilities for tool tests: building a [`ToolContext`] over temp storage with a
    //! mock engine and a deterministic embedder.

    use super::*;
    use crate::shared::api::EmbedRole;
    use crate::shared::api::mock::{MockBackend, MockEmbedder};
    use crate::shared::paths::Paths;

    /// Default tool parameters for tests.
    fn test_params() -> ToolParams {
        ToolParams {
            chunk_params: rag::ChunkParams::default(),
            self_model_params: SelfModelParams::default(),
            recall_includes_self: false,
            history_page_tokens: crate::shared::config::DEFAULT_COMPACTION_PAGE_TOKENS,
            attachments: crate::shared::config::AttachmentSettings::default(),
            mcp_images: true,
            python_net: false,
            python_mode: crate::shared::config::PythonMode::Wasmer,
            workspace: crate::shared::config::WorkspaceSettings::default(),
            file_hint: None,
            named_secrets: Vec::new().into(),
        }
    }

    /// Default turn snapshot for tests (profile given, chat is new).
    fn test_turn(profile_id: Uuid) -> TurnInfo {
        TurnInfo {
            profile_id,
            chat_id: Uuid::new_v4(),
            system_message: "системное сообщение".into(),
            effective_sampling: SamplingConfig::default(),
            last_user_message_at: None,
            // No attachments by default; tests that need them set `ctx.attachments`.
            attachments: std::sync::Arc::from(Vec::new()),
            history: None,
            // No other chats by default; tests that need them set `ctx.other_chats`.
            other_chats: std::sync::Arc::from(Vec::new()),
            workspace: None,
            workspace_journal: None,
            // No stored files and no folder by default; tests that store set both.
            files_dir: None,
            files: std::sync::Arc::from(Vec::new()),
            // Empty, like the snapshots above: a test that sets them calls
            // `ctx.sync_inputs()` afterwards, which is what a turn's round does.
            inputs: std::sync::Arc::from(Vec::new()),
            images: std::sync::Arc::from(Vec::new()),
            stages_files: false,
            lang: crate::shared::i18n::Lang::Ru,
            cancel: tokio_util::sync::CancellationToken::new(),
            // No engine name by default; tests that need one set `ctx.model_name`.
            model_name: None,
            engine_mode: crate::shared::config::ServerMode::default(),
            // No session budget by default (a background task's shape); the
            // summary permit test sets `ctx.sessions`.
            sessions: None,
            silent_lane: false,
        }
    }

    /// Context of a tool over temp storage. Also returns `TempDir` (keep alive)
    /// and `Arc<Storage>` (for checks in the test).
    pub fn ctx_with_storage(profile_id: Uuid) -> (tempfile::TempDir, Arc<Storage>, ToolContext) {
        ctx_with_storage_lang(profile_id, crate::shared::i18n::Lang::Ru)
    }

    /// Like [`ctx_with_storage`], but with an explicit scaffold language (for
    /// checking tool-result localization — e.g. `python_exec` on an en profile).
    pub fn ctx_with_storage_lang(
        profile_id: Uuid,
        lang: crate::shared::i18n::Lang,
    ) -> (tempfile::TempDir, Arc<Storage>, ToolContext) {
        let dir = tempfile::tempdir().unwrap();
        let storage = Arc::new(Storage::open_in_memory(Paths::with_root(dir.path())).unwrap());
        let deps = ToolDeps {
            storage: storage.clone(),
            engine: Arc::new(MockBackend::scripted(vec![])),
            embedder: Arc::new(MockEmbedder::new(16)),
        };
        let mut turn = test_turn(profile_id);
        turn.lang = lang;
        let ctx = ToolContext::new(deps, test_params(), turn);
        (dir, storage, ctx)
    }

    /// Context of a tool over a ready dependency bundle (tests where several
    /// contexts share one storage — e.g. profile isolation).
    pub fn ctx_with_deps(profile_id: Uuid, deps: ToolDeps) -> ToolContext {
        ToolContext::new(deps, test_params(), test_turn(profile_id))
    }

    /// An embedder that records the role every text was embedded under, on top of
    /// the usual deterministic mock.
    ///
    /// The role is invisible in the result — a wrong one changes no return value,
    /// only the quality of a comparison on a model that uses input prefixes — so
    /// recording it is the only way a test can see it at all (research
    /// docs/research/embedding-input-prefixes.md §2.3, §5).
    pub struct RoleRecorder {
        inner: MockEmbedder,
        pub calls: std::sync::Mutex<Vec<(Vec<String>, EmbedRole)>>,
    }

    impl RoleRecorder {
        pub fn new() -> Self {
            Self {
                inner: MockEmbedder::new(16),
                calls: std::sync::Mutex::new(Vec::new()),
            }
        }

        /// Roles recorded so far, in call order.
        pub fn roles(&self) -> Vec<EmbedRole> {
            self.calls.lock().unwrap().iter().map(|(_, r)| *r).collect()
        }

        /// Whether every recorded call used `role` (and at least one happened).
        pub fn all_were(&self, role: EmbedRole) -> bool {
            let roles = self.roles();
            !roles.is_empty() && roles.iter().all(|r| *r == role)
        }
    }

    #[async_trait::async_trait]
    impl Embedder for RoleRecorder {
        async fn embed(
            &self,
            texts: Vec<String>,
            role: EmbedRole,
        ) -> anyhow::Result<Vec<Vec<f32>>> {
            self.calls.lock().unwrap().push((texts.clone(), role));
            self.inner.embed(texts, role).await
        }
    }

    /// Context of a tool with a custom engine/embedder (web/subagent/rag/fetch
    /// tests), over temp storage.
    pub fn ctx_with_backends(
        profile_id: Uuid,
        engine: Arc<dyn EngineBackend>,
        embedder: Arc<dyn Embedder>,
    ) -> (tempfile::TempDir, Arc<Storage>, ToolContext) {
        let dir = tempfile::tempdir().unwrap();
        let storage = Arc::new(Storage::open_in_memory(Paths::with_root(dir.path())).unwrap());
        let deps = ToolDeps {
            storage: storage.clone(),
            engine,
            embedder,
        };
        let ctx = ToolContext::new(deps, test_params(), test_turn(profile_id));
        (dir, storage, ctx)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A tool reads a user's file with the interface language's hint, not the profile's
    /// scaffold language: the file belongs to its user (docs/research/local-file-encoding.md
    /// fork F2c).
    #[test]
    fn tool_params_take_the_file_hint_from_the_interface_language() {
        let mut cfg = AppConfig::default();
        cfg.interface.language = crate::shared::i18n::Lang::Ru;
        assert_eq!(ToolParams::from_config(&cfg).file_hint, Some("ru"));
        cfg.interface.language = crate::shared::i18n::Lang::En;
        assert_eq!(ToolParams::from_config(&cfg).file_hint, None);
    }

    /// §14 V5: the network switch is the sandbox's. In Local mode the code runs with the
    /// user's own reach, so the value the confirmation popup states is `true` there
    /// whatever the setting says — a popup promising an isolated network would be a lie.
    #[test]
    fn local_mode_reports_the_network_as_reachable_whatever_the_switch_says() {
        let mut cfg = AppConfig::default();
        cfg.tools.python_net_enabled = false;
        cfg.tools.python_mode = crate::shared::config::PythonMode::Wasmer;
        assert!(!ToolParams::from_config(&cfg).python_net);
        cfg.tools.python_mode = crate::shared::config::PythonMode::Local;
        let params = ToolParams::from_config(&cfg);
        assert!(params.python_net);
        assert_eq!(params.python_mode, crate::shared::config::PythonMode::Local);
    }

    /// The concurrent set is exactly the documented one
    /// (docs/research/concurrent-tools.md §2.3) — a tool cannot be marked by
    /// accident and the document cannot drift — and no marked tool is
    /// dangerous: a confirmation popup can never be part of a segment, which
    /// is what lets the loop skip the gate for a segment's members (§4.3).
    #[test]
    fn concurrent_tools_are_the_documented_set_and_never_dangerous() {
        let reg = standard_registry(&ToolConfig::default());
        let infos = reg.infos();
        let mut marked: Vec<&str> = infos
            .iter()
            .filter(|i| i.concurrent)
            .map(|i| i.id.as_str())
            .collect();
        marked.sort_unstable();
        let mut documented = vec![
            fs::FS_READ_ID,
            fs::FS_LIST_ID,
            code::CODE_READ_ID,
            code::CODE_GREP_ID,
            code::CODE_LIST_ID,
            attachment::ATTACHMENT_READ_ID,
            attachment::ATTACHMENT_SEARCH_ID,
            chats::CHAT_SEARCH_ID,
            chats::CHAT_READ_ID,
            history::HISTORY_READ_ID,
            history::HISTORY_SEARCH_ID,
            self_model::GET_SELF_MODEL_ID,
            GET_SAMPLING_ID,
            llm::GET_LLM_NAME_ID,
            llm::GET_LLM_HISTORY_ID,
            FETCH_URL_ID,
        ];
        documented.sort_unstable();
        assert_eq!(marked, documented);
        for info in infos.iter().filter(|i| i.concurrent) {
            let tool = reg.get(&info.id).unwrap();
            assert!(
                !tool.danger(),
                "{} is marked concurrent and dangerous",
                info.id
            );
        }
        assert!(reg.is_concurrent(FETCH_URL_ID));
        assert!(!reg.is_concurrent(fs::FS_WRITE_ID));
        assert!(
            !reg.is_concurrent(WEB_SEARCH_ID),
            "out until measured (fork F4)"
        );
        assert!(
            !reg.is_concurrent(subagent::CALL_SUBAGENT_ID),
            "the group's own path"
        );
        assert!(!reg.is_concurrent("no_such_tool"));
    }

    /// The ~1200 tests built on [`testkit::ctx_with_storage`] run against an
    /// in-memory store on purpose: they exercise SQLite, and on a slow disk
    /// every write is an fsync — measured on the Windows CI runner, the
    /// notes/RAG tests that go through here ran 8–19x slower than locally
    /// against a 3.9x median for the suite, and moving them off disk cut
    /// `features::tools::*` from 103.3s to 16.4s locally.
    ///
    /// Switching the testkit back to [`Storage::open`] would hand all of that
    /// back and **no other test would fail**, which is exactly why this one
    /// exists.
    #[test]
    fn tool_context_storage_touches_no_disk() {
        let (dir, storage, _ctx) = testkit::ctx_with_storage(Uuid::new_v4());

        // A real write, so this cannot pass by simply never touching the store.
        storage
            .db()
            .note_insert(&crate::entities::note::Note::new(
                Uuid::new_v4(),
                "заметка",
                vec![],
            ))
            .unwrap();

        let paths = crate::shared::paths::Paths::with_root(dir.path());
        assert!(
            !paths.data_db().exists(),
            "the tool testkit must not create data.db — see the doc comment above"
        );
        assert!(!paths.cache_db().exists(), "nor cache.db");
    }

    struct Echo;

    #[async_trait::async_trait]
    impl Tool for Echo {
        fn id(&self) -> ToolId {
            "echo".into()
        }
        fn description(&self, _loc: &crate::shared::i18n::Locale) -> String {
            "Возвращает аргумент text".into()
        }
        fn parameters(&self, _loc: &crate::shared::i18n::Locale) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {"text": {"type": "string"}},
                "required": ["text"],
            })
        }
        async fn invoke(&self, _ctx: &ToolContext, args: serde_json::Value) -> Result<ToolOutcome> {
            let text = args["text"].as_str().unwrap_or_default();
            Ok(ToolOutcome::text(text))
        }
        fn group(&self) -> meta::ToolGroup {
            meta::ToolGroup::Utils
        }
        fn ui_label(&self) -> &'static str {
            "echo"
        }
    }

    #[tokio::test]
    async fn registry_invokes_registered_tool() {
        let mut reg = ToolRegistry::new();
        reg.register(Arc::new(Echo));
        let (_d, _s, ctx) = testkit::ctx_with_storage(Uuid::new_v4());
        let out = reg
            .invoke("echo", &ctx, serde_json::json!({"text": "hi"}))
            .await
            .unwrap();
        assert_eq!(out.result, "hi");
        assert!(out.effects.is_empty());
    }

    #[tokio::test]
    async fn registry_unknown_tool_errors() {
        let reg = ToolRegistry::new();
        let (_d, _s, ctx) = testkit::ctx_with_storage(Uuid::new_v4());
        assert!(
            reg.invoke("nope", &ctx, serde_json::json!({}))
                .await
                .is_err()
        );
    }

    #[test]
    fn standard_registry_has_all_default_tools() {
        let reg = standard_registry(&ToolConfig::default());
        // The registry contains the whole catalog — both default and optional
        // control ones.
        for id in all_tool_ids() {
            assert!(reg.get(&id).is_some(), "tool {id} not registered");
        }
        // Schemas for the full catalog cover all ids.
        assert_eq!(
            reg.schemas_for(
                &all_tool_ids(),
                crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru)
            )
            .len(),
            all_tool_ids().len()
        );
    }

    #[test]
    fn all_tool_descriptions_localized_to_en() {
        // Strong gate (§3.5 docs/history/i18n.md): every tool's en description
        // contains no Cyrillic and differs from ru — catches a forgotten `_loc` in
        // any group.
        use crate::shared::i18n::{Lang, locale};
        let reg = standard_registry(&ToolConfig::default());
        let (ru, en) = (locale(Lang::Ru), locale(Lang::En));
        for id in all_tool_ids() {
            let t = reg.get(&id).expect("tool in registry");
            let d_en = t.description(en);
            assert!(
                !d_en
                    .chars()
                    .any(|c| ('а'..='я').contains(&c) || ('А'..='Я').contains(&c)),
                "{id}: Cyrillic in en description: {d_en}"
            );
            assert_ne!(t.description(ru), d_en, "{id}: description not localized");
        }
    }

    #[test]
    fn note_revise_is_default_tool() {
        // Note revision is central to integration — enabled by default.
        assert!(
            default_tool_ids()
                .iter()
                .any(|t| t == notes::NOTE_REVISE_ID)
        );
    }

    #[test]
    fn control_tools_optional_not_in_defaults() {
        // Control tools — in the catalog, but not among the defaults (off by default).
        assert!(
            !default_tool_ids()
                .iter()
                .any(|t| t == control::SEND_FOLLOWUP_ID)
        );
        assert!(
            !default_tool_ids()
                .iter()
                .any(|t| t == control::REWRITE_CURRENT_ID)
        );
        assert!(
            all_tool_ids()
                .iter()
                .any(|t| t == control::SEND_FOLLOWUP_ID)
        );
        assert!(
            all_tool_ids()
                .iter()
                .any(|t| t == control::REWRITE_CURRENT_ID)
        );
    }

    #[test]
    fn self_model_tools_optional_not_in_defaults() {
        // "Self-model" tools — in the catalog, but not among the defaults.
        for id in [
            self_model::GET_SELF_MODEL_ID,
            self_model::REFLECT_ID,
            self_model::UPDATE_SELF_MODEL_ID,
            self_model::UPDATE_USER_MODEL_ID,
            self_model::ADD_INSIGHT_ID,
        ] {
            assert!(
                !default_tool_ids().iter().any(|t| t == id),
                "{id} in defaults"
            );
            assert!(
                all_tool_ids().iter().any(|t| t == id),
                "{id} not in catalog"
            );
        }
        // DB-only: pass the effective set with no global gates.
        let eff = effective_tool_ids(
            &all_tool_ids(),
            &ToolGates {
                background: false,
                history: true,
                ..Default::default()
            },
        );
        assert!(eff.iter().any(|t| t == self_model::GET_SELF_MODEL_ID));
        assert!(eff.iter().any(|t| t == self_model::UPDATE_SELF_MODEL_ID));
    }

    #[test]
    fn effective_tool_ids_gates_external_tools() {
        let enabled = default_tool_ids();
        // web on, python off, fs off → web_search/fetch_url present, no python/fs.
        let eff = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                web: true,
                history: true,
                ..Default::default()
            },
        );
        assert!(eff.iter().any(|t| t == WEB_SEARCH_ID));
        assert!(eff.iter().any(|t| t == FETCH_URL_ID));
        assert!(!eff.iter().any(|t| t == PYTHON_EXEC_ID));
        assert!(!eff.iter().any(|t| t == fs::FS_READ_ID));
        // everything off → no external/file tools, but internal ones remain.
        let eff = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                history: true,
                ..Default::default()
            },
        );
        assert!(!eff.iter().any(|t| t == WEB_SEARCH_ID || t == FETCH_URL_ID));
        assert!(
            !eff.iter()
                .any(|t| t == fs::FS_READ_ID || t == fs::FS_WRITE_ID || t == fs::FS_LIST_ID)
        );
        assert!(eff.iter().any(|t| t == "note_save"));
        // safe tools are always available.
        assert!(eff.iter().any(|t| t == "calculate"));
        assert!(eff.iter().any(|t| t == "current_time"));
        // fs on → file tools appear.
        let eff = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                fs: true,
                history: true,
                ..Default::default()
            },
        );
        assert!(eff.iter().any(|t| t == fs::FS_READ_ID));
        assert!(eff.iter().any(|t| t == fs::FS_WRITE_ID));
        assert!(eff.iter().any(|t| t == fs::FS_LIST_ID));
    }

    #[test]
    fn effective_tool_ids_keeps_sampling_tools_when_params_available() {
        let enabled = default_tool_ids();
        // Any current mode has at least one available parameter (max_tokens) —
        // sampling tools stay available (locally and in the cloud).
        for provider in [
            None,
            Some(CloudProvider::OpenAi),
            Some(CloudProvider::Gemini),
            Some(CloudProvider::Claude),
        ] {
            let eff = effective_tool_ids(
                &enabled,
                &ToolGates {
                    background: false,
                    history: true,
                    sampling_provider: provider,
                    ..Default::default()
                },
            );
            assert!(
                eff.iter().any(|t| t == GET_SAMPLING_ID),
                "get_sampling must be available for {provider:?}"
            );
            assert!(eff.iter().any(|t| t == SET_SAMPLING_ID));
        }
    }

    /// S12: the read-back tools are offered only while the chat actually has a
    /// folded-away range. Two schemas cost prompt on **every** turn, and the same
    /// condition puts the summary block in the prompt — so this is also what lets
    /// the block name them without ever promising an absent tool.
    #[test]
    fn effective_tool_ids_gates_history_tools_by_the_chat() {
        let enabled: Vec<ToolId> = vec![
            "note_save".into(),
            history::HISTORY_READ_ID.into(),
            history::HISTORY_SEARCH_ID.into(),
        ];
        let eff = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                ..Default::default()
            },
        );
        assert!(
            !eff.iter()
                .any(|t| t == history::HISTORY_READ_ID || t == history::HISTORY_SEARCH_ID),
            "nothing folded → the tools must not be offered"
        );
        assert!(eff.iter().any(|t| t == "note_save"), "unrelated tools stay");

        let eff = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                history: true,
                ..Default::default()
            },
        );
        assert!(eff.iter().any(|t| t == history::HISTORY_READ_ID));
        assert!(eff.iter().any(|t| t == history::HISTORY_SEARCH_ID));
    }

    #[test]
    fn effective_tool_ids_gates_mcp_tools_by_prefix() {
        // MCP tools (dynamic, outside CATALOG) are gated by the master switch by
        // the `mcp__` prefix; internal tools don't depend on it.
        let enabled: Vec<ToolId> = vec!["note_save".into(), "mcp__fs__read_text_file".into()];
        let eff = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                history: true,
                ..Default::default()
            },
        );
        assert!(!eff.iter().any(|t| t.starts_with(mcp::MCP_TOOL_PREFIX)));
        assert!(eff.iter().any(|t| t == "note_save"));
        let eff = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                mcp: true,
                history: true,
                ..Default::default()
            },
        );
        assert!(eff.iter().any(|t| t == "mcp__fs__read_text_file"));
    }

    /// The workspace family is gated by the **project**, not by a switch: with
    /// nothing attached the schemas never reach the prompt, and attaching is the
    /// consent (spec §9.12). This mirrors the history pair's gate, and is what
    /// keeps a chat with no project byte-identical to what the app sent before
    /// the feature existed.
    #[test]
    fn workspace_tools_need_an_attached_project() {
        let enabled: Vec<ToolId> = code::WORKSPACE_TOOL_IDS
            .iter()
            .map(|id| ToolId::from(*id))
            .collect();
        let detached = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                history: true,
                ..Default::default()
            },
        );
        assert!(
            detached.is_empty(),
            "with no project the tools must not be offered: {detached:?}"
        );
        let attached = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                history: true,
                workspace: true,
                ..Default::default()
            },
        );
        // A project with no command lines offers the readers and the editors —
        // and none of the three command tools, which have nothing to run.
        assert_eq!(
            attached.len(),
            code::WORKSPACE_TOOL_IDS.len() - 3,
            "a slot with no line must not be offered: {attached:?}"
        );
        for id in [code::CODE_BUILD_ID, code::CODE_RUN_ID, code::CODE_TEST_ID] {
            assert!(!attached.iter().any(|t| t == id), "{id} without a line");
        }

        // Give one slot a line and exactly its tool appears. Per slot rather
        // than for "the commands", because the wrong-slot wiring is invisible
        // from a count (docs/lessons.md §2).
        for slot in crate::entities::workspace::CommandSlot::ALL {
            let mut ws = crate::entities::workspace::Workspace::new("/p");
            ws.set_command(slot, Some("cargo build".into()));
            let offered = effective_tool_ids(
                &enabled,
                &ToolGates {
                    background: false,
                    history: true,
                    workspace: true,
                    workspace_commands: code::WorkspaceCommands::of(&ws),
                    ..Default::default()
                },
            );
            let wanted = crate::features::tools::code::CodeTool::Command(slot).id();
            assert!(
                offered.iter().any(|t| t == wanted),
                "{wanted} must be offered once its slot has a line: {offered:?}"
            );
            assert_eq!(
                offered.len(),
                code::WORKSPACE_TOOL_IDS.len() - 2,
                "only this slot's tool joins: {offered:?}"
            );
        }

        // The gate is the project *and* the profile: a tool the user switched
        // off stays off with a project attached.
        let one: Vec<ToolId> = vec![code::CODE_READ_ID.into()];
        let narrow = effective_tool_ids(
            &one,
            &ToolGates {
                background: false,
                history: true,
                workspace: true,
                ..Default::default()
            },
        );
        assert_eq!(narrow, one);
    }

    /// The family is not gated by `tools.fs_enabled`: it is a different
    /// capability, narrowed to one directory the user pointed at, and pairing it
    /// with the file-system switch would make attaching a project insufficient.
    #[test]
    fn workspace_tools_do_not_ride_the_fs_switch() {
        let enabled: Vec<ToolId> = vec![code::CODE_LIST_ID.into()];
        let fs_off = effective_tool_ids(
            &enabled,
            &ToolGates {
                background: false,
                history: true,
                workspace: true,
                ..Default::default()
            },
        );
        assert_eq!(fs_off, enabled, "fs_enabled must not gate the code tools");
    }

    #[test]
    fn schemas_for_filters_and_orders() {
        let mut reg = ToolRegistry::new();
        reg.register(Arc::new(Echo));
        // Only enabled names make it into the schemas; unknown ones are ignored.
        let schemas = reg.schemas_for(
            &["echo".into(), "missing".into()],
            crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
        );
        assert_eq!(schemas.len(), 1);
        assert_eq!(schemas[0].name, "echo");
        assert!(
            reg.schemas_for(
                &[],
                crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru)
            )
            .is_empty()
        );
    }
}