eggsact 1.2.7

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

use crate::mcp::budget::{self, ToolBudget};
use crate::mcp::registry::{self, ToolExposure, ToolListAudience, ToolSpec};
use crate::mcp::response::{truncate_response, ToolResponse};
use crate::mcp::schema_validation;
use serde_json::Value;
use std::fmt;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;

use crate::calc::context::EvalContext;
pub use crate::mcp::compat::CompatibilityMode;

/// Typed profile selection for tool filtering.
///
/// Profiles control which subset of tools is available. Each profile
/// corresponds to a string profile name used in the MCP registry.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum Profile {
    /// All non-hidden tools.
    #[default]
    Full,
    /// Default tool set.
    Default,
    /// Minimal codegg tool set.
    CodeggCoreMin,
    /// Core codegg tools.
    CodeggCore,
    /// Codegg preflight tools.
    CodeggPreflight,
    /// Codegg patch/edit tools.
    CodeggPatch,
    /// Codegg config validation tools.
    CodeggConfig,
    /// Codegg unicode security tools.
    CodeggUnicodeSecurity,
    /// Codegg shell/command tools.
    CodeggShell,
    /// Codegg repository audit tools.
    CodeggRepoAudit,
    /// Human-friendly math tools.
    HumanMath,
    /// Custom profile by name.
    Custom(String),
}

impl Profile {
    /// Convert to the string profile name used in the MCP registry.
    pub fn as_str(&self) -> &str {
        match self {
            Profile::Full => "full",
            Profile::Default => "default",
            Profile::CodeggCoreMin => "codegg_core_min",
            Profile::CodeggCore => "codegg_core",
            Profile::CodeggPreflight => "codegg_preflight",
            Profile::CodeggPatch => "codegg_patch",
            Profile::CodeggConfig => "codegg_config",
            Profile::CodeggUnicodeSecurity => "codegg_unicode_security",
            Profile::CodeggShell => "codegg_shell",
            Profile::CodeggRepoAudit => "codegg_repo_audit",
            Profile::HumanMath => "human_math",
            Profile::Custom(name) => name,
        }
    }

    /// Create an explicit custom profile by name.
    ///
    /// Use this when you intentionally want a profile not in the built-in set.
    /// For parsing user input, prefer [`from_str_opt`](Self::from_str_opt)
    /// which rejects unknown names.
    pub fn custom(name: impl Into<String>) -> Self {
        Profile::Custom(name.into())
    }

    /// Parse a profile from a string name.
    ///
    /// Returns `Some` only for known built-in profile names.
    /// Returns `None` for unknown names. To construct a custom profile
    /// explicitly, use [`Profile::custom(name)`](Self::custom).
    pub fn from_str_opt(name: &str) -> Option<Self> {
        match name {
            "full" => Some(Profile::Full),
            "default" => Some(Profile::Default),
            "codegg_core_min" => Some(Profile::CodeggCoreMin),
            "codegg_core" => Some(Profile::CodeggCore),
            "codegg_preflight" => Some(Profile::CodeggPreflight),
            "codegg_patch" => Some(Profile::CodeggPatch),
            "codegg_config" => Some(Profile::CodeggConfig),
            "codegg_unicode_security" => Some(Profile::CodeggUnicodeSecurity),
            "codegg_shell" => Some(Profile::CodeggShell),
            "codegg_repo_audit" => Some(Profile::CodeggRepoAudit),
            "human_math" => Some(Profile::HumanMath),
            _ => None,
        }
    }
}

impl fmt::Display for Profile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Audience for tool listing, controlling which exposure levels are included.
///
/// - `Model`: Excludes `HarnessOnly` and `Hidden`. Safe for ordinary
///   model-facing codegg integrations.
/// - `Harness`: Includes `HarnessOnly` tools for selected profiles but
///   excludes `Hidden`. For automatic preflight checks.
/// - `Debug`: Includes all non-hidden tools, including `ExpertOnly`
///   and `HarnessOnly`. Internal/debug listing only.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToolAudience {
    #[default]
    Model,
    Harness,
    Debug,
}

impl ToolAudience {
    /// Lowercase name matching the `EGGCALC_MCP_AUDIENCE` convention
    /// (`model`, `harness`, `debug`).
    pub fn as_str(self) -> &'static str {
        match self {
            ToolAudience::Model => "model",
            ToolAudience::Harness => "harness",
            ToolAudience::Debug => "debug",
        }
    }

    /// Convert to the MCP registry's `ToolListAudience`.
    pub fn as_registry_audience(self) -> ToolListAudience {
        match self {
            ToolAudience::Model => ToolListAudience::Model,
            ToolAudience::Harness => ToolListAudience::Harness,
            ToolAudience::Debug => ToolListAudience::Debug,
        }
    }

    /// Whether this audience may execute a tool with the given exposure level.
    ///
    /// Rules:
    /// - Model audience rejects `HarnessOnly` and `Hidden`.
    /// - Harness audience accepts `HarnessOnly` but rejects `Hidden`.
    /// - Debug audience accepts all non-hidden exposure levels.
    pub fn can_execute_exposure(self, exposure: ToolExposure) -> bool {
        match self {
            ToolAudience::Model => {
                exposure != ToolExposure::HarnessOnly && exposure != ToolExposure::Hidden
            }
            ToolAudience::Harness => exposure != ToolExposure::Hidden,
            ToolAudience::Debug => exposure != ToolExposure::Hidden,
        }
    }
}

impl fmt::Display for ToolAudience {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Errors that can occur before tool execution.
///
/// Tool-level failures (e.g., invalid input that the tool handles gracefully)
/// return `Ok(ToolResponse)` with `ok: false`. These errors represent
/// registry-level failures such as unknown tools or profile violations.
#[derive(Debug, Clone)]
pub enum ToolCallError {
    /// The requested tool name was not found in the registry.
    UnknownTool(String),
    /// The tool exists but is not available in the current profile.
    ToolUnavailable { tool: String, profile: String },
    /// The tool exists in the profile but the current audience cannot execute it.
    ToolNotAllowedForAudience {
        tool: String,
        profile: String,
        audience: String,
        exposure: String,
    },
    /// The tool arguments failed schema validation.
    InvalidArguments(String),
    /// An internal error occurred during tool lookup or dispatch.
    Internal(String),
}

impl fmt::Display for ToolCallError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ToolCallError::UnknownTool(name) => write!(f, "Unknown tool: {}", name),
            ToolCallError::ToolUnavailable { tool, profile } => {
                write!(
                    f,
                    "Tool '{}' is not available in profile '{}'",
                    tool, profile
                )
            }
            ToolCallError::ToolNotAllowedForAudience {
                tool,
                profile,
                audience,
                exposure,
            } => {
                write!(
                    f,
                    "Tool '{}' (exposure: {}) is not executable by {} audience in profile '{}'",
                    tool, exposure, audience, profile
                )
            }
            ToolCallError::InvalidArguments(msg) => write!(f, "Invalid arguments: {}", msg),
            ToolCallError::Internal(msg) => write!(f, "Internal error: {}", msg),
        }
    }
}

impl std::error::Error for ToolCallError {}

/// A read-only view of a tool's metadata.
#[derive(Clone, Debug)]
pub struct ToolView {
    pub name: String,
    pub description: String,
    pub category: String,
    pub tier: u8,
    pub profiles: Vec<String>,
    pub tags: Vec<String>,
    pub exposure: String,
    pub cost: String,
    pub stability: String,
    pub composite: bool,
}

impl ToolView {
    fn from_spec(spec: &ToolSpec) -> Self {
        Self {
            name: spec.name.to_string(),
            description: spec.description.to_string(),
            category: spec.category.to_string(),
            tier: spec.tier,
            profiles: spec.profiles.iter().map(|s| s.to_string()).collect(),
            tags: spec.tags.iter().map(|s| s.to_string()).collect(),
            exposure: spec.exposure.as_str().to_string(),
            cost: spec.cost.as_str().to_string(),
            stability: spec.stability.as_str().to_string(),
            composite: spec.composite,
        }
    }
}

