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 "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"
60 | "ctx_shape" => ToolCategory::Internal,
61
62 "ctx_read" | "ctx_search" | "ctx_shell" | "shell" | "ctx_tree" | "ctx_edit"
69 | "ctx_patch" | "ctx_session" | "ctx_checkpoint" | "ctx_knowledge" | "ctx_overview"
70 | "ctx_graph" | "ctx_callgraph" | "ctx_call" | "ctx_compress" | "ctx_cache"
71 | "ctx_retrieve" | "ctx_expand" => ToolCategory::Core,
72
73 "ctx_multi_read" | "ctx_smart_read" | "ctx_delta" | "ctx_outline" | "ctx_context" => {
75 ToolCategory::Core
76 }
77
78 "ctx_architecture" | "ctx_impact" | "ctx_refactor" | "ctx_symbol" | "ctx_routes"
80 | "ctx_smells" | "ctx_quality" | "ctx_index" => ToolCategory::Arch,
81
82 "ctx_benchmark" | "ctx_verify" | "ctx_analyze" | "ctx_profile" | "ctx_proof"
84 | "ctx_review" | "ctx_compare" => ToolCategory::Debug,
85
86 "ctx_provider" | "ctx_url_read" | "ctx_git_read" | "ctx_tools" | "ctx_semantic_search" => {
93 ToolCategory::Core
94 }
95
96 "ctx_artifacts" => ToolCategory::Memory,
98
99 "ctx_fill" | "ctx_execute" | "ctx_pack" | "ctx_plan" | "ctx_control" | "ctx_compile" => {
101 ToolCategory::Metrics
102 }
103
104 "ctx_agent" | "ctx_share" | "ctx_task" | "ctx_handoff" | "ctx_workflow"
106 | "ctx_work_graph" => ToolCategory::Session,
107
108 _ => ToolCategory::Core,
109 }
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct DeprecatedAlias {
119 pub replacement: &'static str,
121 pub hint: &'static str,
123}
124
125#[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 "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#[must_use]
159pub fn is_deprecated_alias(name: &str) -> bool {
160 deprecated_alias(name).is_some()
161}
162
163pub const LOCAL_COLLABORATION_COMPATIBILITY_TOOLS: &[&str] = &[
170 "ctx_agent",
171 "ctx_share",
172 "ctx_task",
173 "ctx_handoff",
174 "ctx_workflow",
175];
176
177#[must_use]
180pub fn is_local_collaboration_compatibility_tool(name: &str) -> bool {
181 LOCAL_COLLABORATION_COMPATIBILITY_TOOLS.contains(&name)
182}
183
184pub const INTERNAL_HOST_TOOLS: &[&str] = &["ctx_shape"];
188
189#[must_use]
195pub fn is_publicly_advertised_tool(name: &str) -> bool {
196 !is_deprecated_alias(name)
197 && !is_local_collaboration_compatibility_tool(name)
198 && !INTERNAL_HOST_TOOLS.contains(&name)
199}
200
201#[must_use]
205pub fn deprecation_notice(name: &str) -> Option<String> {
206 deprecated_alias(name).map(|d| {
207 format!(
208 "[DEPRECATED] {name} is superseded by {} — {}. This alias is hidden from \
209 tools/list and will be removed in a future release.",
210 d.replacement, d.hint
211 )
212 })
213}
214
215pub fn is_readonly_tool(name: &str) -> bool {
216 matches!(
217 name,
218 "ctx_read"
219 | "ctx_search"
220 | "ctx_tree"
221 | "ctx_overview"
222 | "ctx_plan"
223 | "ctx_metrics"
224 | "ctx_compress"
225 | "ctx_session"
226 | "ctx_knowledge"
227 | "ctx_graph"
228 | "ctx_retrieve"
229 | "ctx_provider"
230 | "ctx_multi_read"
231 | "ctx_smart_read"
232 | "ctx_delta"
233 | "ctx_outline"
234 | "ctx_context"
235 | "ctx_call"
236 | "ctx_url_read"
237 | "ctx_git_read"
238 | "ctx_architecture"
239 | "ctx_impact"
240 | "ctx_callgraph"
241 | "ctx_symbol"
242 | "ctx_routes"
243 | "ctx_smells"
244 | "ctx_quality"
245 | "ctx_index"
246 | "ctx_semantic_search"
247 | "ctx_explore"
248 | "ctx_artifacts"
249 | "ctx_cost"
250 | "ctx_gain"
251 | "ctx_heatmap"
252 | "ctx_compare"
253 )
254}
255
256#[derive(Debug)]
257pub struct DynamicToolState {
258 active_categories: HashSet<ToolCategory>,
259 supports_list_changed: bool,
260}
261
262impl Default for DynamicToolState {
263 fn default() -> Self {
264 Self::new()
265 }
266}
267
268impl DynamicToolState {
269 pub fn new() -> Self {
270 let mut active = HashSet::new();
271 active.insert(ToolCategory::Core);
272 Self {
273 active_categories: active,
274 supports_list_changed: false,
275 }
276 }
277
278 pub fn from_config(categories: &[String]) -> Self {
280 let mut active = HashSet::new();
281 active.insert(ToolCategory::Core);
282 for cat_str in categories {
283 if let Some(cat) = ToolCategory::parse(cat_str) {
284 active.insert(cat);
285 }
286 }
287 Self {
288 active_categories: active,
289 supports_list_changed: false,
290 }
291 }
292
293 pub fn all_enabled() -> Self {
294 let mut active = HashSet::new();
295 active.insert(ToolCategory::Core);
296 active.insert(ToolCategory::Arch);
297 active.insert(ToolCategory::Debug);
298 active.insert(ToolCategory::Memory);
299 active.insert(ToolCategory::Metrics);
300 active.insert(ToolCategory::Session);
301 Self {
302 active_categories: active,
303 supports_list_changed: false,
304 }
305 }
306
307 pub fn set_supports_list_changed(&mut self, val: bool) {
308 self.supports_list_changed = val;
309 }
310
311 pub fn supports_list_changed(&self) -> bool {
312 self.supports_list_changed
313 }
314
315 pub fn load_category(&mut self, cat: ToolCategory) -> bool {
316 self.active_categories.insert(cat)
317 }
318
319 pub fn unload_category(&mut self, cat: ToolCategory) -> bool {
320 if cat == ToolCategory::Core || cat == ToolCategory::Internal {
321 return false;
322 }
323 self.active_categories.remove(&cat)
324 }
325
326 pub fn is_tool_active(&self, name: &str) -> bool {
327 let cat = categorize_tool(name);
328 if cat == ToolCategory::Internal {
329 return false;
330 }
331 if !self.supports_list_changed {
332 return cat != ToolCategory::Session || self.active_categories.contains(&cat);
336 }
337 self.active_categories.contains(&cat)
338 }
339
340 pub fn active_categories(&self) -> Vec<&'static str> {
341 let mut cats: Vec<_> = self
342 .active_categories
343 .iter()
344 .map(ToolCategory::as_str)
345 .collect();
346 cats.sort_unstable();
347 cats
348 }
349
350 pub fn all_categories() -> Vec<&'static str> {
351 vec!["core", "arch", "debug", "memory", "metrics", "session"]
352 }
353}
354
355static GLOBAL: OnceLock<Mutex<DynamicToolState>> = OnceLock::new();
356
357pub fn global() -> &'static Mutex<DynamicToolState> {
358 GLOBAL.get_or_init(|| Mutex::new(DynamicToolState::new()))
359}
360
361pub fn init_all_enabled() {
362 let _ = GLOBAL.set(Mutex::new(DynamicToolState::all_enabled()));
363}
364
365pub fn init_from_config(categories: &[String]) {
370 if GLOBAL
371 .set(Mutex::new(DynamicToolState::from_config(categories)))
372 .is_err()
373 && let Ok(mut state) = global().lock()
374 {
375 let desired = DynamicToolState::from_config(categories);
376 *state = desired;
377 }
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383
384 #[test]
385 fn core_tools_always_active() {
386 let state = DynamicToolState::new();
387 assert!(state.is_tool_active("ctx_read"));
388 assert!(state.is_tool_active("ctx_search"));
389 assert!(!state.is_tool_active("ctx_agent"));
390 assert!(!state.is_tool_active("ctx_task"));
391 assert!(!state.is_tool_active("ctx_workflow"));
392 }
393
394 #[test]
395 fn deprecated_alias_maps_read_cluster_to_ctx_read() {
396 assert_eq!(
399 deprecated_alias("ctx_smart_read").unwrap().replacement,
400 "ctx_read"
401 );
402 assert_eq!(
403 deprecated_alias("ctx_multi_read").unwrap().replacement,
404 "ctx_read"
405 );
406 assert!(deprecated_alias("ctx_read").is_none());
407 assert!(deprecated_alias("ctx_search").is_none());
408 assert!(is_deprecated_alias("ctx_multi_read"));
409 assert!(!is_deprecated_alias("ctx_read"));
410
411 assert_eq!(
413 deprecated_alias("ctx_semantic_search").unwrap().replacement,
414 "ctx_search"
415 );
416 assert_eq!(
417 deprecated_alias("ctx_symbol").unwrap().replacement,
418 "ctx_search"
419 );
420 assert!(is_deprecated_alias("ctx_symbol"));
421 }
422
423 #[test]
424 fn local_collaboration_substrate_is_compatibility_only() {
425 for name in LOCAL_COLLABORATION_COMPATIBILITY_TOOLS {
426 assert!(is_local_collaboration_compatibility_tool(name));
427 assert!(!is_publicly_advertised_tool(name));
428 }
429 assert!(!is_local_collaboration_compatibility_tool("ctx_session"));
430 assert!(is_publicly_advertised_tool("ctx_session"));
431 assert!(!is_publicly_advertised_tool("ctx_shape"));
433 }
434
435 #[test]
436 fn deprecation_notice_is_stable_and_names_replacement() {
437 let notice = deprecation_notice("ctx_multi_read").unwrap();
440 assert!(notice.starts_with("[DEPRECATED] ctx_multi_read is superseded by ctx_read"));
441 assert!(notice.contains("paths="));
442 assert_eq!(notice, deprecation_notice("ctx_multi_read").unwrap());
443 assert!(deprecation_notice("ctx_read").is_none());
444 }
445
446 #[test]
447 fn dynamic_tools_filtered_when_list_changed() {
448 let mut state = DynamicToolState::new();
449 state.set_supports_list_changed(true);
450 assert!(!state.is_tool_active("ctx_benchmark"));
451 assert!(!state.is_tool_active("ctx_architecture"));
452 assert!(state.is_tool_active("ctx_read"));
453 }
454
455 #[test]
456 fn load_category_enables_tools() {
457 let mut state = DynamicToolState::new();
458 state.set_supports_list_changed(true);
459 assert!(!state.is_tool_active("ctx_architecture"));
460 state.load_category(ToolCategory::Arch);
461 assert!(state.is_tool_active("ctx_architecture"));
462 }
463
464 #[test]
465 fn cannot_unload_core() {
466 let mut state = DynamicToolState::new();
467 assert!(!state.unload_category(ToolCategory::Core));
468 }
469
470 #[test]
471 fn all_tools_visible_without_list_changed() {
472 let state = DynamicToolState::new();
473 assert!(state.is_tool_active("ctx_graph"));
474 assert!(!state.is_tool_active("ctx_agent"));
475 assert!(!state.is_tool_active("ctx_metrics")); }
477
478 #[test]
479 fn internal_tools_never_active() {
480 let state = DynamicToolState::all_enabled();
481 assert!(!state.is_tool_active("ctx_metrics"));
482 assert!(!state.is_tool_active("ctx_cost"));
483 assert!(!state.is_tool_active("ctx_discover_tools"));
484 assert!(!state.is_tool_active("ctx_dedup"));
485 }
486
487 #[test]
490 fn from_config_core_arch_memory() {
491 let cats = vec!["core".to_string(), "arch".to_string(), "memory".to_string()];
492 let mut state = DynamicToolState::from_config(&cats);
493 state.set_supports_list_changed(true);
494 assert!(state.is_tool_active("ctx_read"));
495 assert!(state.is_tool_active("ctx_architecture"));
496 assert!(state.is_tool_active("ctx_artifacts"));
497 assert!(!state.is_tool_active("ctx_benchmark"));
498 assert!(!state.is_tool_active("ctx_fill"));
499 }
500
501 #[test]
502 fn from_config_empty_still_has_core() {
503 let mut state = DynamicToolState::from_config(&[]);
504 state.set_supports_list_changed(true);
505 assert!(state.is_tool_active("ctx_read"));
506 assert!(!state.is_tool_active("ctx_architecture"));
507 assert!(!state.is_tool_active("ctx_benchmark"));
508 assert!(!state.is_tool_active("ctx_artifacts"));
509 }
510
511 #[test]
514 fn from_config_all_categories_enables_everything_except_internal() {
515 let cats = vec![
516 "core".to_string(),
517 "arch".to_string(),
518 "debug".to_string(),
519 "memory".to_string(),
520 "metrics".to_string(),
521 "session".to_string(),
522 ];
523 let mut state = DynamicToolState::from_config(&cats);
524 state.set_supports_list_changed(true);
525 assert!(state.is_tool_active("ctx_read"));
526 assert!(state.is_tool_active("ctx_architecture"));
527 assert!(state.is_tool_active("ctx_benchmark"));
528 assert!(state.is_tool_active("ctx_semantic_search"));
529 assert!(state.is_tool_active("ctx_fill"));
530 assert!(state.is_tool_active("ctx_workflow"));
531 assert!(!state.is_tool_active("ctx_metrics"));
532 }
533
534 #[test]
537 fn from_config_only_debug() {
538 let cats = vec!["debug".to_string()];
539 let mut state = DynamicToolState::from_config(&cats);
540 state.set_supports_list_changed(true);
541 assert!(state.is_tool_active("ctx_read"));
542 assert!(state.is_tool_active("ctx_benchmark"));
543 assert!(!state.is_tool_active("ctx_architecture"));
544 assert!(!state.is_tool_active("ctx_workflow"));
545 }
546
547 #[test]
550 fn from_config_ignores_unknown_categories() {
551 let cats = vec![
552 "core".to_string(),
553 "nonexistent".to_string(),
554 "foobar".to_string(),
555 ];
556 let mut state = DynamicToolState::from_config(&cats);
557 state.set_supports_list_changed(true);
558 assert!(state.is_tool_active("ctx_read"));
559 assert!(!state.is_tool_active("ctx_architecture"));
560 }
561
562 #[test]
563 fn from_config_only_invalid_still_has_core() {
564 let cats = vec!["invalid".to_string(), "bogus".to_string()];
565 let mut state = DynamicToolState::from_config(&cats);
566 state.set_supports_list_changed(true);
567 assert!(state.is_tool_active("ctx_read"));
568 assert!(!state.is_tool_active("ctx_benchmark"));
569 }
570
571 #[test]
574 fn from_config_duplicates_are_harmless() {
575 let cats = vec!["arch".to_string(), "arch".to_string(), "arch".to_string()];
576 let mut state = DynamicToolState::from_config(&cats);
577 state.set_supports_list_changed(true);
578 assert!(state.is_tool_active("ctx_architecture"));
579 let active = state.active_categories();
580 let arch_count = active.iter().filter(|&&c| c == "arch").count();
581 assert_eq!(arch_count, 1);
582 }
583
584 #[test]
587 fn from_config_internal_category_not_parseable() {
588 assert!(ToolCategory::parse("internal").is_none());
589 }
590
591 #[test]
594 fn from_config_alias_architecture_maps_to_arch() {
595 let cats = vec!["architecture".to_string()];
596 let mut state = DynamicToolState::from_config(&cats);
597 state.set_supports_list_changed(true);
598 assert!(state.is_tool_active("ctx_architecture"));
599 }
600
601 #[test]
602 fn from_config_alias_profiling_maps_to_debug() {
603 let cats = vec!["profiling".to_string()];
604 let mut state = DynamicToolState::from_config(&cats);
605 state.set_supports_list_changed(true);
606 assert!(state.is_tool_active("ctx_benchmark"));
607 }
608
609 #[test]
610 fn from_config_alias_semantic_maps_to_memory() {
611 let cats = vec!["semantic".to_string()];
612 let mut state = DynamicToolState::from_config(&cats);
613 state.set_supports_list_changed(true);
614 assert!(state.is_tool_active("ctx_artifacts"));
615 }
616
617 #[test]
620 fn from_config_then_load_additional_category() {
621 let cats = vec!["core".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.load_category(ToolCategory::Arch);
626 assert!(state.is_tool_active("ctx_architecture"));
627 }
628
629 #[test]
630 fn from_config_then_unload_non_core_category() {
631 let cats = vec!["core".to_string(), "arch".to_string()];
632 let mut state = DynamicToolState::from_config(&cats);
633 state.set_supports_list_changed(true);
634 assert!(state.is_tool_active("ctx_architecture"));
635 state.unload_category(ToolCategory::Arch);
636 assert!(!state.is_tool_active("ctx_architecture"));
637 }
638
639 #[test]
640 fn from_config_cannot_unload_core() {
641 let cats = vec!["core".to_string(), "arch".to_string()];
642 let mut state = DynamicToolState::from_config(&cats);
643 assert!(!state.unload_category(ToolCategory::Core));
644 }
645
646 #[test]
649 fn from_config_without_list_changed_shows_all() {
650 let cats = vec!["core".to_string()];
651 let state = DynamicToolState::from_config(&cats);
652 assert!(state.is_tool_active("ctx_architecture"));
653 assert!(state.is_tool_active("ctx_benchmark"));
654 assert!(!state.is_tool_active("ctx_metrics"));
655 }
656
657 #[test]
658 fn lazy_core_tools_survive_default_category_gate() {
659 let mut state = DynamicToolState::new();
664 state.set_supports_list_changed(true);
665 for name in crate::tool_defs::core_tool_names() {
666 assert!(
667 state.is_tool_active(name),
668 "{name} is in CORE_TOOL_NAMES but dropped by the default category gate"
669 );
670 }
671 }
672
673 #[test]
674 fn categorize_known_tools() {
675 assert_eq!(categorize_tool("ctx_read"), ToolCategory::Core);
676 assert_eq!(categorize_tool("ctx_graph"), ToolCategory::Core);
677 assert_eq!(categorize_tool("ctx_patch"), ToolCategory::Core);
680 assert_eq!(categorize_tool("ctx_benchmark"), ToolCategory::Debug);
681 assert_eq!(categorize_tool("ctx_semantic_search"), ToolCategory::Core);
682 assert_eq!(categorize_tool("ctx_artifacts"), ToolCategory::Memory);
683 assert_eq!(categorize_tool("ctx_metrics"), ToolCategory::Internal);
684 assert_eq!(categorize_tool("ctx_workflow"), ToolCategory::Session);
685 }
686
687 #[test]
688 fn readonly_classification() {
689 assert!(is_readonly_tool("ctx_read"));
690 assert!(is_readonly_tool("ctx_search"));
691 assert!(is_readonly_tool("ctx_tree"));
692 assert!(is_readonly_tool("ctx_overview"));
693 assert!(is_readonly_tool("ctx_provider"));
694
695 assert!(!is_readonly_tool("ctx_edit"));
696 assert!(!is_readonly_tool("ctx_shell"));
697 assert!(!is_readonly_tool("ctx_compile"));
698 assert!(!is_readonly_tool("ctx_execute"));
699 assert!(!is_readonly_tool("ctx_cache"));
700 }
701
702 #[test]
703 fn plan_mode_tools_are_all_readonly() {
704 for tool in crate::core::editor_registry::plan_mode::plan_mode_tools() {
705 assert!(
706 is_readonly_tool(tool),
707 "{tool} is listed as plan mode tool but not marked readonly"
708 );
709 }
710 }
711}