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_discover"
52        | "ctx_discover_tools"
53        | "ctx_load_tools"
54        | "ctx_dedup"
55        | "ctx_preload"
56        | "ctx_prefetch"
57        | "ctx_compress_memory"
58        | "ctx_shape" => ToolCategory::Internal,
59
60        // Core: always visible. Must cover every CORE_TOOL_NAMES entry —
61        // otherwise the category gate silently drops a lazy-core tool for
62        // list_changed-capable clients (ctx_expand was lost this way, #575).
63        // ctx_callgraph joined the lazy core in #578 (INTENT routes
64        // callers/impact to it), so it must be Core here too.
65        // ctx_patch joined in #1008 (anchored editing is a core workflow).
66        "ctx_read" | "ctx_search" | "ctx_shell" | "shell" | "ctx_tree" | "ctx_edit"
67        | "ctx_patch" | "ctx_session" | "ctx_checkpoint" | "ctx_knowledge" | "ctx_graph"
68        | "ctx_callgraph" | "ctx_call" | "ctx_compress" | "ctx_expand" | "ctx_delta"
69        | "ctx_outline" | "ctx_context" => ToolCategory::Core,
70
71        // Arch: on-demand index maintenance
72        "ctx_index" => ToolCategory::Arch,
73
74        // Debug/Verify: on-demand verification
75        "ctx_verify" | "ctx_profile" | "ctx_proof" => ToolCategory::Debug,
76
77        // Provider + URL/Git readers + the MCP gateway are Core: gateways to
78        // external context (GitHub issues, Jira, Postgres, web pages, YouTube,
79        // remote git repos, downstream MCP servers) — always available.
80        "ctx_provider" | "ctx_url_read" | "ctx_git_read" | "ctx_tools" => ToolCategory::Core,
81
82        // Memory: on-demand artifact retrieval
83        "ctx_artifacts" => ToolCategory::Memory,
84
85        // Batch: on-demand batch/PR/sandbox tools
86        "ctx_execute" | "ctx_pack" | "ctx_control" => ToolCategory::Metrics,
87
88        // Multi-agent: on-demand collaboration
89        "ctx_agent" | "ctx_share" | "ctx_handoff" | "ctx_work_graph" | "ctx_tasks"
90        | "ctx_compute" => ToolCategory::Session,
91
92        _ => ToolCategory::Core,
93    }
94}
95
96/// A tool that was removed: folded into a primary tool (#509) or retired
97/// without a successor (focus release, 2026-10). Only the name survives, so a
98/// call from an older agent prompt or config gets the way forward instead of
99/// a bare "Unknown tool" (`docs/migration/focus-2026-10.md`).
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct RemovedTool {
102    /// The primary tool that covers this use case (e.g. `"ctx_read"`), or
103    /// `None` for a tool retired from the Context Gateway without a successor.
104    pub replacement: Option<&'static str>,
105    /// One-line migration hint (e.g. how the primary covers this use case).
106    pub hint: &'static str,
107}
108
109const fn superseded(replacement: &'static str, hint: &'static str) -> Option<RemovedTool> {
110    Some(RemovedTool {
111        replacement: Some(replacement),
112        hint,
113    })
114}
115
116const fn retired(hint: &'static str) -> Option<RemovedTool> {
117    Some(RemovedTool {
118        replacement: None,
119        hint,
120    })
121}
122
123/// The successor and migration hint for a removed tool name, else `None`.
124#[must_use]
125pub fn removed_tool(name: &str) -> Option<RemovedTool> {
126    match name {
127        "ctx_smart_read" => superseded(
128            "ctx_read",
129            "ctx_read auto-selects the mode (omit `mode`, or pass mode=\"auto\")",
130        ),
131        "ctx_multi_read" => superseded(
132            "ctx_read",
133            "ctx_read now batch-reads via paths=[\"a.rs\",\"b.rs\"]",
134        ),
135        // #509 search consolidation: one ctx_search entry, `action` picks the engine.
136        "ctx_semantic_search" => superseded(
137            "ctx_search",
138            "ctx_search with action=\"semantic\" (query=…); reindex/find_related are actions too",
139        ),
140        "ctx_symbol" => superseded(
141            "ctx_search",
142            "ctx_search with action=\"symbol\" (name=…, optional file/kind)",
143        ),
144        // Focus release 2026-10-15, Select: one task-ranked entry point.
145        "ctx_overview" | "ctx_summary" | "ctx_explore" => superseded(
146            "ctx_compose",
147            "ctx_compose(task=…) returns the ranked files, symbols and structure for a task",
148        ),
149        "ctx_plan" | "ctx_compile" | "ctx_fill" => superseded(
150            "ctx_compose",
151            "ctx_compose selects under the turn budget; read chosen files with ctx_read",
152        ),
153        // One code-graph tool beside ctx_callgraph.
154        "ctx_impact" => superseded(
155            "ctx_graph",
156            "ctx_graph action=\"impact\" (path=…), action=\"path\" for chains, action=\"diff\" for changes",
157        ),
158        "ctx_architecture" | "ctx_repomap" => superseded(
159            "ctx_graph",
160            "ctx_graph action=\"diagram\"|\"explain\"|\"related\"; ctx_tree for the directory map",
161        ),
162        "ctx_routes" => superseded(
163            "ctx_search",
164            "ctx_search for route definitions (pattern=…), ctx_graph action=\"related\" for handlers",
165        ),
166        "ctx_retrieve" => superseded(
167            "ctx_expand",
168            "ctx_expand id=… returns withheld or archived content",
169        ),
170        // Maintenance, not an agent decision: the CLI keeps it. (`ctx_index`
171        // stays public: it carries `ctx_search`'s former reindex action, #1624.)
172        "ctx_cache" => superseded(
173            "ctx_read",
174            "ctx_read fresh=true re-reads; maintenance runs via `lean-ctx cache prune|reset`",
175        ),
176        // Focus release 2026-10-15, retired: not part of Select · Control · Prove.
177        "ctx_smells" | "ctx_quality" | "ctx_optimize" | "ctx_review" => {
178            retired("code review and linting belong to the host's own tooling")
179        }
180        "ctx_quality_lab" | "ctx_benchmark" | "ctx_perf" | "ctx_cognitive" | "ctx_ledger"
181        | "ctx_live_zone" => retired(
182            "measurement and diagnostics live in `lean-ctx gain`, `lean-ctx doctor` and the dashboard",
183        ),
184        "ctx_refactor" => retired(
185            "write refactorings are host execution; ctx_callgraph keeps the LSP read side (references)",
186        ),
187        "ctx_analyze" | "ctx_compare" => retired(
188            "ctx_read mode=\"auto\" picks the mode; `lean-ctx compress diff <file>` previews compression",
189        ),
190        "ctx_crush" => {
191            retired("ctx_read and ctx_shell apply the JSON/CSV/YAML crushers automatically")
192        }
193        "ctx_response" => {
194            retired("LeanCTX shapes the context the model reads, not the model's own responses")
195        }
196        "ctx_skillify" | "ctx_rules" => retired(
197            "agent rule files are host configuration; use `lean-ctx rules status|diff` or `lean-ctx doctor`",
198        ),
199        "ctx_workflow" => retired(
200            "workflow execution belongs to the host; ctx_work_graph keeps the shared coordination state",
201        ),
202        // Retired 2026-10-17: no calls from any installation in 30 days.
203        "ctx_task" => retired(
204            "task assignment is host execution; ctx_work_graph keeps the shared coordination state",
205        ),
206        "ctx_intent" => retired(
207            "LeanCTX infers intent from the tool calls; ctx_compose(task=…) selects context for a task",
208        ),
209        _ => None,
210    }
211}
212
213/// Local collaboration substrate that remains callable for installed users but
214/// is excluded from every public MCP tool surface.
215///
216/// LeanCTX is a Context SDK, not an agent coordination product. These tools
217/// support local development compatibility only; they do not imply a supported
218/// public agent bus, task scheduler, workflow engine, or A2A product.
219pub const LOCAL_COLLABORATION_COMPATIBILITY_TOOLS: &[&str] =
220    &["ctx_agent", "ctx_share", "ctx_handoff"];
221
222/// Whether a registered tool is retained only for local compatibility and must
223/// never be advertised from a public tool-definition path.
224#[must_use]
225pub fn is_local_collaboration_compatibility_tool(name: &str) -> bool {
226    LOCAL_COLLABORATION_COMPATIBILITY_TOOLS.contains(&name)
227}
228
229/// Host-integration hooks: called by a host extension (the Claude Code mod's
230/// `$.mcp.call`, through the listed `ctx_call` since hosts may refuse unlisted
231/// tools, #2089), never by an agent. Advertising them would only spend prompt
232/// tokens on a tool the model must not use.
233pub const INTERNAL_HOST_TOOLS: &[&str] = &["ctx_shape"];
234
235/// Whether a call — direct, or through `ctx_call`/`ctx` — targets an internal
236/// host hook. A host replaces a native tool's output with the hook's success
237/// body, so every gate refusal on such a call must read as an error: then the
238/// host keeps the original output instead of a block message (#2089).
239#[must_use]
240pub fn targets_internal_host_tool(
241    name: &str,
242    args: Option<&serde_json::Map<String, serde_json::Value>>,
243) -> bool {
244    crate::tools::registered::ctx_call::resolve(name, args)
245        .is_ok_and(|(inner, _)| INTERNAL_HOST_TOOLS.contains(&inner.as_str()))
246}
247
248/// Hive MCP tools. They ship with the connector but follow its release switch
249/// (`core::hive::available_locally`, owner 28.10.): while it is off they are
250/// in no tool list and every call answers [`crate::core::hive::TOOL_NOT_AVAILABLE`].
251pub const HIVE_TOOLS: &[&str] = &["ctx_tasks", "ctx_compute"];
252
253/// Whether `name` is a Hive tool withheld by the release switch.
254#[must_use]
255pub fn is_withheld_hive_tool(name: &str) -> bool {
256    HIVE_TOOLS.contains(&name) && !crate::core::hive::available_locally()
257}
258
259/// The fixed answer for a call — direct, or through `ctx_call`/`ctx` — to a
260/// withheld Hive tool, else `None`. Stable text (#498).
261#[must_use]
262pub fn withheld_hive_tool_refusal(
263    name: &str,
264    args: Option<&serde_json::Map<String, serde_json::Value>>,
265) -> Option<&'static str> {
266    crate::tools::registered::ctx_call::resolve(name, args)
267        .is_ok_and(|(inner, _)| is_withheld_hive_tool(&inner))
268        .then_some(crate::core::hive::TOOL_NOT_AVAILABLE)
269}
270
271/// Whether a registered tool belongs on a public MCP tool surface.
272///
273/// Local collaboration substrate and internal host hooks remain directly
274/// callable, including through `ctx_call`; this gate only controls discovery.
275/// Withheld Hive tools are neither advertised nor callable.
276#[must_use]
277pub fn is_publicly_advertised_tool(name: &str) -> bool {
278    !is_local_collaboration_compatibility_tool(name)
279        && !INTERNAL_HOST_TOOLS.contains(&name)
280        && !is_withheld_hive_tool(name)
281}
282
283/// The error text for a call to a removed tool. Stable per name (no
284/// timestamps/counters) so provider-side prompt caching stays byte-stable (#498).
285#[must_use]
286pub fn removed_tool_message(name: &str) -> Option<String> {
287    removed_tool(name).map(|r| match r.replacement {
288        Some(replacement) => format!(
289            "{name} was removed; use {replacement} instead — {}.",
290            r.hint
291        ),
292        None => format!("{name} was removed — {}.", r.hint),
293    })
294}
295
296pub fn is_readonly_tool(name: &str) -> bool {
297    matches!(
298        name,
299        "ctx_read"
300            | "ctx_search"
301            | "ctx_tree"
302            | "ctx_metrics"
303            | "ctx_compress"
304            | "ctx_session"
305            | "ctx_knowledge"
306            | "ctx_graph"
307            | "ctx_provider"
308            | "ctx_delta"
309            | "ctx_outline"
310            | "ctx_context"
311            | "ctx_call"
312            | "ctx_url_read"
313            | "ctx_git_read"
314            | "ctx_callgraph"
315            | "ctx_index"
316            | "ctx_artifacts"
317            | "ctx_cost"
318            | "ctx_gain"
319            | "ctx_heatmap"
320    )
321}
322
323#[derive(Debug)]
324pub struct DynamicToolState {
325    active_categories: HashSet<ToolCategory>,
326    supports_list_changed: bool,
327}
328
329impl Default for DynamicToolState {
330    fn default() -> Self {
331        Self::new()
332    }
333}
334
335impl DynamicToolState {
336    pub fn new() -> Self {
337        let mut active = HashSet::new();
338        active.insert(ToolCategory::Core);
339        Self {
340            active_categories: active,
341            supports_list_changed: false,
342        }
343    }
344
345    /// Creates state with categories from config (env var > config.toml > default).
346    pub fn from_config(categories: &[String]) -> Self {
347        let mut active = HashSet::new();
348        active.insert(ToolCategory::Core);
349        for cat_str in categories {
350            if let Some(cat) = ToolCategory::parse(cat_str) {
351                active.insert(cat);
352            }
353        }
354        Self {
355            active_categories: active,
356            supports_list_changed: false,
357        }
358    }
359
360    pub fn all_enabled() -> Self {
361        let mut active = HashSet::new();
362        active.insert(ToolCategory::Core);
363        active.insert(ToolCategory::Arch);
364        active.insert(ToolCategory::Debug);
365        active.insert(ToolCategory::Memory);
366        active.insert(ToolCategory::Metrics);
367        active.insert(ToolCategory::Session);
368        Self {
369            active_categories: active,
370            supports_list_changed: false,
371        }
372    }
373
374    pub fn set_supports_list_changed(&mut self, val: bool) {
375        self.supports_list_changed = val;
376    }
377
378    pub fn supports_list_changed(&self) -> bool {
379        self.supports_list_changed
380    }
381
382    pub fn load_category(&mut self, cat: ToolCategory) -> bool {
383        self.active_categories.insert(cat)
384    }
385
386    pub fn unload_category(&mut self, cat: ToolCategory) -> bool {
387        if cat == ToolCategory::Core || cat == ToolCategory::Internal {
388            return false;
389        }
390        self.active_categories.remove(&cat)
391    }
392
393    pub fn is_tool_active(&self, name: &str) -> bool {
394        let cat = categorize_tool(name);
395        if cat == ToolCategory::Internal {
396            return false;
397        }
398        if !self.supports_list_changed {
399            // Clients without `list_changed` cannot progressively reveal a
400            // category. Keep experimental local collaboration out of their
401            // default surface too; an explicit config category still enables it.
402            return cat != ToolCategory::Session || self.active_categories.contains(&cat);
403        }
404        self.active_categories.contains(&cat)
405    }
406
407    pub fn active_categories(&self) -> Vec<&'static str> {
408        let mut cats: Vec<_> = self
409            .active_categories
410            .iter()
411            .map(ToolCategory::as_str)
412            .collect();
413        cats.sort_unstable();
414        cats
415    }
416
417    pub fn all_categories() -> Vec<&'static str> {
418        vec!["core", "arch", "debug", "memory", "metrics", "session"]
419    }
420}
421
422static GLOBAL: OnceLock<Mutex<DynamicToolState>> = OnceLock::new();
423
424pub fn global() -> &'static Mutex<DynamicToolState> {
425    GLOBAL.get_or_init(|| Mutex::new(DynamicToolState::new()))
426}
427
428pub fn init_all_enabled() {
429    let _ = GLOBAL.set(Mutex::new(DynamicToolState::all_enabled()));
430}
431
432/// Initializes the global state from user config (env var > config.toml > default).
433/// Call once during server startup after config is loaded.
434/// If the global was already initialized (e.g. by a concurrent `global()` call),
435/// applies the categories to the existing state instead.
436pub fn init_from_config(categories: &[String]) {
437    if GLOBAL
438        .set(Mutex::new(DynamicToolState::from_config(categories)))
439        .is_err()
440        && let Ok(mut state) = global().lock()
441    {
442        let desired = DynamicToolState::from_config(categories);
443        *state = desired;
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    #[test]
452    fn core_tools_always_active() {
453        let state = DynamicToolState::new();
454        assert!(state.is_tool_active("ctx_read"));
455        assert!(state.is_tool_active("ctx_search"));
456        assert!(!state.is_tool_active("ctx_agent"));
457    }
458
459    #[test]
460    fn removed_tools_point_at_a_live_public_tool() {
461        assert_eq!(
462            removed_tool("ctx_multi_read").unwrap().replacement,
463            Some("ctx_read")
464        );
465        assert!(removed_tool("ctx_read").is_none());
466        // No removed name may send agents to a tool that is gone or hidden.
467        let registry = crate::server::registry::build_registry();
468        let live = registry.names();
469        for name in [
470            "ctx_smart_read",
471            "ctx_multi_read",
472            "ctx_semantic_search",
473            "ctx_symbol",
474            "ctx_overview",
475            "ctx_summary",
476            "ctx_explore",
477            "ctx_plan",
478            "ctx_compile",
479            "ctx_fill",
480            "ctx_impact",
481            "ctx_architecture",
482            "ctx_repomap",
483            "ctx_routes",
484            "ctx_retrieve",
485            "ctx_cache",
486        ] {
487            let replacement = removed_tool(name).and_then(|r| r.replacement).unwrap();
488            assert!(!live.contains(&name), "{name} is still registered");
489            assert!(
490                live.contains(&replacement) && is_publicly_advertised_tool(replacement),
491                "{name} points at {replacement}, which is not a live public tool"
492            );
493        }
494    }
495
496    #[test]
497    fn local_collaboration_substrate_is_compatibility_only() {
498        for name in LOCAL_COLLABORATION_COMPATIBILITY_TOOLS {
499            assert!(is_local_collaboration_compatibility_tool(name));
500            assert!(!is_publicly_advertised_tool(name));
501        }
502        assert!(!is_local_collaboration_compatibility_tool("ctx_session"));
503        assert!(is_publicly_advertised_tool("ctx_session"));
504        // Host hooks are callable but must never cost agents prompt tokens.
505        assert!(!is_publicly_advertised_tool("ctx_shape"));
506    }
507
508    /// #2089: hosts reach ctx_shape through the listed ctx_call, so a call is a
509    /// host-hook call in every spelling — and only then.
510    #[test]
511    fn host_hook_calls_are_recognised_in_every_spelling() {
512        let args = |v: serde_json::Value| v.as_object().cloned();
513        let shape = args(serde_json::json!({"tool": "Bash", "output": "x"}));
514        assert!(targets_internal_host_tool("ctx_shape", shape.as_ref()));
515        let via_call =
516            args(serde_json::json!({"name": "ctx_shape", "arguments": {"tool": "Bash"}}));
517        assert!(targets_internal_host_tool("ctx_call", via_call.as_ref()));
518        let via_ctx = args(serde_json::json!({"tool": "shape", "output": "x"}));
519        assert!(targets_internal_host_tool("ctx", via_ctx.as_ref()));
520
521        let read = args(serde_json::json!({"name": "ctx_read", "arguments": {"path": "a"}}));
522        assert!(!targets_internal_host_tool("ctx_call", read.as_ref()));
523        assert!(!targets_internal_host_tool("ctx_read", None));
524        assert!(!targets_internal_host_tool("ctx_call", None));
525    }
526
527    #[test]
528    fn removed_tool_message_names_the_way_forward() {
529        let message = removed_tool_message("ctx_multi_read").unwrap();
530        assert!(message.starts_with("ctx_multi_read was removed; use ctx_read instead — "));
531        assert!(message.contains("paths="));
532        assert!(removed_tool_message("ctx_read").is_none());
533        let retired = removed_tool_message("ctx_smells").unwrap();
534        assert!(retired.starts_with("ctx_smells was removed — "));
535    }
536
537    #[test]
538    fn dynamic_tools_filtered_when_list_changed() {
539        let mut state = DynamicToolState::new();
540        state.set_supports_list_changed(true);
541        assert!(!state.is_tool_active("ctx_verify"));
542        assert!(!state.is_tool_active("ctx_index"));
543        assert!(state.is_tool_active("ctx_read"));
544    }
545
546    #[test]
547    fn load_category_enables_tools() {
548        let mut state = DynamicToolState::new();
549        state.set_supports_list_changed(true);
550        assert!(!state.is_tool_active("ctx_index"));
551        state.load_category(ToolCategory::Arch);
552        assert!(state.is_tool_active("ctx_index"));
553    }
554
555    #[test]
556    fn cannot_unload_core() {
557        let mut state = DynamicToolState::new();
558        assert!(!state.unload_category(ToolCategory::Core));
559    }
560
561    #[test]
562    fn all_tools_visible_without_list_changed() {
563        let state = DynamicToolState::new();
564        assert!(state.is_tool_active("ctx_graph"));
565        assert!(!state.is_tool_active("ctx_agent"));
566        assert!(!state.is_tool_active("ctx_metrics")); // Internal tools never active
567    }
568
569    #[test]
570    fn internal_tools_never_active() {
571        let state = DynamicToolState::all_enabled();
572        assert!(!state.is_tool_active("ctx_metrics"));
573        assert!(!state.is_tool_active("ctx_cost"));
574        assert!(!state.is_tool_active("ctx_discover_tools"));
575        assert!(!state.is_tool_active("ctx_dedup"));
576    }
577
578    // --- from_config: basic scenarios ---
579
580    #[test]
581    fn from_config_core_arch_memory() {
582        let cats = vec!["core".to_string(), "arch".to_string(), "memory".to_string()];
583        let mut state = DynamicToolState::from_config(&cats);
584        state.set_supports_list_changed(true);
585        assert!(state.is_tool_active("ctx_read"));
586        assert!(state.is_tool_active("ctx_index"));
587        assert!(state.is_tool_active("ctx_artifacts"));
588        assert!(!state.is_tool_active("ctx_verify"));
589        assert!(!state.is_tool_active("ctx_pack"));
590    }
591
592    #[test]
593    fn from_config_empty_still_has_core() {
594        let mut state = DynamicToolState::from_config(&[]);
595        state.set_supports_list_changed(true);
596        assert!(state.is_tool_active("ctx_read"));
597        assert!(!state.is_tool_active("ctx_index"));
598        assert!(!state.is_tool_active("ctx_verify"));
599        assert!(!state.is_tool_active("ctx_artifacts"));
600    }
601
602    // --- from_config: all categories ---
603
604    #[test]
605    fn from_config_all_categories_enables_everything_except_internal() {
606        let cats = vec![
607            "core".to_string(),
608            "arch".to_string(),
609            "debug".to_string(),
610            "memory".to_string(),
611            "metrics".to_string(),
612            "session".to_string(),
613        ];
614        let mut state = DynamicToolState::from_config(&cats);
615        state.set_supports_list_changed(true);
616        assert!(state.is_tool_active("ctx_read"));
617        assert!(state.is_tool_active("ctx_index"));
618        assert!(state.is_tool_active("ctx_verify"));
619        assert!(state.is_tool_active("ctx_provider"));
620        assert!(state.is_tool_active("ctx_pack"));
621        assert!(state.is_tool_active("ctx_work_graph"));
622        assert!(!state.is_tool_active("ctx_metrics"));
623    }
624
625    // --- from_config: single category ---
626
627    #[test]
628    fn from_config_only_debug() {
629        let cats = vec!["debug".to_string()];
630        let mut state = DynamicToolState::from_config(&cats);
631        state.set_supports_list_changed(true);
632        assert!(state.is_tool_active("ctx_read"));
633        assert!(state.is_tool_active("ctx_verify"));
634        assert!(!state.is_tool_active("ctx_index"));
635        assert!(!state.is_tool_active("ctx_work_graph"));
636    }
637
638    // --- from_config: invalid categories are silently ignored ---
639
640    #[test]
641    fn from_config_ignores_unknown_categories() {
642        let cats = vec![
643            "core".to_string(),
644            "nonexistent".to_string(),
645            "foobar".to_string(),
646        ];
647        let mut state = DynamicToolState::from_config(&cats);
648        state.set_supports_list_changed(true);
649        assert!(state.is_tool_active("ctx_read"));
650        assert!(!state.is_tool_active("ctx_index"));
651    }
652
653    #[test]
654    fn from_config_only_invalid_still_has_core() {
655        let cats = vec!["invalid".to_string(), "bogus".to_string()];
656        let mut state = DynamicToolState::from_config(&cats);
657        state.set_supports_list_changed(true);
658        assert!(state.is_tool_active("ctx_read"));
659        assert!(!state.is_tool_active("ctx_verify"));
660    }
661
662    // --- from_config: duplicate categories are idempotent ---
663
664    #[test]
665    fn from_config_duplicates_are_harmless() {
666        let cats = vec!["arch".to_string(), "arch".to_string(), "arch".to_string()];
667        let mut state = DynamicToolState::from_config(&cats);
668        state.set_supports_list_changed(true);
669        assert!(state.is_tool_active("ctx_index"));
670        let active = state.active_categories();
671        let arch_count = active.iter().filter(|&&c| c == "arch").count();
672        assert_eq!(arch_count, 1);
673    }
674
675    // --- from_config: internal category is never user-activatable ---
676
677    #[test]
678    fn from_config_internal_category_not_parseable() {
679        assert!(ToolCategory::parse("internal").is_none());
680    }
681
682    // --- from_config: category aliases work ---
683
684    #[test]
685    fn from_config_alias_architecture_maps_to_arch() {
686        let cats = vec!["architecture".to_string()];
687        let mut state = DynamicToolState::from_config(&cats);
688        state.set_supports_list_changed(true);
689        assert!(state.is_tool_active("ctx_index"));
690    }
691
692    #[test]
693    fn from_config_alias_profiling_maps_to_debug() {
694        let cats = vec!["profiling".to_string()];
695        let mut state = DynamicToolState::from_config(&cats);
696        state.set_supports_list_changed(true);
697        assert!(state.is_tool_active("ctx_verify"));
698    }
699
700    #[test]
701    fn from_config_alias_semantic_maps_to_memory() {
702        let cats = vec!["semantic".to_string()];
703        let mut state = DynamicToolState::from_config(&cats);
704        state.set_supports_list_changed(true);
705        assert!(state.is_tool_active("ctx_artifacts"));
706    }
707
708    // --- from_config: subsequent load/unload still works ---
709
710    #[test]
711    fn from_config_then_load_additional_category() {
712        let cats = vec!["core".to_string()];
713        let mut state = DynamicToolState::from_config(&cats);
714        state.set_supports_list_changed(true);
715        assert!(!state.is_tool_active("ctx_index"));
716        state.load_category(ToolCategory::Arch);
717        assert!(state.is_tool_active("ctx_index"));
718    }
719
720    #[test]
721    fn from_config_then_unload_non_core_category() {
722        let cats = vec!["core".to_string(), "arch".to_string()];
723        let mut state = DynamicToolState::from_config(&cats);
724        state.set_supports_list_changed(true);
725        assert!(state.is_tool_active("ctx_index"));
726        state.unload_category(ToolCategory::Arch);
727        assert!(!state.is_tool_active("ctx_index"));
728    }
729
730    #[test]
731    fn from_config_cannot_unload_core() {
732        let cats = vec!["core".to_string(), "arch".to_string()];
733        let mut state = DynamicToolState::from_config(&cats);
734        assert!(!state.unload_category(ToolCategory::Core));
735    }
736
737    // --- from_config: without list_changed, all tools visible ---
738
739    #[test]
740    fn from_config_without_list_changed_shows_all() {
741        let cats = vec!["core".to_string()];
742        let state = DynamicToolState::from_config(&cats);
743        assert!(state.is_tool_active("ctx_index"));
744        assert!(state.is_tool_active("ctx_verify"));
745        assert!(!state.is_tool_active("ctx_metrics"));
746    }
747
748    #[test]
749    fn lazy_core_tools_survive_default_category_gate() {
750        // Regression for #575: every advertised lazy-core tool must stay
751        // active under the default category gate (Core + Session) when the
752        // client supports list_changed — otherwise Cursor silently loses
753        // tools like ctx_expand from the 13-tool core set.
754        let mut state = DynamicToolState::new();
755        state.set_supports_list_changed(true);
756        for name in crate::tool_defs::core_tool_names() {
757            assert!(
758                state.is_tool_active(name),
759                "{name} is in CORE_TOOL_NAMES but dropped by the default category gate"
760            );
761        }
762    }
763
764    #[test]
765    fn categorize_known_tools() {
766        assert_eq!(categorize_tool("ctx_read"), ToolCategory::Core);
767        assert_eq!(categorize_tool("ctx_graph"), ToolCategory::Core);
768        // #1008: anchored editing is a core workflow — an explicit Core entry so
769        // the category gate can never hide the lazy-core editor.
770        assert_eq!(categorize_tool("ctx_patch"), ToolCategory::Core);
771        assert_eq!(categorize_tool("ctx_verify"), ToolCategory::Debug);
772        assert_eq!(categorize_tool("ctx_provider"), ToolCategory::Core);
773        assert_eq!(categorize_tool("ctx_artifacts"), ToolCategory::Memory);
774        assert_eq!(categorize_tool("ctx_metrics"), ToolCategory::Internal);
775        assert_eq!(categorize_tool("ctx_work_graph"), ToolCategory::Session);
776    }
777
778    #[test]
779    fn readonly_classification() {
780        assert!(is_readonly_tool("ctx_read"));
781        assert!(is_readonly_tool("ctx_search"));
782        assert!(is_readonly_tool("ctx_tree"));
783        assert!(is_readonly_tool("ctx_graph"));
784        assert!(is_readonly_tool("ctx_provider"));
785
786        assert!(!is_readonly_tool("ctx_edit"));
787        assert!(!is_readonly_tool("ctx_shell"));
788        assert!(!is_readonly_tool("ctx_patch"));
789        assert!(!is_readonly_tool("ctx_execute"));
790        assert!(!is_readonly_tool("ctx_work_graph"));
791    }
792
793    #[test]
794    fn plan_mode_tools_are_all_readonly() {
795        for tool in crate::core::editor_registry::plan_mode::plan_mode_tools() {
796            assert!(
797                is_readonly_tool(tool),
798                "{tool} is listed as plan mode tool but not marked readonly"
799            );
800        }
801    }
802}