/// A read-only view of a tool spec including schemas.
#[derive(Clone, Debug)]
pub struct ToolSpecView {
    pub view: ToolView,
    pub input_schema: Value,
    pub output_schema: Value,
}

impl ToolSpecView {
    fn from_spec(spec: &ToolSpec) -> Self {
        Self {
            view: ToolView::from_spec(spec),
            input_schema: (spec.input_schema)(),
            output_schema: (spec.output_schema)(),
        }
    }
}

/// In-process tool registry for calling eggsact tools directly.
///
/// `ToolRegistry` provides a synchronous, typed API over the consolidated
/// tool registry. It supports profile filtering, audience filtering,
/// argument validation, and direct tool execution without starting an MCP server.
///
/// # Example
///
/// ```
/// use eggsact::agent::ToolRegistry;
///
/// let registry = ToolRegistry::default();
/// let response = registry.call_json("math_eval", serde_json::json!({
///     "expression": "2 + 2"
/// })).unwrap();
/// assert!(response.ok);
/// ```
///
/// For model-facing codegg integrations, use [`ToolRegistry::available_tools_model_safe`]
/// to exclude harness-only tools from the listing:
///
/// ```
/// use eggsact::agent::ToolRegistry;
///
/// let registry = ToolRegistry::default();
/// let model_tools = registry.available_tools_model_safe();
/// // model_tools excludes HarnessOnly and Hidden tools
/// ```
pub struct ToolRegistry {
    profile: Profile,
    audience: ToolAudience,
    compat_mode: CompatibilityMode,
}

impl ToolRegistry {
    /// Create a registry with the default (full) profile and Model audience.
    ///
    /// Uses [`CompatibilityMode::StrictNative`] by default.
    pub fn new() -> Self {
        Self {
            profile: Profile::Full,
            audience: ToolAudience::Model,
            compat_mode: CompatibilityMode::default(),
        }
    }

    /// Create a registry with a specific profile (defaults to Model audience).
    ///
    /// Uses [`CompatibilityMode::StrictNative`] by default.
    pub fn with_profile(profile: Profile) -> Self {
        Self {
            profile,
            audience: ToolAudience::Model,
            compat_mode: CompatibilityMode::default(),
        }
    }

    /// Create a registry with a specific profile and audience.
    ///
    /// Uses [`CompatibilityMode::StrictNative`] by default.
    pub fn with_profile_and_audience(profile: Profile, audience: ToolAudience) -> Self {
        Self {
            profile,
            audience,
            compat_mode: CompatibilityMode::default(),
        }
    }

    /// Set the compatibility mode for this registry.
    ///
    /// Use [`CompatibilityMode::EggcalcPython`] to preserve Python-parity
    /// behavior (Python-style type names in error messages and selected
    /// compatibility error wording). The default is
    /// [`CompatibilityMode::StrictNative`].
    ///
    /// **Note**: Neither mode allows JSON booleans for numeric schema fields.
    /// The validator rejects `true`/`false` for `integer`/`number` fields in
    /// both modes; only this and selected error-message wording differ between
    /// modes. See `architecture/compatibility.md` for the full comparison.
    pub fn with_compat_mode(mut self, compat_mode: CompatibilityMode) -> Self {
        self.compat_mode = compat_mode;
        self
    }

    /// Get the active profile for this registry.
    pub fn profile(&self) -> &Profile {
        &self.profile
    }

    /// Get the active audience for this registry.
    pub fn audience(&self) -> ToolAudience {
        self.audience
    }

    /// Get the active compatibility mode for this registry.
    pub fn compat_mode(&self) -> CompatibilityMode {
        self.compat_mode
    }

