Skip to main content

lean_ctx/server/
dynamic_tools.rs

1use std::collections::HashSet;
2use std::sync::{Mutex, OnceLock};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5pub enum ToolCategory {
6    Core,
7    Internal,
8    Arch,
9    Debug,
10    Memory,
11    Metrics,
12    Session,
13}
14
15impl ToolCategory {
16    pub fn parse(s: &str) -> Option<Self> {
17        match s {
18            "core" => Some(Self::Core),
19            "arch" | "architecture" => Some(Self::Arch),
20            "debug" | "profiling" => Some(Self::Debug),
21            "memory" | "semantic" => Some(Self::Memory),
22            "metrics" | "stats" => Some(Self::Metrics),
23            "session" => Some(Self::Session),
24            _ => None,
25        }
26    }
27
28    pub fn as_str(&self) -> &'static str {
29        match self {
30            Self::Core => "core",
31            Self::Internal => "internal",
32            Self::Arch => "arch",
33            Self::Debug => "debug",
34            Self::Memory => "memory",
35            Self::Metrics => "metrics",
36            Self::Session => "session",
37        }
38    }
39}
40
41#[allow(clippy::match_same_arms)]
42pub fn categorize_tool(name: &str) -> ToolCategory {
43    match name {
44        // Internal: meta/self-referential + automated mechanisms (never exposed)
45        "ctx_metrics"
46        | "ctx_cost"
47        | "ctx_gain"
48        | "ctx_radar"
49        | "ctx_heatmap"
50        | "ctx_feedback"
51        | "ctx_intent"
52        | "ctx_response"
53        | "ctx_discover"
54        | "ctx_discover_tools"
55        | "ctx_load_tools"
56        | "ctx_dedup"
57        | "ctx_preload"
58        | "ctx_prefetch"
59        | "ctx_compress_memory" => ToolCategory::Internal,
60
61        // Core: always visible. Must cover every CORE_TOOL_NAMES entry —
62        // otherwise the category gate silently drops a lazy-core tool for
63        // list_changed-capable clients (ctx_expand was lost this way, #575).
64        // ctx_callgraph joined the lazy core in #578 (INTENT routes
65        // callers/impact to it), so it must be Core here too.
66        // ctx_patch joined in #1008 (anchored editing is a core workflow).
67        "ctx_read" | "ctx_search" | "ctx_shell" | "shell" | "ctx_tree" | "ctx_edit"
68        | "ctx_patch" | "ctx_session" | "ctx_checkpoint" | "ctx_knowledge" | "ctx_overview"
69        | "ctx_graph" | "ctx_callgraph" | "ctx_call" | "ctx_compress" | "ctx_cache"
70        | "ctx_retrieve" | "ctx_expand" => ToolCategory::Core,
71
72        // Merged tools (redirects in registry, treated as Core for backward compat)
73        "ctx_multi_read" | "ctx_smart_read" | "ctx_delta" | "ctx_outline" | "ctx_context" => {
74            ToolCategory::Core
75        }
76
77        // Arch: on-demand architecture analysis
78        "ctx_architecture" | "ctx_impact" | "ctx_refactor" | "ctx_symbol" | "ctx_routes"
79        | "ctx_smells" | "ctx_quality" | "ctx_index" => ToolCategory::Arch,
80
81        // Debug/Verify: on-demand quality analysis
82        "ctx_benchmark" | "ctx_verify" | "ctx_analyze" | "ctx_profile" | "ctx_proof"
83        | "ctx_review" | "ctx_compare" => ToolCategory::Debug,
84
85        // Provider + URL/Git readers + the MCP gateway are Core: gateways to
86        // external context (GitHub issues, Jira, Postgres, web pages, YouTube,
87        // remote git repos, downstream MCP servers) — always available.
88        // ctx_semantic_search is a first-class retrieval tool (advertised in the
89        // lean core, #422) — keep it Core so the default category gate never hides
90        // it, the very reason agents stopped reaching for it.
91        "ctx_provider" | "ctx_url_read" | "ctx_git_read" | "ctx_tools" | "ctx_semantic_search" => {
92            ToolCategory::Core
93        }
94
95        // Memory: on-demand artifact retrieval
96        "ctx_artifacts" => ToolCategory::Memory,
97
98        // Batch: on-demand batch/PR/sandbox tools
99        "ctx_fill" | "ctx_execute" | "ctx_pack" | "ctx_plan" | "ctx_control" | "ctx_compile" => {
100            ToolCategory::Metrics
101        }
102
103        // Multi-agent: on-demand collaboration
104        "ctx_agent" | "ctx_share" | "ctx_task" | "ctx_handoff" | "ctx_workflow" => {
105            ToolCategory::Session
106        }
107
108        _ => ToolCategory::Core,
109    }
110}
111
112/// A deprecated tool that has been folded into a primary tool (#509 Phase 1).
113///
114/// The alias stays **registered and callable** (directly and via `ctx_call`) for
115/// one release so nothing breaks, but it is hidden from `tools/list` and warns on
116/// use, steering agents to the consolidated primary. Removal happens in Phase 2.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct DeprecatedAlias {
119    /// The primary tool that supersedes this alias (e.g. `"ctx_read"`).
120    pub replacement: &'static str,
121    /// One-line migration hint (e.g. how the primary covers this use case).
122    pub hint: &'static str,
123}
124
125/// Single source of truth for read-cluster deprecations (#509). Returns the
126/// replacement + migration hint when `name` is a deprecated alias, else `None`.
127///
128/// Used by [`crate::server::tool_visibility::is_tool_visible`] to hide the alias
129/// from `tools/list`, and by the dispatch layer to prepend a one-line
130/// deprecation notice to the alias's output. Keeping both behaviours keyed off
131/// this one function guarantees "hidden" and "warned" can never drift apart.
132#[must_use]
133pub fn deprecated_alias(name: &str) -> Option<DeprecatedAlias> {
134    match name {
135        "ctx_smart_read" => Some(DeprecatedAlias {
136            replacement: "ctx_read",
137            hint: "ctx_read auto-selects the mode (omit `mode`, or pass mode=\"auto\")",
138        }),
139        "ctx_multi_read" => Some(DeprecatedAlias {
140            replacement: "ctx_read",
141            hint: "ctx_read now batch-reads via paths=[\"a.rs\",\"b.rs\"]",
142        }),
143        // #509 search consolidation: one ctx_search entry, `action` picks the
144        // engine. Aliases stay callable for one release so nothing breaks.
145        "ctx_semantic_search" => Some(DeprecatedAlias {
146            replacement: "ctx_search",
147            hint: "ctx_search with action=\"semantic\" (query=…); reindex/find_related are actions too",
148        }),
149        "ctx_symbol" => Some(DeprecatedAlias {
150            replacement: "ctx_search",
151            hint: "ctx_search with action=\"symbol\" (name=…, optional file/kind)",
152        }),
153        _ => None,
154    }
155}
156
157/// Whether `name` is a deprecated alias hidden from `tools/list` (#509).
158#[must_use]
159pub fn is_deprecated_alias(name: &str) -> bool {
160    deprecated_alias(name).is_some()
161}
162
163/// Local collaboration substrate that remains callable for installed users but
164/// is excluded from every public MCP tool surface.
165///
166/// LeanCTX is a Context SDK, not an agent coordination product. These tools
167/// support local development compatibility only; they do not imply a supported
168/// public agent bus, task scheduler, workflow engine, or A2A product.
169pub const LOCAL_COLLABORATION_COMPATIBILITY_TOOLS: &[&str] = &[
170    "ctx_agent",
171    "ctx_share",
172    "ctx_task",
173    "ctx_handoff",
174    "ctx_workflow",
175];
176
177/// Whether a registered tool is retained only for local compatibility and must
178/// never be advertised from a public tool-definition path.
179#[must_use]
180pub fn is_local_collaboration_compatibility_tool(name: &str) -> bool {
181    LOCAL_COLLABORATION_COMPATIBILITY_TOOLS.contains(&name)
182}
183
184/// Whether a registered tool belongs on a public MCP tool surface.
185///
186/// Compatibility aliases and local collaboration substrate remain directly
187/// callable, including through `ctx_call`; this gate only controls discovery.
188#[must_use]
189pub fn is_publicly_advertised_tool(name: &str) -> bool {
190    !is_deprecated_alias(name) && !is_local_collaboration_compatibility_tool(name)
191}
192
193/// The one-line deprecation notice prepended to a deprecated alias's output.
194/// Stable per tool (no timestamps/counters) so provider-side prompt caching
195/// stays byte-stable (#498).
196#[must_use]
197pub fn deprecation_notice(name: &str) -> Option<String> {
198    deprecated_alias(name).map(|d| {
199        format!(
200            "[DEPRECATED] {name} is superseded by {} — {}. This alias is hidden from \
201             tools/list and will be removed in a future release.",
202            d.replacement, d.hint
203        )
204    })
205}
206
207pub fn is_readonly_tool(name: &str) -> bool {
208    matches!(
209        name,
210        "ctx_read"
211            | "ctx_search"
212            | "ctx_tree"
213            | "ctx_overview"
214            | "ctx_plan"
215            | "ctx_metrics"
216            | "ctx_compress"
217            | "ctx_session"
218            | "ctx_knowledge"
219            | "ctx_graph"
220            | "ctx_retrieve"
221            | "ctx_provider"
222            | "ctx_multi_read"
223            | "ctx_smart_read"
224            | "ctx_delta"
225            | "ctx_outline"
226            | "ctx_context"
227            | "ctx_call"
228            | "ctx_url_read"
229            | "ctx_git_read"
230            | "ctx_architecture"
231            | "ctx_impact"
232            | "ctx_callgraph"
233            | "ctx_symbol"
234            | "ctx_routes"
235            | "ctx_smells"
236            | "ctx_quality"
237            | "ctx_index"
238            | "ctx_semantic_search"
239            | "ctx_explore"
240            | "ctx_artifacts"
241            | "ctx_cost"
242            | "ctx_gain"
243            | "ctx_heatmap"
244            | "ctx_compare"
245    )
246}
247
248#[derive(Debug)]
249pub struct DynamicToolState {
250    active_categories: HashSet<ToolCategory>,
251    supports_list_changed: bool,
252}
253
254impl Default for DynamicToolState {
255    fn default() -> Self {
256        Self::new()
257    }
258}
259
260impl DynamicToolState {
261    pub fn new() -> Self {
262        let mut active = HashSet::new();
263        active.insert(ToolCategory::Core);
264        Self {
265            active_categories: active,
266            supports_list_changed: false,
267        }
268    }
269
270    /// Creates state with categories from config (env var > config.toml > default).
271    pub fn from_config(categories: &[String]) -> Self {
272        let mut active = HashSet::new();
273        active.insert(ToolCategory::Core);
274        for cat_str in categories {
275            if let Some(cat) = ToolCategory::parse(cat_str) {
276                active.insert(cat);
277            }
278        }
279        Self {
280            active_categories: active,
281            supports_list_changed: false,
282        }
283    }
284
285    pub fn all_enabled() -> Self {
286        let mut active = HashSet::new();
287        active.insert(ToolCategory::Core);
288        active.insert(ToolCategory::Arch);
289        active.insert(ToolCategory::Debug);
290        active.insert(ToolCategory::Memory);
291        active.insert(ToolCategory::Metrics);
292        active.insert(ToolCategory::Session);
293        Self {
294            active_categories: active,
295            supports_list_changed: false,
296        }
297    }
298
299    pub fn set_supports_list_changed(&mut self, val: bool) {
300        self.supports_list_changed = val;
301    }
302
303    pub fn supports_list_changed(&self) -> bool {
304        self.supports_list_changed
305    }
306
307    pub fn load_category(&mut self, cat: ToolCategory) -> bool {
308        self.active_categories.insert(cat)
309    }
310
311    pub fn unload_category(&mut self, cat: ToolCategory) -> bool {
312        if cat == ToolCategory::Core || cat == ToolCategory::Internal {
313            return false;
314        }
315        self.active_categories.remove(&cat)
316    }
317
318    pub fn is_tool_active(&self, name: &str) -> bool {
319        let cat = categorize_tool(name);
320        if cat == ToolCategory::Internal {
321            return false;
322        }
323        if !self.supports_list_changed {
324            // Clients without `list_changed` cannot progressively reveal a
325            // category. Keep experimental local collaboration out of their
326            // default surface too; an explicit config category still enables it.
327            return cat != ToolCategory::Session || self.active_categories.contains(&cat);
328        }
329        self.active_categories.contains(&cat)
330    }
331
332    pub fn active_categories(&self) -> Vec<&'static str> {
333        let mut cats: Vec<_> = self
334            .active_categories
335            .iter()
336            .map(ToolCategory::as_str)
337            .collect();
338        cats.sort_unstable();
339        cats
340    }
341
342    pub fn all_categories() -> Vec<&'static str> {
343        vec!["core", "arch", "debug", "memory", "metrics", "session"]
344    }
345}
346
347static GLOBAL: OnceLock<Mutex<DynamicToolState>> = OnceLock::new();
348
349pub fn global() -> &'static Mutex<DynamicToolState> {
350    GLOBAL.get_or_init(|| Mutex::new(DynamicToolState::new()))
351}
352
353pub fn init_all_enabled() {
354    let _ = GLOBAL.set(Mutex::new(DynamicToolState::all_enabled()));
355}
356
357/// Initializes the global state from user config (env var > config.toml > default).
358/// Call once during server startup after config is loaded.
359/// If the global was already initialized (e.g. by a concurrent `global()` call),
360/// applies the categories to the existing state instead.
361pub fn init_from_config(categories: &[String]) {
362    if GLOBAL
363        .set(Mutex::new(DynamicToolState::from_config(categories)))
364        .is_err()
365        && let Ok(mut state) = global().lock()
366    {
367        let desired = DynamicToolState::from_config(categories);
368        *state = desired;
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn core_tools_always_active() {
378        let state = DynamicToolState::new();
379        assert!(state.is_tool_active("ctx_read"));
380        assert!(state.is_tool_active("ctx_search"));
381        assert!(!state.is_tool_active("ctx_agent"));
382        assert!(!state.is_tool_active("ctx_task"));
383        assert!(!state.is_tool_active("ctx_workflow"));
384    }
385
386    #[test]
387    fn deprecated_alias_maps_read_cluster_to_ctx_read() {
388        // #509: only the folded read-cluster tools are deprecated; everything
389        // else (incl. the primary) returns None.
390        assert_eq!(
391            deprecated_alias("ctx_smart_read").unwrap().replacement,
392            "ctx_read"
393        );
394        assert_eq!(
395            deprecated_alias("ctx_multi_read").unwrap().replacement,
396            "ctx_read"
397        );
398        assert!(deprecated_alias("ctx_read").is_none());
399        assert!(deprecated_alias("ctx_search").is_none());
400        assert!(is_deprecated_alias("ctx_multi_read"));
401        assert!(!is_deprecated_alias("ctx_read"));
402
403        // #509 search consolidation: the folded search tools point at ctx_search.
404        assert_eq!(
405            deprecated_alias("ctx_semantic_search").unwrap().replacement,
406            "ctx_search"
407        );
408        assert_eq!(
409            deprecated_alias("ctx_symbol").unwrap().replacement,
410            "ctx_search"
411        );
412        assert!(is_deprecated_alias("ctx_symbol"));
413    }
414
415    #[test]
416    fn local_collaboration_substrate_is_compatibility_only() {
417        for name in LOCAL_COLLABORATION_COMPATIBILITY_TOOLS {
418            assert!(is_local_collaboration_compatibility_tool(name));
419            assert!(!is_publicly_advertised_tool(name));
420        }
421        assert!(!is_local_collaboration_compatibility_tool("ctx_session"));
422        assert!(is_publicly_advertised_tool("ctx_session"));
423    }
424
425    #[test]
426    fn deprecation_notice_is_stable_and_names_replacement() {
427        // Stable text (no timestamps/counters) for cache-byte-stability (#498),
428        // and it must point at the primary so agents know where to go.
429        let notice = deprecation_notice("ctx_multi_read").unwrap();
430        assert!(notice.starts_with("[DEPRECATED] ctx_multi_read is superseded by ctx_read"));
431        assert!(notice.contains("paths="));
432        assert_eq!(notice, deprecation_notice("ctx_multi_read").unwrap());
433        assert!(deprecation_notice("ctx_read").is_none());
434    }
435
436    #[test]
437    fn dynamic_tools_filtered_when_list_changed() {
438        let mut state = DynamicToolState::new();
439        state.set_supports_list_changed(true);
440        assert!(!state.is_tool_active("ctx_benchmark"));
441        assert!(!state.is_tool_active("ctx_architecture"));
442        assert!(state.is_tool_active("ctx_read"));
443    }
444
445    #[test]
446    fn load_category_enables_tools() {
447        let mut state = DynamicToolState::new();
448        state.set_supports_list_changed(true);
449        assert!(!state.is_tool_active("ctx_architecture"));
450        state.load_category(ToolCategory::Arch);
451        assert!(state.is_tool_active("ctx_architecture"));
452    }
453
454    #[test]
455    fn cannot_unload_core() {
456        let mut state = DynamicToolState::new();
457        assert!(!state.unload_category(ToolCategory::Core));
458    }
459
460    #[test]
461    fn all_tools_visible_without_list_changed() {
462        let state = DynamicToolState::new();
463        assert!(state.is_tool_active("ctx_graph"));
464        assert!(!state.is_tool_active("ctx_agent"));
465        assert!(!state.is_tool_active("ctx_metrics")); // Internal tools never active
466    }
467
468    #[test]
469    fn internal_tools_never_active() {
470        let state = DynamicToolState::all_enabled();
471        assert!(!state.is_tool_active("ctx_metrics"));
472        assert!(!state.is_tool_active("ctx_cost"));
473        assert!(!state.is_tool_active("ctx_discover_tools"));
474        assert!(!state.is_tool_active("ctx_dedup"));
475    }
476
477    // --- from_config: basic scenarios ---
478
479    #[test]
480    fn from_config_core_arch_memory() {
481        let cats = vec!["core".to_string(), "arch".to_string(), "memory".to_string()];
482        let mut state = DynamicToolState::from_config(&cats);
483        state.set_supports_list_changed(true);
484        assert!(state.is_tool_active("ctx_read"));
485        assert!(state.is_tool_active("ctx_architecture"));
486        assert!(state.is_tool_active("ctx_artifacts"));
487        assert!(!state.is_tool_active("ctx_benchmark"));
488        assert!(!state.is_tool_active("ctx_fill"));
489    }
490
491    #[test]
492    fn from_config_empty_still_has_core() {
493        let mut state = DynamicToolState::from_config(&[]);
494        state.set_supports_list_changed(true);
495        assert!(state.is_tool_active("ctx_read"));
496        assert!(!state.is_tool_active("ctx_architecture"));
497        assert!(!state.is_tool_active("ctx_benchmark"));
498        assert!(!state.is_tool_active("ctx_artifacts"));
499    }
500
501    // --- from_config: all categories ---
502
503    #[test]
504    fn from_config_all_categories_enables_everything_except_internal() {
505        let cats = vec![
506            "core".to_string(),
507            "arch".to_string(),
508            "debug".to_string(),
509            "memory".to_string(),
510            "metrics".to_string(),
511            "session".to_string(),
512        ];
513        let mut state = DynamicToolState::from_config(&cats);
514        state.set_supports_list_changed(true);
515        assert!(state.is_tool_active("ctx_read"));
516        assert!(state.is_tool_active("ctx_architecture"));
517        assert!(state.is_tool_active("ctx_benchmark"));
518        assert!(state.is_tool_active("ctx_semantic_search"));
519        assert!(state.is_tool_active("ctx_fill"));
520        assert!(state.is_tool_active("ctx_workflow"));
521        assert!(!state.is_tool_active("ctx_metrics"));
522    }
523
524    // --- from_config: single category ---
525
526    #[test]
527    fn from_config_only_debug() {
528        let cats = vec!["debug".to_string()];
529        let mut state = DynamicToolState::from_config(&cats);
530        state.set_supports_list_changed(true);
531        assert!(state.is_tool_active("ctx_read"));
532        assert!(state.is_tool_active("ctx_benchmark"));
533        assert!(!state.is_tool_active("ctx_architecture"));
534        assert!(!state.is_tool_active("ctx_workflow"));
535    }
536
537    // --- from_config: invalid categories are silently ignored ---
538
539    #[test]
540    fn from_config_ignores_unknown_categories() {
541        let cats = vec![
542            "core".to_string(),
543            "nonexistent".to_string(),
544            "foobar".to_string(),
545        ];
546        let mut state = DynamicToolState::from_config(&cats);
547        state.set_supports_list_changed(true);
548        assert!(state.is_tool_active("ctx_read"));
549        assert!(!state.is_tool_active("ctx_architecture"));
550    }
551
552    #[test]
553    fn from_config_only_invalid_still_has_core() {
554        let cats = vec!["invalid".to_string(), "bogus".to_string()];
555        let mut state = DynamicToolState::from_config(&cats);
556        state.set_supports_list_changed(true);
557        assert!(state.is_tool_active("ctx_read"));
558        assert!(!state.is_tool_active("ctx_benchmark"));
559    }
560
561    // --- from_config: duplicate categories are idempotent ---
562
563    #[test]
564    fn from_config_duplicates_are_harmless() {
565        let cats = vec!["arch".to_string(), "arch".to_string(), "arch".to_string()];
566        let mut state = DynamicToolState::from_config(&cats);
567        state.set_supports_list_changed(true);
568        assert!(state.is_tool_active("ctx_architecture"));
569        let active = state.active_categories();
570        let arch_count = active.iter().filter(|&&c| c == "arch").count();
571        assert_eq!(arch_count, 1);
572    }
573
574    // --- from_config: internal category is never user-activatable ---
575
576    #[test]
577    fn from_config_internal_category_not_parseable() {
578        assert!(ToolCategory::parse("internal").is_none());
579    }
580
581    // --- from_config: category aliases work ---
582
583    #[test]
584    fn from_config_alias_architecture_maps_to_arch() {
585        let cats = vec!["architecture".to_string()];
586        let mut state = DynamicToolState::from_config(&cats);
587        state.set_supports_list_changed(true);
588        assert!(state.is_tool_active("ctx_architecture"));
589    }
590
591    #[test]
592    fn from_config_alias_profiling_maps_to_debug() {
593        let cats = vec!["profiling".to_string()];
594        let mut state = DynamicToolState::from_config(&cats);
595        state.set_supports_list_changed(true);
596        assert!(state.is_tool_active("ctx_benchmark"));
597    }
598
599    #[test]
600    fn from_config_alias_semantic_maps_to_memory() {
601        let cats = vec!["semantic".to_string()];
602        let mut state = DynamicToolState::from_config(&cats);
603        state.set_supports_list_changed(true);
604        assert!(state.is_tool_active("ctx_artifacts"));
605    }
606
607    // --- from_config: subsequent load/unload still works ---
608
609    #[test]
610    fn from_config_then_load_additional_category() {
611        let cats = vec!["core".to_string()];
612        let mut state = DynamicToolState::from_config(&cats);
613        state.set_supports_list_changed(true);
614        assert!(!state.is_tool_active("ctx_architecture"));
615        state.load_category(ToolCategory::Arch);
616        assert!(state.is_tool_active("ctx_architecture"));
617    }
618
619    #[test]
620    fn from_config_then_unload_non_core_category() {
621        let cats = vec!["core".to_string(), "arch".to_string()];
622        let mut state = DynamicToolState::from_config(&cats);
623        state.set_supports_list_changed(true);
624        assert!(state.is_tool_active("ctx_architecture"));
625        state.unload_category(ToolCategory::Arch);
626        assert!(!state.is_tool_active("ctx_architecture"));
627    }
628
629    #[test]
630    fn from_config_cannot_unload_core() {
631        let cats = vec!["core".to_string(), "arch".to_string()];
632        let mut state = DynamicToolState::from_config(&cats);
633        assert!(!state.unload_category(ToolCategory::Core));
634    }
635
636    // --- from_config: without list_changed, all tools visible ---
637
638    #[test]
639    fn from_config_without_list_changed_shows_all() {
640        let cats = vec!["core".to_string()];
641        let state = DynamicToolState::from_config(&cats);
642        assert!(state.is_tool_active("ctx_architecture"));
643        assert!(state.is_tool_active("ctx_benchmark"));
644        assert!(!state.is_tool_active("ctx_metrics"));
645    }
646
647    #[test]
648    fn lazy_core_tools_survive_default_category_gate() {
649        // Regression for #575: every advertised lazy-core tool must stay
650        // active under the default category gate (Core + Session) when the
651        // client supports list_changed — otherwise Cursor silently loses
652        // tools like ctx_expand from the 13-tool core set.
653        let mut state = DynamicToolState::new();
654        state.set_supports_list_changed(true);
655        for name in crate::tool_defs::core_tool_names() {
656            assert!(
657                state.is_tool_active(name),
658                "{name} is in CORE_TOOL_NAMES but dropped by the default category gate"
659            );
660        }
661    }
662
663    #[test]
664    fn categorize_known_tools() {
665        assert_eq!(categorize_tool("ctx_read"), ToolCategory::Core);
666        assert_eq!(categorize_tool("ctx_graph"), ToolCategory::Core);
667        // #1008: anchored editing is a core workflow — an explicit Core entry so
668        // the category gate can never hide the lazy-core editor.
669        assert_eq!(categorize_tool("ctx_patch"), ToolCategory::Core);
670        assert_eq!(categorize_tool("ctx_benchmark"), ToolCategory::Debug);
671        assert_eq!(categorize_tool("ctx_semantic_search"), ToolCategory::Core);
672        assert_eq!(categorize_tool("ctx_artifacts"), ToolCategory::Memory);
673        assert_eq!(categorize_tool("ctx_metrics"), ToolCategory::Internal);
674        assert_eq!(categorize_tool("ctx_workflow"), ToolCategory::Session);
675    }
676
677    #[test]
678    fn readonly_classification() {
679        assert!(is_readonly_tool("ctx_read"));
680        assert!(is_readonly_tool("ctx_search"));
681        assert!(is_readonly_tool("ctx_tree"));
682        assert!(is_readonly_tool("ctx_overview"));
683        assert!(is_readonly_tool("ctx_provider"));
684
685        assert!(!is_readonly_tool("ctx_edit"));
686        assert!(!is_readonly_tool("ctx_shell"));
687        assert!(!is_readonly_tool("ctx_compile"));
688        assert!(!is_readonly_tool("ctx_execute"));
689        assert!(!is_readonly_tool("ctx_cache"));
690    }
691
692    #[test]
693    fn plan_mode_tools_are_all_readonly() {
694        for tool in crate::core::editor_registry::plan_mode::plan_mode_tools() {
695            assert!(
696                is_readonly_tool(tool),
697                "{tool} is listed as plan mode tool but not marked readonly"
698            );
699        }
700    }
701}