    /// List all tools available in the current profile (legacy, not model-safe).
    ///
    /// This method only filters out `Hidden` tools. For model-facing codegg
    /// integrations, prefer [`ToolRegistry::available_tools_model_safe`] or
    /// [`ToolRegistry::available_tools_for_audience`] to also exclude `HarnessOnly` tools.
    #[deprecated(
        since = "1.1.4",
        note = "use available_tools_model_safe, available_tools_for_audience, or available_tools_for_current_audience"
    )]
    pub fn available_tools(&self) -> Vec<ToolView> {
        registry::tools_for_profile(self.profile.as_str())
            .into_iter()
            .filter(|spec| spec.exposure != ToolExposure::Hidden)
            .map(ToolView::from_spec)
            .collect()
    }

    /// List tools for a specific audience.
    pub fn available_tools_for_audience(&self, audience: ToolAudience) -> Vec<ToolView> {
        registry::tools_for_profile_audience(self.profile.as_str(), audience.as_registry_audience())
            .into_iter()
            .map(ToolView::from_spec)
            .collect()
    }

    /// List tools safe for ordinary model-facing codegg integrations.
    ///
    /// Equivalent to `available_tools_for_audience(ToolAudience::Model)`.
    /// Excludes `HarnessOnly` and `Hidden` tools.
    pub fn available_tools_model_safe(&self) -> Vec<ToolView> {
        self.available_tools_for_audience(ToolAudience::Model)
    }

    /// List tools for the registry's stored audience.
    ///
    /// This is the ergonomic shortcut for consumers who construct a registry
    /// with a specific profile and audience and then want tools for that audience
    /// without passing the audience again.
    pub fn available_tools_for_current_audience(&self) -> Vec<ToolView> {
        self.available_tools_for_audience(self.audience)
    }

    /// Get detailed information about a specific tool.
    ///
    /// Returns metadata only when the tool is available for the registry's
    /// current profile **and** audience. Use [`get_tool_unfiltered`](Self::get_tool_unfiltered)
    /// to bypass audience checks.
    pub fn get_tool(&self, name: &str) -> Option<ToolSpecView> {
        let spec = registry::get_tool(name)?;
        let profile_tools = registry::tools_for_profile(self.profile.as_str());
        if !profile_tools.iter().any(|s| s.name == name) {
            return None;
        }
        if !self.audience.can_execute_exposure(spec.exposure) {
            return None;
        }
        Some(ToolSpecView::from_spec(spec))
    }

    /// Check if a tool is available in the current profile and executable
    /// under the current audience.
    ///
    /// Returns true only when the tool passes both profile membership and
    /// audience/exposure checks. Use [`has_registered_tool`](Self::has_registered_tool)
    /// to bypass audience checks.
    pub fn has_tool(&self, name: &str) -> bool {
        let profile_tools = registry::tools_for_profile(self.profile.as_str());
        if !profile_tools.iter().any(|s| s.name == name) {
            return false;
        }
        if let Some(spec) = registry::get_tool(name) {
            self.audience.can_execute_exposure(spec.exposure)
        } else {
            false
        }
    }

    /// Get tool metadata without profile or audience filtering.
    ///
    /// Returns metadata for any registered tool regardless of profile
    /// membership or audience restrictions. Intended for administrative
    /// and debugging use only.
    pub fn get_tool_unfiltered(&self, name: &str) -> Option<ToolSpecView> {
        let spec = registry::get_tool(name)?;
        Some(ToolSpecView::from_spec(spec))
    }

    /// Check if a tool is registered, regardless of profile or audience.
    ///
    /// Returns true for any tool in the registry, including hidden and
    /// harness-only tools. Use [`has_tool`](Self::has_tool) for the
    /// policy-aware check.
    pub fn has_registered_tool(&self, name: &str) -> bool {
        registry::get_tool(name).is_some()
    }

    /// Prepare a tool call by performing lookup, profile check, and validation.
    ///
    /// Returns a [`ToolCallOutcome`] that the caller can match on to decide
    /// how to handle pre-execution errors vs. ready-to-execute handlers.
    /// This is the shared core used by both `call_json` and the MCP server.
    ///
    /// Delegates to [`prepare_tool_call_with_policy`](Self::prepare_tool_call_with_policy)
    /// using the registry's stored profile, audience, and compatibility mode.
    pub fn prepare_tool_call(&self, name: &str, args: &Value) -> ToolCallOutcome {
        self.prepare_tool_call_with_policy(
            name,
            args,
            &self.profile,
            self.audience,
            self.compat_mode,
        )
    }

    /// Prepare a tool call with explicit effective policy, performing lookup,
    /// profile check, audience check, and validation.
    ///
    /// All dispatch surfaces should use this function to ensure consistent
    /// policy enforcement. The effective profile and audience take precedence
    /// over the registry's stored values.
    ///
    /// # Dispatch ordering
    ///
    /// All dispatch surfaces follow this consistent ordering:
    ///
    /// 1. **Registry lookup** — find the tool handler by name.
    /// 2. **Profile check** — verify the tool is in the effective profile.
    /// 3. **Audience/exposure check** — verify the audience can execute the
    ///    tool's exposure level.
    /// 4. **Schema validation** — validate arguments against the tool schema.
    /// 5. **Serialized input-budget check** — (in `call_json_with_*` methods)
    ///    verify serialized args fit within `max_input_bytes`.
    /// 6. **Cancellation-before-execution check** — (via `BudgetContext`)
    ///    check the cancel flag before invoking the handler.
    /// 7. **Handler execution** — invoke the tool handler.
    /// 8. **Output truncation and limits metadata** — apply budget-aware
    ///    truncation to the response.
    ///
    /// Steps 5–8 occur in the `call_json_with_*` methods, not in this
    /// function. This function handles steps 1–4.
    pub fn prepare_tool_call_with_policy(
        &self,
        name: &str,
        args: &Value,
        effective_profile: &Profile,
        effective_audience: ToolAudience,
        effective_compat: CompatibilityMode,
    ) -> ToolCallOutcome {
        match self.prepare_tool_call_internal(
            name,
            args,
            effective_profile,
            effective_audience,
            effective_compat,
        ) {
            Ok(prepared) => ToolCallOutcome::Ready {
                handler: prepared.handler,
            },
            Err(error) => ToolCallOutcome::PreExecutionError(error),
        }
    }

    /// Internal preparation projection used by the MCP boundary. It retains
    /// the one registry lookup's cost metadata so the server does not perform
    /// a second scan solely to resolve the execution budget.
    pub(crate) fn prepare_tool_call_internal(
        &self,
        name: &str,
        args: &Value,
        effective_profile: &Profile,
        effective_audience: ToolAudience,
        effective_compat: CompatibilityMode,
    ) -> Result<PreparedToolCall, ToolCallError> {
        let spec =
            registry::get_tool(name).ok_or_else(|| ToolCallError::UnknownTool(name.to_string()))?;
        let in_profile = effective_profile.as_str() == "full"
            && spec.exposure != ToolExposure::Hidden
            || spec.profiles.contains(&effective_profile.as_str());
        if !in_profile {
            return Err(ToolCallError::ToolUnavailable {
                tool: name.to_string(),
                profile: effective_profile.to_string(),
            });
        }
        if !effective_audience.can_execute_exposure(spec.exposure) {
            return Err(ToolCallError::ToolNotAllowedForAudience {
                tool: name.to_string(),
                profile: effective_profile.to_string(),
                audience: format!("{:?}", effective_audience),
                exposure: spec.exposure.as_str().to_string(),
            });
        }
        if let Some(msg) = schema_validation::validate_arguments(name, args, effective_compat) {
            return Err(ToolCallError::InvalidArguments(msg));
        }
        Ok(PreparedToolCall {
            handler: spec.handler,
            cost: spec.cost,
        })
    }

    /// Call a tool by name with JSON arguments, returning the full `ToolResponse`.
    ///
    /// This is the primary entry point for in-process tool execution. It performs:
    /// 1. Tool lookup by name
    /// 2. Profile availability check
    /// 3. Argument schema validation
    /// 4. Synchronous tool handler execution
    ///
    /// **Note**: This method executes the handler directly on the calling thread
    /// with no elapsed-time enforcement or concurrency limiting. For budget-aware
    /// execution, use [`call_json_with_budget`](Self::call_json_with_budget) or
    /// [`call_json_with_execution_context`](Self::call_json_with_execution_context).
    ///
    /// Tool-level failures (e.g., invalid input) return `Ok(response)` with
    /// `response.ok == false`. Registry-level failures return `Err(ToolCallError)`.
    pub fn call_json(&self, name: &str, args: Value) -> Result<ToolResponse, ToolCallError> {
        match self.prepare_tool_call(name, &args) {
            ToolCallOutcome::Ready { handler } => {
                let mut eval_ctx = EvalContext::new();
                Ok(budget::with_eval_context(&mut eval_ctx, || handler(&args)))
            }
            ToolCallOutcome::PreExecutionError(e) => Err(e),
        }
    }

    /// Call a tool with an explicit budget, applying resource limits and output truncation.
    ///
    /// This is the budget-aware entry point for in-process tool execution. It:
    /// 1. Validates profile, audience, and arguments on the calling thread
    /// 2. Resolves the tool's default budget from its declared `ToolCost`
    /// 3. Merges with any explicit `budget` override
    /// 4. Executes the approved handler on a bounded worker pool with elapsed-time enforcement
    /// 5. Truncates output findings and result to fit within budget limits
    /// 6. Populates `limits_applied` on the response
    ///
    /// Pre-execution failures (unknown tool, profile mismatch, invalid args)
    /// return `Err(ToolCallError)`. Runtime failures (timeout, queue full)
    /// return `Ok(ToolResponse)` with appropriate machine codes.
    ///
    /// Use this method when the caller needs deterministic resource discipline.
    /// For simple calls without budget enforcement, use [`call_json`](Self::call_json).
    pub fn call_json_with_budget(
        &self,
        name: &str,
        args: Value,
        budget: Option<ToolBudget>,
    ) -> Result<ToolResponse, ToolCallError> {
        let outcome = self.prepare_tool_call(name, &args);
        let handler = match outcome {
            ToolCallOutcome::Ready { handler } => handler,
            ToolCallOutcome::PreExecutionError(e) => return Err(e),
        };
        let effective_budget = Self::resolve_budget(name, budget)?;
        if let Some(resp) = Self::check_input_size(&args, &effective_budget, name) {
            return Ok(resp);
        }
        self.run_bounded(handler, args, None, &effective_budget, name)
    }

    /// Call a tool with an explicit budget and cancellation flag, applying resource
    /// limits and output truncation.
    ///
    /// This extends [`call_json_with_budget`](Self::call_json_with_budget) with
    /// an external cancellation flag. The flag is installed as the thread-local
    /// cancel flag during handler execution so that high-risk handlers that create
    /// their own `BudgetContext` (via [`budget::for_handler`]) will inherit cancellation.
    /// On timeout, the flag is set to `true` by the pool so the handler can observe it.
    pub fn call_json_with_context(
        &self,
        name: &str,
        args: Value,
        budget: Option<ToolBudget>,
        cancel_flag: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
    ) -> Result<ToolResponse, ToolCallError> {
        let outcome = self.prepare_tool_call(name, &args);
        let handler = match outcome {
            ToolCallOutcome::Ready { handler } => handler,
            ToolCallOutcome::PreExecutionError(e) => return Err(e),
        };
        let effective_budget = Self::resolve_budget(name, budget)?;
        if let Some(resp) = Self::check_input_size(&args, &effective_budget, name) {
            return Ok(resp);
        }
        self.run_bounded(handler, args, cancel_flag, &effective_budget, name)
    }

    /// Call a tool with a full execution context, applying all dispatch-scoped state.
    ///
    /// This is the context-aware entry point that uses the provided [`ExecutionContext`]
    /// for budget resolution, cancellation, profile, audience, and compatibility mode.
    /// When `ctx.profile` or `ctx.audience` is `Some`, those values take precedence
    /// over the registry's stored values; when `None`, the registry's defaults are
    /// used as fallback.
    ///
    /// # Eval-context handling
    ///
    /// `ctx.eval_ctx` is **cloned** before dispatch (line `let mut eval_ctx = ctx.eval_ctx.clone()`).
    /// The handler receives a thread-local reference to the clone via
    /// [`budget::with_eval_context`]. Only tools that opt into the eval-context bridge
    /// (currently **`math_eval`**) read from it via [`budget::with_current_eval_context`].
    /// Any PRNG draws, memory mutations, or variable assignments inside the handler are
    /// confined to the clone and do not modify the caller's `ExecutionContext`.
    /// Two calls with identical seeds produce the same first random value.
    pub fn call_json_with_execution_context(
        &self,
        name: &str,
        args: Value,
        ctx: &ExecutionContext,
    ) -> Result<ToolResponse, ToolCallError> {
        let effective_profile = ctx.profile.clone().unwrap_or_else(|| self.profile.clone());
        let effective_audience = ctx.audience.unwrap_or(self.audience);
        let effective_compat = ctx.compatibility_mode;

        let outcome = self.prepare_tool_call_with_policy(
            name,
            &args,
            &effective_profile,
            effective_audience,
            effective_compat,
        );
        let handler = match outcome {
            ToolCallOutcome::Ready { handler } => handler,
            ToolCallOutcome::PreExecutionError(e) => return Err(e),
        };
        let effective_budget = Self::resolve_budget(name, ctx.budget)?;
        if let Some(resp) = Self::check_input_size(&args, &effective_budget, name) {
            return Ok(resp);
        }

        let eval_ctx_clone = ctx.eval_ctx.clone();
        let cancel_flag = ctx
            .cancellation
            .clone()
            .unwrap_or_else(|| Arc::new(AtomicBool::new(false)));
        self.run_bounded_with_ctx(
            handler,
            args,
            eval_ctx_clone,
            cancel_flag,
            &effective_budget,
            name,
        )
    }

    /// Call a tool with an immutable execution template.
    ///
    /// `eval_ctx` is cloned before dispatch — handler mutations do not persist.
    /// Repeated calls with the same template are reproducible.
    /// This is the preferred entry point for ordinary deterministic agent calls.
    ///
    /// Alias for [`call_json_with_execution_context`](Self::call_json_with_execution_context)
    /// with explicit immutable-template semantics.
    ///
    /// # Examples
    ///
    /// ```
    /// use eggsact::agent::{ToolRegistry, ExecutionContext, Profile, ToolAudience};
    ///
    /// let registry = ToolRegistry::default();
    /// let ctx = ExecutionContext::mcp_default(Profile::Full, ToolAudience::Model);
    ///
    /// // Both calls produce the same result — the template is immutable.
    /// let r1 = registry.call_json_with_execution_template(
    ///     "math_eval",
    ///     serde_json::json!({"expression": "2 + 3"}),
    ///     &ctx,
    /// ).unwrap();
    /// let r2 = registry.call_json_with_execution_template(
    ///     "math_eval",
    ///     serde_json::json!({"expression": "2 + 3"}),
    ///     &ctx,
    /// ).unwrap();
    /// assert!(r1.ok && r2.ok);
    /// assert_eq!(
    ///     r1.result.unwrap()["value"],
    ///     r2.result.unwrap()["value"],
    /// );
    /// ```
    pub fn call_json_with_execution_template(
        &self,
        name: &str,
        args: Value,
        template: &ExecutionContext,
    ) -> Result<ToolResponse, ToolCallError> {
        self.call_json_with_execution_context(name, args, template)
    }

    /// Call a tool with a mutable execution context.
    ///
    /// # Transaction safety
    ///
    /// On pre-execution policy failure or parse/evaluation error, `ctx.eval_ctx`
    /// is unchanged (no partial mutations). On success, `ctx.eval_ctx` may be
    /// mutated in place.
    ///
    /// # Limitation: `math_eval` does not persist calculator state
    ///
    /// The dispatch layer clones `ctx.eval_ctx` before the handler runs.
    /// PRNG draws, memory mutations, and variable assignments from `math_eval`
    /// therefore do **not** persist back into `ctx.eval_ctx`. To persist
    /// calculator state, use
    /// [`evaluate_with_context`](crate::calc::evaluate_with_context) or
    /// [`run_with_context`](crate::calc::run_with_context) directly.
    ///
    /// # Note
    ///
    /// This method is **deprecated** as of 1.0.0. Calculator-backed tool
    /// handlers do not persist state through the `_mut` dispatch path.
    #[deprecated(
        since = "1.0.0",
        note = "Does not persist calculator state through math_eval. Use evaluate_with_context() or run_with_context() directly for persistent calculator sessions. The method remains useful for transaction safety on failure paths."
    )]
    pub fn call_json_with_execution_context_mut(
        &self,
        name: &str,
        args: Value,
        ctx: &mut ExecutionContext,
    ) -> Result<ToolResponse, ToolCallError> {
        // Deprecated: delegate to immutable dispatch. Calculator state does not
        // persist through math_eval regardless of commit-slot machinery.
        self.call_json_with_execution_context(name, args, ctx)
    }

    /// Call a tool and return only the result `Value`, or `null` on error.
    ///
    /// Convenience wrapper around [`call_json`](Self::call_json) that
    /// extracts the `result` field from the response.
    pub fn call_json_value(&self, name: &str, args: Value) -> Value {
        match self.call_json(name, args) {
            Ok(response) => response.result.unwrap_or(Value::Null),
            Err(_) => Value::Null,
        }
    }

    /// Resolve effective budget: use the explicit override if provided,
    /// otherwise look up the tool's default budget from its declared cost.
    fn resolve_budget(
        name: &str,
        budget_override: Option<ToolBudget>,
    ) -> Result<ToolBudget, ToolCallError> {
        match budget_override {
            Some(b) => Ok(b),
            None => {
                let spec = registry::get_tool(name)
                    .ok_or_else(|| ToolCallError::UnknownTool(name.to_string()))?;
                Ok(budget_for_tool_resolved(name, spec))
            }
        }
    }

    /// Check that serialized args fit within the budget's max_input_bytes.
    /// Returns `Some(response)` if the check fails (caller should return it),
    /// or `None` if args are within budget.
    fn check_input_size(args: &Value, budget: &ToolBudget, name: &str) -> Option<ToolResponse> {
        struct Counter(usize);
        impl std::io::Write for Counter {
            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
                self.0 = self.0.saturating_add(bytes.len());
                Ok(bytes.len())
            }

            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }
        let mut counter = Counter(0);
        let serialized_len = serde_json::to_writer(&mut counter, args)
            .map(|_| counter.0)
            .unwrap_or(0);
        if serialized_len > budget.max_input_bytes {
            Some(ToolResponse::error_with_code(
                "input_too_large",
                crate::mcp::machine_codes::INPUT_TOO_LARGE,
                &format!(
                    "Serialized arguments ({} bytes) exceed budget max_input_bytes ({} bytes)",
                    serialized_len, budget.max_input_bytes
                ),
                None,
                Some(name),
            ))
        } else {
            None
        }
    }

    /// Shared bounded dispatch: resolve eval context from registry defaults,
    /// submit handler to sync pool with budget/timeout/cancellation, truncate.
    fn run_bounded(
        &self,
        handler: registry::ToolHandler,
        args: Value,
        cancel_flag: Option<Arc<AtomicBool>>,
        budget: &ToolBudget,
        name: &str,
    ) -> Result<ToolResponse, ToolCallError> {
        let eval_ctx = crate::calc::EvalContext::mcp_mode();
        let flag = cancel_flag.unwrap_or_else(|| Arc::new(AtomicBool::new(false)));
        self.run_bounded_with_ctx(handler, args, eval_ctx, flag, budget, name)
    }

    /// Shared bounded dispatch with a caller-provided eval context clone.
    fn run_bounded_with_ctx(
        &self,
        handler: registry::ToolHandler,
        args: Value,
        eval_ctx: EvalContext,
        cancel_flag: Arc<AtomicBool>,
        budget: &ToolBudget,
        name: &str,
    ) -> Result<ToolResponse, ToolCallError> {
        let timeout = Duration::from_millis(budget.max_elapsed_ms);
        let handler_cancel = cancel_flag.clone();
        let result = crate::mcp::sync_pool::sync_pool().submit_cancellable(
            move || {
                budget::with_cancel_flag(Some(handler_cancel), || {
                    let mut eval_ctx = eval_ctx;
                    crate::mcp::budget::with_eval_context(&mut eval_ctx, || handler(&args))
                })
            },
            timeout,
            cancel_flag,
        );
        match result {
            Ok(mut response) => {
                truncate_response(&mut response, budget);
                Ok(response)
            }
            Err(pool_error) => Ok(pool_error.to_tool_response(name)),
        }
    }
}

/// Outcome of [`ToolRegistry::prepare_tool_call`].
///
/// This enum allows the MCP server to handle pre-execution errors as
/// JSON-RPC errors while executing tools via the shared handler path.
pub enum ToolCallOutcome {
    /// Tool is ready to execute — caller should invoke `handler(&args)`.
    Ready { handler: registry::ToolHandler },
    /// Pre-execution error (unknown tool, profile mismatch, invalid args).
    PreExecutionError(ToolCallError),
}

pub(crate) struct PreparedToolCall {
    pub(crate) handler: registry::ToolHandler,
    pub(crate) cost: crate::mcp::registry::ToolCost,
}

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

/// Resolve the effective budget for a tool by combining its declared cost
/// with any tool-specific overrides from the budget module.
fn budget_for_tool_resolved(name: &str, spec: &ToolSpec) -> ToolBudget {
    budget::budget_for_tool(name, spec.cost)
}

/// Re-export budget types for convenience.
pub use crate::mcp::budget::{BudgetContext, BudgetTier, ToolBudget as ToolBudgetType};

/// Source of a tool call, for logging and auditing.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum ExecutionSource {
    /// Direct CLI invocation.
    Cli,
    /// Library/API call.
    Library,
    /// MCP server dispatch.
    Mcp,
    /// In-process agent call.
    Agent,
    /// Test invocation.
    #[default]
    Test,
}

/// Per-call execution context that carries all dispatch-scoped state.
///
/// `ExecutionContext` unifies profile, audience, budget, cancellation,
/// and compatibility mode into a single explicit parameter. This replaces
/// implicit reliance on global statics (ACTIVE_PROFILE, thread-local
/// cancel flags) for new code paths.
///
/// # Active dispatch controls
///
/// - **`profile`** — selects which tools are available (e.g. `full`, `codegg_core_min`).
/// - **`audience`** — filters tools by exposure level (Model / Harness / Debug).
/// - **`compatibility_mode`** — selects validation behavior (`EggcalcPython` vs `StrictNative`).
/// - **`budget`** — per-tool resource limits (max input/output bytes, elapsed time).
/// - **`cancellation`** — cooperative cancellation flag checked at pipeline stages.
///
/// # Eval-context bridge (`eval_ctx`)
///
/// The `eval_ctx` field holds calculator state (PRNG seed, memory registers,
/// user-defined variables). Only calculator-backed tools that opt into the
/// eval-context bridge read from it; the sole current consumer is **`math_eval`**.
///
/// `eval_ctx` is **always cloned at dispatch** — `call_json_with_execution_context`
/// clones explicitly before submitting to the sync pool. All PRNG draws,
/// memory mutations, and variable assignments inside `math_eval` operate on
/// the dispatch-owned clone and **do not persist back** to the caller's
/// `ExecutionContext`. Two calls with the same seed produce the same first
/// random value.
///
/// To persist calculator state across calls, use
/// [`evaluate_with_context`](crate::calc::evaluate_with_context) or
/// [`run_with_context`](crate::calc::run_with_context) directly — they accept
/// a mutable `&mut EvalContext` reference without cloning.
///
/// # MCP compatibility
///
/// The MCP server still resolves its active profile from the startup
/// environment (`EGGCALC_MCP_PROFILE`) at init time. An in-process
/// `ExecutionContext` does not change the MCP JSON-RPC wire protocol;
/// it only affects `ToolRegistry::call_json_with_execution_context` and
/// the typed preflight wrappers.
///
/// Legacy APIs (`call_json`, `call_json_with_budget`, `call_json_with_context`)
/// remain as wrappers for backward compatibility.
pub struct ExecutionContext {
    /// Calculator evaluation context with per-call mutable state.
    pub eval_ctx: EvalContext,
    /// Compatibility mode for validation and error messages.
    pub compatibility_mode: CompatibilityMode,
    /// Active profile for tool filtering.
    pub profile: Option<Profile>,
    /// Audience for tool exposure filtering.
    pub audience: Option<ToolAudience>,
    /// Resource budget for this call.
    pub budget: Option<ToolBudget>,
    /// Cancellation flag for cooperative cancellation.
    pub cancellation: Option<Arc<AtomicBool>>,
    /// Optional request ID for tracing.
    pub request_id: Option<String>,
    /// Source of the call.
    pub source: ExecutionSource,
}

impl ExecutionContext {
    /// Create a default context for CLI invocation.
    pub fn cli_default() -> Self {
        Self {
            eval_ctx: EvalContext::new(),
            compatibility_mode: CompatibilityMode::default(),
            profile: None,
            audience: None,
            budget: None,
            cancellation: None,
            request_id: None,
            source: ExecutionSource::Cli,
        }
    }

    /// Create a default context for library/API calls.
    pub fn library_default() -> Self {
        Self {
            eval_ctx: EvalContext::new(),
            compatibility_mode: CompatibilityMode::StrictNative,
            profile: None,
            audience: None,
            budget: None,
            cancellation: None,
            request_id: None,
            source: ExecutionSource::Library,
        }
    }

    /// Create a default context for MCP server dispatch.
    pub fn mcp_default(profile: Profile, audience: ToolAudience) -> Self {
        Self {
            eval_ctx: EvalContext::mcp_mode(),
            compatibility_mode: CompatibilityMode::EggcalcPython,
            profile: Some(profile),
            audience: Some(audience),
            budget: None,
            cancellation: None,
            request_id: None,
            source: ExecutionSource::Mcp,
        }
    }

    /// Create a default context for in-process agent calls.
    pub fn agent_default(profile: Profile, audience: ToolAudience) -> Self {
        Self {
            eval_ctx: EvalContext::new(),
            compatibility_mode: CompatibilityMode::StrictNative,
            profile: Some(profile),
            audience: Some(audience),
            budget: None,
            cancellation: None,
            request_id: None,
            source: ExecutionSource::Agent,
        }
    }

    /// Create a default context for test invocations.
    pub fn test_default() -> Self {
        Self {
            eval_ctx: EvalContext::new(),
            compatibility_mode: CompatibilityMode::default(),
            profile: None,
            audience: None,
            budget: None,
            cancellation: None,
            request_id: None,
            source: ExecutionSource::Test,
        }
    }

    /// Set the resource budget for this call.
    pub fn with_budget(mut self, budget: ToolBudget) -> Self {
        self.budget = Some(budget);
        self
    }

    /// Set the cancellation flag for cooperative cancellation.
    pub fn with_cancellation(mut self, flag: Arc<AtomicBool>) -> Self {
        self.cancellation = Some(flag);
        self
    }

    /// Set the request ID for tracing.
    pub fn with_request_id(mut self, id: impl Into<String>) -> Self {
        self.request_id = Some(id.into());
        self
    }

    /// Set the calculator evaluation context for this call.
    ///
    /// The provided `eval_ctx` is **cloned** into the `ExecutionContext`, so the
    /// caller's original is unaffected. At dispatch time (`call_json_with_execution_context`),
    /// the context is cloned again before the handler runs. PRNG draws, memory
    /// mutations, and variable assignments inside `math_eval` operate on the
    /// per-call clone and never propagate back.
    ///
    /// This lets callers seed repeated calls with identical state and get
    /// reproducible first random values, while retaining full control over the
    /// seed/registers between calls.
    pub fn with_eval_context(mut self, eval_ctx: &EvalContext) -> Self {
        self.eval_ctx = eval_ctx.clone();
        self
    }

    /// Create a builder for constructing an `ExecutionContext` with named fields.
    pub fn builder() -> ExecutionContextBuilder {
        ExecutionContextBuilder::default()
    }
}

/// Builder for `ExecutionContext` with named field initialization.
#[derive(Default)]
pub struct ExecutionContextBuilder {
    eval_ctx: Option<EvalContext>,
    compatibility_mode: Option<CompatibilityMode>,
    profile: Option<Profile>,
    audience: Option<ToolAudience>,
    budget: Option<ToolBudget>,
    cancellation: Option<Arc<AtomicBool>>,
    request_id: Option<String>,
    source: Option<ExecutionSource>,
}

impl ExecutionContextBuilder {
    pub fn eval_ctx(mut self, eval_ctx: EvalContext) -> Self {
        self.eval_ctx = Some(eval_ctx);
        self
    }

    pub fn compatibility_mode(mut self, mode: CompatibilityMode) -> Self {
        self.compatibility_mode = Some(mode);
        self
    }

    pub fn profile(mut self, profile: Profile) -> Self {
        self.profile = Some(profile);
        self
    }

    pub fn audience(mut self, audience: ToolAudience) -> Self {
        self.audience = Some(audience);
        self
    }

    pub fn budget(mut self, budget: ToolBudget) -> Self {
        self.budget = Some(budget);
        self
    }

    pub fn cancellation(mut self, flag: Arc<AtomicBool>) -> Self {
        self.cancellation = Some(flag);
        self
    }

    pub fn request_id(mut self, id: impl Into<String>) -> Self {
        self.request_id = Some(id.into());
        self
    }

    pub fn source(mut self, source: ExecutionSource) -> Self {
        self.source = Some(source);
        self
    }

    pub fn build(self) -> ExecutionContext {
        ExecutionContext {
            eval_ctx: self.eval_ctx.unwrap_or_default(),
            compatibility_mode: self.compatibility_mode.unwrap_or_default(),
            profile: self.profile,
            audience: self.audience,
            budget: self.budget,
            cancellation: self.cancellation,
            request_id: self.request_id,
            source: self.source.unwrap_or_default(),
        }
    }
}

impl Default for ExecutionContext {
    fn default() -> Self {
        Self::test_default()
    }
}

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

    #[test]
    #[allow(deprecated)]
    fn tool_registry_default_lists_tools() {
        let registry = ToolRegistry::default();
        let tools = registry.available_tools();
        assert!(!tools.is_empty(), "should have tools in full profile");
        // text_equal is in the full profile
        assert!(tools.iter().any(|t| t.name == "text_equal"));
    }

    #[test]
    #[allow(deprecated)]
    fn tool_registry_profile_filters_tools() {
        let registry = ToolRegistry::with_profile(Profile::CodeggCoreMin);
        let tools = registry.available_tools();
        // codegg_core_min should have fewer tools than full
        let full_count = ToolRegistry::default().available_tools().len();
        assert!(tools.len() <= full_count);
        // All tools should be in the codegg_core_min profile
        for tool in &tools {
            assert!(
                tool.profiles.contains(&"codegg_core_min".to_string()),
                "tool {} not in codegg_core_min profile",
                tool.name
            );
        }
    }

    #[test]
    fn tool_registry_unknown_tool_returns_error() {
        let registry = ToolRegistry::default();
        let result = registry.call_json("nonexistent_tool", serde_json::json!({}));
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::UnknownTool(name) => assert_eq!(name, "nonexistent_tool"),
            other => panic!("expected UnknownTool, got {:?}", other),
        }
    }

    #[test]
    fn tool_registry_outside_profile_returns_error() {
        // Create a registry with a limited profile
        let registry = ToolRegistry::with_profile(Profile::HumanMath);
        // math_eval should be available in human_math
        assert!(registry.has_tool("math_eval"));
        // text_equal might not be in human_math
        let result = registry.call_json("text_equal", serde_json::json!({"a": "x", "b": "x"}));
        if let Err(ToolCallError::ToolUnavailable { tool, .. }) = &result {
            assert_eq!(tool, "text_equal");
        }
        // It should either be ToolUnavailable or succeed (if in profile)
    }

    #[test]
    fn tool_registry_invalid_arguments_returns_error() {
        let registry = ToolRegistry::default();
        // math_eval requires "expression"
        let result = registry.call_json("math_eval", serde_json::json!({}));
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::InvalidArguments(msg) => {
                assert!(msg.contains("Missing required argument"));
            }
            other => panic!("expected InvalidArguments, got {:?}", other),
        }
    }

    #[test]
    fn tool_registry_call_json_succeeds() {
        let registry = ToolRegistry::default();
        let response = registry
            .call_json("text_equal", serde_json::json!({"a": "foo", "b": "foo"}))
            .unwrap();
        assert!(response.ok);
    }

    #[test]
    fn tool_registry_call_json_value_succeeds() {
        let registry = ToolRegistry::default();
        let value =
            registry.call_json_value("text_equal", serde_json::json!({"a": "foo", "b": "foo"}));
        assert!(value.get("equal").and_then(|v| v.as_bool()) == Some(true));
    }

    #[test]
    fn tool_registry_get_tool_returns_spec() {
        let registry = ToolRegistry::default();
        let spec = registry.get_tool("text_equal");
        assert!(spec.is_some());
        let spec = spec.unwrap();
        assert_eq!(spec.view.name, "text_equal");
        assert!(spec.input_schema.is_object());
    }

    #[test]
    fn tool_registry_profile_display() {
        assert_eq!(Profile::Full.to_string(), "full");
        assert_eq!(Profile::CodeggCore.to_string(), "codegg_core");
        assert_eq!(Profile::Custom("test".to_string()).to_string(), "test");
    }

    #[test]
    fn tool_registry_profile_from_str() {
        assert_eq!(Profile::from_str_opt("full"), Some(Profile::Full));
        assert_eq!(
            Profile::from_str_opt("codegg_core"),
            Some(Profile::CodeggCore)
        );
        assert_eq!(Profile::from_str_opt("nonexistent"), None);
        assert_eq!(Profile::from_str_opt("coddeg_core_typo"), None);
    }

    #[test]
    fn profile_custom_constructor() {
        let p = Profile::custom("my_custom");
        assert_eq!(p, Profile::Custom("my_custom".to_string()));
        assert_eq!(p.as_str(), "my_custom");
        assert_eq!(p.to_string(), "my_custom");
        // custom() allows any name including known ones
        let p2 = Profile::custom("full");
        assert_eq!(p2, Profile::Custom("full".to_string()));
    }

    #[test]
    fn tool_audience_default_is_model() {
        let registry = ToolRegistry::default();
        assert_eq!(registry.audience(), ToolAudience::Model);
    }

    #[test]
    fn tool_audience_getter_returns_constructor_value() {
        let registry =
            ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Harness);
        assert_eq!(registry.audience(), ToolAudience::Harness);
    }

    #[test]
    fn model_safe_excludes_harness_only_tools() {
        let registry = ToolRegistry::default();
        let model_tools = registry.available_tools_model_safe();
        let harness_only_names: Vec<String> = registry::tools_for_profile("full")
            .into_iter()
            .filter(|t| t.exposure == ToolExposure::HarnessOnly)
            .map(|t| t.name.to_string())
            .collect();
        for name in &harness_only_names {
            assert!(
                !model_tools.iter().any(|t| t.name == *name),
                "harness_only tool '{}' should not appear in model-safe listing",
                name
            );
        }
    }

    #[test]
    #[allow(deprecated)]
    fn model_safe_is_subset_of_available_tools() {
        let registry = ToolRegistry::default();
        let all_tools = registry.available_tools();
        let model_tools = registry.available_tools_model_safe();
        assert!(model_tools.len() <= all_tools.len());
        for tool in &model_tools {
            assert!(
                all_tools.iter().any(|t| t.name == tool.name),
                "model-safe tool '{}' should also appear in available_tools()",
                tool.name
            );
        }
    }

    #[test]
    fn harness_audience_includes_harness_only_tools() {
        let registry = ToolRegistry::with_profile(Profile::CodeggPreflight);
        let harness_tools = registry.available_tools_for_audience(ToolAudience::Harness);
        let harness_only_in_profile: Vec<String> = registry::tools_for_profile("codegg_preflight")
            .into_iter()
            .filter(|t| t.exposure == ToolExposure::HarnessOnly)
            .map(|t| t.name.to_string())
            .collect();
        assert!(
            !harness_only_in_profile.is_empty(),
            "codegg_preflight should have harness-only tools"
        );
        for name in &harness_only_in_profile {
            assert!(
                harness_tools.iter().any(|t| t.name == *name),
                "harness audience for codegg_preflight should include '{}'",
                name
            );
        }
    }

    #[test]
    fn harness_audience_for_codegg_core_min_excludes_harness_only() {
        let registry = ToolRegistry::with_profile(Profile::CodeggCoreMin);
        let harness_tools = registry.available_tools_for_audience(ToolAudience::Harness);
        for spec in registry::tools_for_profile("codegg_core_min") {
            if spec.exposure == ToolExposure::HarnessOnly {
                assert!(
                    !harness_tools.iter().any(|t| t.name == spec.name),
                    "harness audience for codegg_core_min should not include harness-only '{}'",
                    spec.name
                );
            }
        }
    }

    #[test]
    fn debug_audience_includes_all_non_hidden() {
        let registry = ToolRegistry::default();
        let debug_tools = registry.available_tools_for_audience(ToolAudience::Debug);
        let all_non_hidden: Vec<String> = registry::tools_for_profile("full")
            .into_iter()
            .filter(|t| t.exposure != ToolExposure::Hidden)
            .map(|t| t.name.to_string())
            .collect();
        assert_eq!(debug_tools.len(), all_non_hidden.len());
    }

    #[test]
    fn with_profile_and_audience_combines_both() {
        let registry =
            ToolRegistry::with_profile_and_audience(Profile::CodeggPreflight, ToolAudience::Model);
        assert_eq!(registry.profile(), &Profile::CodeggPreflight);
        assert_eq!(registry.audience(), ToolAudience::Model);
        let tools = registry.available_tools_model_safe();
        for spec in registry::tools_for_profile("codegg_preflight") {
            if spec.exposure == ToolExposure::HarnessOnly {
                assert!(
                    !tools.iter().any(|t| t.name == spec.name),
                    "Model audience for codegg_preflight should not include harness-only '{}'",
                    spec.name
                );
            }
        }
    }

    #[test]
    fn current_audience_model_excludes_harness_only() {
        let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
        let current = registry.available_tools_for_current_audience();
        let explicit = registry.available_tools_for_audience(ToolAudience::Model);
        assert_eq!(current.len(), explicit.len());
        for t in &current {
            assert!(!t.exposure.contains("harness_only"));
        }
    }

    #[test]
    fn current_audience_harness_includes_preflight_harness_tools() {
        let registry = ToolRegistry::with_profile_and_audience(
            Profile::CodeggPreflight,
            ToolAudience::Harness,
        );
        let tools = registry.available_tools_for_current_audience();
        // codegg_preflight has harness-only tools like shell_split, path_scope_check, etc.
        assert!(
            tools.iter().any(|t| t.name == "shell_split"),
            "harness audience should include shell_split"
        );
        assert!(
            tools.iter().any(|t| t.name == "path_scope_check"),
            "harness audience should include path_scope_check"
        );
    }

    #[test]
    fn current_audience_debug_matches_debug_listing() {
        let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Debug);
        let current = registry.available_tools_for_current_audience();
        let explicit = registry.available_tools_for_audience(ToolAudience::Debug);
        assert_eq!(current.len(), explicit.len());
    }

    // -- Exposure helper tests --

    #[test]
    fn model_audience_allows_default_exposure() {
        assert!(ToolAudience::Model.can_execute_exposure(ToolExposure::Default));
    }

    #[test]
    fn model_audience_allows_contextual_exposure() {
        assert!(ToolAudience::Model.can_execute_exposure(ToolExposure::Contextual));
    }

    #[test]
    fn model_audience_allows_expert_only_exposure() {
        assert!(ToolAudience::Model.can_execute_exposure(ToolExposure::ExpertOnly));
    }

    #[test]
    fn model_audience_rejects_harness_only_exposure() {
        assert!(!ToolAudience::Model.can_execute_exposure(ToolExposure::HarnessOnly));
    }

    #[test]
    fn model_audience_rejects_hidden_exposure() {
        assert!(!ToolAudience::Model.can_execute_exposure(ToolExposure::Hidden));
    }

    #[test]
    fn harness_audience_allows_default_exposure() {
        assert!(ToolAudience::Harness.can_execute_exposure(ToolExposure::Default));
    }

    #[test]
    fn harness_audience_allows_harness_only_exposure() {
        assert!(ToolAudience::Harness.can_execute_exposure(ToolExposure::HarnessOnly));
    }

    #[test]
    fn harness_audience_rejects_hidden_exposure() {
        assert!(!ToolAudience::Harness.can_execute_exposure(ToolExposure::Hidden));
    }

    #[test]
    fn debug_audience_allows_default_exposure() {
        assert!(ToolAudience::Debug.can_execute_exposure(ToolExposure::Default));
    }

    #[test]
    fn debug_audience_allows_harness_only_exposure() {
        assert!(ToolAudience::Debug.can_execute_exposure(ToolExposure::HarnessOnly));
    }

    #[test]
    fn debug_audience_rejects_hidden_exposure() {
        assert!(!ToolAudience::Debug.can_execute_exposure(ToolExposure::Hidden));
    }

    // -- Registry audience enforcement at dispatch time --

    #[test]
    fn model_audience_rejects_harness_only_tool_call() {
        // Find a harness-only tool in the full profile
        let harness_tool = registry::tools_for_profile("full")
            .into_iter()
            .find(|t| t.exposure == ToolExposure::HarnessOnly)
            .expect("full profile should have harness-only tools");
        let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
        let result = registry.call_json(harness_tool.name, serde_json::json!({}));
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::ToolNotAllowedForAudience { tool, exposure, .. } => {
                assert_eq!(tool, harness_tool.name);
                assert_eq!(exposure, "harness_only");
            }
            other => panic!("expected ToolNotAllowedForAudience, got {:?}", other),
        }
    }

    #[test]
    fn harness_audience_allows_harness_only_tool_call() {
        // Find a harness-only tool in codegg_preflight
        let harness_tool = registry::tools_for_profile("codegg_preflight")
            .into_iter()
            .find(|t| t.exposure == ToolExposure::HarnessOnly)
            .expect("codegg_preflight should have harness-only tools");
        let registry = ToolRegistry::with_profile_and_audience(
            Profile::CodeggPreflight,
            ToolAudience::Harness,
        );
        let result = registry.call_json(harness_tool.name, serde_json::json!({}));
        // Should not fail with ToolNotAllowedForAudience (may fail for other reasons like args)
        if let Err(ToolCallError::ToolNotAllowedForAudience { .. }) = result {
            panic!(
                "harness audience should allow harness-only tool: {}",
                harness_tool.name
            );
        }
    }

    #[test]
    fn restricted_profile_rejects_out_of_profile_tool() {
        let registry = ToolRegistry::with_profile(Profile::HumanMath);
        // math_eval should work in human_math
        let result = registry.call_json("math_eval", serde_json::json!({"expression": "1+1"}));
        assert!(result.is_ok());
    }

    #[test]
    fn model_audience_error_includes_tool_profile_audience_exposure() {
        let harness_tool = registry::tools_for_profile("full")
            .into_iter()
            .find(|t| t.exposure == ToolExposure::HarnessOnly)
            .expect("full profile should have harness-only tools");
        let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
        let result = registry.call_json(harness_tool.name, serde_json::json!({}));
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains(harness_tool.name));
        assert!(msg.contains("harness_only"));
        assert!(msg.contains("Model"));
    }

    #[test]
    fn call_json_with_budget_succeeds() {
        let registry = ToolRegistry::default();
        let response = registry
            .call_json_with_budget(
                "text_equal",
                serde_json::json!({"a": "foo", "b": "foo"}),
                None,
            )
            .unwrap();
        assert!(response.ok);
    }

    #[test]
    fn call_json_with_budget_explicit_cheap() {
        let registry = ToolRegistry::default();
        let response = registry
            .call_json_with_budget(
                "text_equal",
                serde_json::json!({"a": "hello", "b": "hello"}),
                Some(ToolBudget::CHEAP),
            )
            .unwrap();
        assert!(response.ok);
    }

    #[test]
    fn call_json_with_budget_truncates_findings() {
        let registry = ToolRegistry::default();
        // Use a tool that produces findings
        let response = registry
            .call_json_with_budget(
                "validate_json",
                serde_json::json!({"text": "not valid json at all"}),
                Some(ToolBudget::CHEAP.with_max_findings(1)),
            )
            .unwrap();
        // Should still succeed (findings truncated, not rejected)
        assert!(response.ok);
        if let Some(ref findings) = response.findings {
            assert!(findings.len() <= 2); // findings + possible truncation notice
        }
    }

    #[test]
    fn call_json_with_budget_unknown_tool_error() {
        let registry = ToolRegistry::default();
        let result = registry.call_json_with_budget("nonexistent", serde_json::json!({}), None);
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::UnknownTool(name) => assert_eq!(name, "nonexistent"),
            other => panic!("expected UnknownTool, got {:?}", other),
        }
    }

    // -- Workstream 4+5 regression tests: registry policy in budget-aware calls --

    #[test]
    fn human_math_rejects_text_equal_with_budget() {
        let registry = ToolRegistry::with_profile(Profile::HumanMath);
        let result = registry.call_json_with_budget(
            "text_equal",
            serde_json::json!({"a": "x", "b": "x"}),
            None,
        );
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::ToolUnavailable { tool, .. } => assert_eq!(tool, "text_equal"),
            other => panic!("expected ToolUnavailable, got {:?}", other),
        }
    }

    #[test]
    fn full_harness_allows_shell_split_with_budget() {
        let registry =
            ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Harness);
        let result = registry.call_json_with_budget(
            "shell_split",
            serde_json::json!({"command": "echo hello"}),
            None,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn full_model_rejects_shell_split_with_budget() {
        let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
        let result = registry.call_json_with_budget(
            "shell_split",
            serde_json::json!({"command": "echo hello"}),
            None,
        );
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::ToolNotAllowedForAudience { .. } => {}
            other => panic!("expected ToolNotAllowedForAudience, got {:?}", other),
        }
    }

    #[test]
    fn unknown_tool_with_budget_returns_error() {
        let registry = ToolRegistry::default();
        let result =
            registry.call_json_with_budget("nonexistent_tool_xyz", serde_json::json!({}), None);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ToolCallError::UnknownTool(_)));
    }

    #[test]
    fn invalid_args_with_budget_returns_error() {
        let registry = ToolRegistry::default();
        let result = registry.call_json_with_budget("math_eval", serde_json::json!({}), None);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolCallError::InvalidArguments(_)
        ));
    }

    #[test]
    fn human_math_rejects_text_equal_with_context() {
        let registry = ToolRegistry::with_profile(Profile::HumanMath);
        let result = registry.call_json_with_context(
            "text_equal",
            serde_json::json!({"a": "x", "b": "x"}),
            None,
            None,
        );
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::ToolUnavailable { tool, .. } => assert_eq!(tool, "text_equal"),
            other => panic!("expected ToolUnavailable, got {:?}", other),
        }
    }

    #[test]
    fn full_model_rejects_shell_split_with_context() {
        let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
        let result = registry.call_json_with_context(
            "shell_split",
            serde_json::json!({"command": "echo hello"}),
            None,
            None,
        );
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::ToolNotAllowedForAudience { .. } => {}
            other => panic!("expected ToolNotAllowedForAudience, got {:?}", other),
        }
    }

    #[test]
    fn execution_context_overrides_profile_for_budget_call() {
        let registry = ToolRegistry::default();
        let ctx = ExecutionContext {
            profile: Some(Profile::HumanMath),
            ..ExecutionContext::test_default()
        };
        // text_equal is not in human_math, should be rejected
        let result = registry.call_json_with_execution_context(
            "text_equal",
            serde_json::json!({"a": "x", "b": "x"}),
            &ctx,
        );
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::ToolUnavailable { tool, .. } => assert_eq!(tool, "text_equal"),
            other => panic!("expected ToolUnavailable, got {:?}", other),
        }
    }

    #[test]
    fn execution_context_audience_enforced_for_budget_call() {
        let registry = ToolRegistry::default();
        let ctx = ExecutionContext {
            profile: Some(Profile::Full),
            audience: Some(ToolAudience::Model),
            ..ExecutionContext::test_default()
        };
        let result = registry.call_json_with_execution_context(
            "shell_split",
            serde_json::json!({"command": "echo hello"}),
            &ctx,
        );
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::ToolNotAllowedForAudience { .. } => {}
            other => panic!("expected ToolNotAllowedForAudience, got {:?}", other),
        }
    }

    #[test]
    #[allow(deprecated)]
    fn execution_context_mut_routes_through_pool() {
        let registry = ToolRegistry::default();
        let mut ctx = ExecutionContext::test_default();
        let result = registry.call_json_with_execution_context_mut(
            "text_equal",
            serde_json::json!({"a": "foo", "b": "foo"}),
            &mut ctx,
        );
        assert!(result.is_ok());
        assert!(result.unwrap().ok);
    }

    #[test]
    #[allow(deprecated)]
    fn execution_context_mut_rejects_unavailable_tool() {
        let registry = ToolRegistry::with_profile(Profile::HumanMath);
        let mut ctx = ExecutionContext {
            profile: Some(Profile::HumanMath),
            ..ExecutionContext::test_default()
        };
        let result = registry.call_json_with_execution_context_mut(
            "text_equal",
            serde_json::json!({"a": "x", "b": "x"}),
            &mut ctx,
        );
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolCallError::ToolUnavailable { tool, .. } => assert_eq!(tool, "text_equal"),
            other => panic!("expected ToolUnavailable, got {:?}", other),
        }
    }
}