1use std::fmt;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum ToolProfile {
17 Minimal,
18 Standard,
19 Power,
20 Auto,
21 Custom(Vec<String>),
22}
23
24impl ToolProfile {
25 pub fn parse(s: &str) -> Option<Self> {
26 match s.to_lowercase().as_str() {
27 "minimal" | "min" => Some(Self::Minimal),
28 "standard" | "std" | "default" => Some(Self::Standard),
29 "power" | "full" | "all" => Some(Self::Power),
30 "auto" => Some(Self::Auto),
31 _ => None,
32 }
33 }
34
35 pub fn as_str(&self) -> &str {
36 match self {
37 Self::Minimal => "minimal",
38 Self::Standard => "standard",
39 Self::Power => "power",
40 Self::Auto => "auto",
41 Self::Custom(_) => "custom",
42 }
43 }
44
45 pub fn description(&self) -> &str {
46 match self {
47 Self::Minimal => "5 surgical tools — each irreplaceable (recommended)",
48 Self::Standard => "15 balanced tools (adds compose, callgraph, graph, patch, more)",
49 Self::Power => "All tools exposed",
50 Self::Auto => "Starts minimal, escalates based on session complexity",
51 Self::Custom(v) => {
52 if v.is_empty() {
53 "Custom tool list (empty)"
54 } else {
55 "Custom tool list"
56 }
57 }
58 }
59 }
60
61 #[must_use]
65 pub fn without_tool(&self, tool_name: &str) -> Self {
66 if !self.is_tool_enabled(tool_name) {
67 return self.clone();
68 }
69 match self {
70 Self::Power => Self::Custom(
71 crate::tool_defs::CORE_TOOL_NAMES
72 .iter()
73 .chain(STANDARD_TOOLS.iter())
74 .copied()
75 .filter(|t| *t != tool_name)
76 .collect::<std::collections::BTreeSet<_>>()
77 .into_iter()
78 .map(String::from)
79 .collect(),
80 ),
81 Self::Standard => Self::Custom(
82 STANDARD_TOOLS
83 .iter()
84 .filter(|t| **t != tool_name)
85 .map(|t| String::from(*t))
86 .collect(),
87 ),
88 Self::Minimal => Self::Custom(
89 MINIMAL_TOOLS
90 .iter()
91 .filter(|t| **t != tool_name)
92 .map(|t| String::from(*t))
93 .collect(),
94 ),
95 Self::Auto => Self::Auto,
96 Self::Custom(list) => Self::Custom(
97 list.iter()
98 .filter(|t| t.as_str() != tool_name)
99 .cloned()
100 .collect(),
101 ),
102 }
103 }
104
105 pub fn is_tool_enabled(&self, tool_name: &str) -> bool {
106 match self {
107 Self::Power => true,
108 Self::Minimal | Self::Auto => MINIMAL_TOOLS.contains(&tool_name),
109 Self::Standard => STANDARD_TOOLS.contains(&tool_name),
110 Self::Custom(list) => list.iter().any(|t| t == tool_name),
111 }
112 }
113
114 pub fn tool_count(&self) -> usize {
115 match self {
116 Self::Minimal | Self::Auto => MINIMAL_TOOLS.len(),
117 Self::Standard => STANDARD_TOOLS.len(),
118 Self::Power => 0, Self::Custom(list) => list.len(),
120 }
121 }
122
123 pub fn tool_names(&self) -> Vec<&str> {
124 match self {
125 Self::Minimal | Self::Auto => MINIMAL_TOOLS.to_vec(),
126 Self::Standard => STANDARD_TOOLS.to_vec(),
127 Self::Power | Self::Custom(_) => vec![],
128 }
129 }
130
131 pub fn resolve_auto(
137 turn_count: u64,
138 has_used_ctx_tools: bool,
139 system_prompt_tokens: usize,
140 ) -> ToolProfile {
141 if has_used_ctx_tools {
142 return ToolProfile::Standard;
143 }
144 if turn_count >= 10 {
145 return ToolProfile::Power;
146 }
147 if turn_count < 2 && system_prompt_tokens < 2000 {
148 return ToolProfile::Minimal;
149 }
150 ToolProfile::Standard
151 }
152
153 pub fn from_config(cfg: &super::config::Config) -> Self {
159 if let Ok(val) = std::env::var("LEAN_CTX_TOOL_PROFILE") {
160 let trimmed = val.trim();
161 if let Some(profile) = Self::parse(trimmed) {
162 return profile;
163 }
164 if !trimmed.is_empty() && !is_unpinned_alias(trimmed) {
166 tracing::warn!("Unknown LEAN_CTX_TOOL_PROFILE value '{trimmed}', using config");
167 }
168 }
169
170 if let Some(ref profile_name) = cfg.tool_profile {
171 if let Some(profile) = Self::parse(profile_name) {
172 return profile;
173 }
174 if !is_unpinned_alias(profile_name) {
180 tracing::warn!("Unknown tool_profile '{profile_name}' in config, using default");
181 }
182 }
183
184 if !cfg.tools_enabled.is_empty() {
185 return Self::Custom(cfg.tools_enabled.clone());
186 }
187
188 Self::Power
189 }
190}
191
192impl fmt::Display for ToolProfile {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 write!(f, "{}", self.as_str())
195 }
196}
197
198pub fn is_unpinned_alias(name: &str) -> bool {
206 matches!(
207 name.trim().to_ascii_lowercase().as_str(),
208 "" | "lean" | "lazy" | "reset"
209 )
210}
211
212const MINIMAL_TOOLS: &[&str] = &[
218 "ctx_read",
219 "ctx_shell",
220 "ctx_search",
221 "ctx_glob",
222 "ctx_tree",
223];
224
225const STANDARD_TOOLS: &[&str] = &[
235 "ctx_read",
236 "ctx_shell",
237 "ctx_search",
238 "ctx_glob",
239 "ctx_tree",
240 "ctx_compose",
241 "ctx_knowledge",
242 "ctx_session",
243 "ctx_callgraph",
244 "ctx_graph",
245 "ctx_delta",
246 "ctx_execute",
247 "ctx_expand",
248 "ctx_url_read",
249 "ctx_patch",
250];
251
252pub const PROFILE_NAMES: &[&str] = &["minimal", "standard", "power", "auto"];
254
255pub struct ProfileInfo {
256 pub name: &'static str,
257 pub tool_count: &'static str,
258 pub description: &'static str,
259}
260
261pub fn list_profiles() -> Vec<ProfileInfo> {
262 vec![
263 ProfileInfo {
264 name: "minimal",
265 tool_count: "5",
266 description: "Surgical core — each tool irreplaceable (recommended)",
267 },
268 ProfileInfo {
269 name: "standard",
270 tool_count: "15",
271 description: "Balanced set — adds compose, knowledge, session, callgraph, patch, more",
272 },
273 ProfileInfo {
274 name: "power",
275 tool_count: "all",
276 description: "Every tool exposed (backward compatible)",
277 },
278 ProfileInfo {
279 name: "auto",
280 tool_count: "5→all",
281 description: "Starts minimal, escalates based on session complexity",
282 },
283 ]
284}
285
286pub fn set_profile_in_config(profile_name: &str) -> Result<(), String> {
289 let config_path = crate::core::config::Config::path()
293 .ok_or_else(|| "Cannot determine config dir".to_string())?;
294
295 let mut doc = crate::config_io::load_toml_document(&config_path);
296 doc["tool_profile"] = toml_edit::value(profile_name);
297 crate::config_io::write_toml_document(&config_path, &doc)?;
298 Ok(())
299}
300
301pub fn clear_profile_in_config() -> Result<(), String> {
306 let config_path = crate::core::config::Config::path()
307 .ok_or_else(|| "Cannot determine config dir".to_string())?;
308 if !config_path.exists() {
309 return Ok(());
310 }
311
312 let mut doc = crate::config_io::load_toml_document(&config_path);
313 if doc.remove("tool_profile").is_none() {
314 return Ok(());
315 }
316 crate::config_io::write_toml_document(&config_path, &doc)?;
317 Ok(())
318}
319
320#[cfg(test)]
321mod tests {
322 use super::{
323 MINIMAL_TOOLS, PROFILE_NAMES, STANDARD_TOOLS, ToolProfile, clear_profile_in_config,
324 is_unpinned_alias, list_profiles, set_profile_in_config,
325 };
326
327 #[test]
328 fn parse_known_profiles() {
329 assert_eq!(ToolProfile::parse("minimal"), Some(ToolProfile::Minimal));
330 assert_eq!(ToolProfile::parse("min"), Some(ToolProfile::Minimal));
331 assert_eq!(ToolProfile::parse("standard"), Some(ToolProfile::Standard));
332 assert_eq!(ToolProfile::parse("std"), Some(ToolProfile::Standard));
333 assert_eq!(ToolProfile::parse("default"), Some(ToolProfile::Standard));
334 assert_eq!(ToolProfile::parse("power"), Some(ToolProfile::Power));
335 assert_eq!(ToolProfile::parse("full"), Some(ToolProfile::Power));
336 assert_eq!(ToolProfile::parse("all"), Some(ToolProfile::Power));
337 assert_eq!(ToolProfile::parse("auto"), Some(ToolProfile::Auto));
338 }
339
340 #[test]
341 fn parse_case_insensitive() {
342 assert_eq!(ToolProfile::parse("MINIMAL"), Some(ToolProfile::Minimal));
343 assert_eq!(ToolProfile::parse("Standard"), Some(ToolProfile::Standard));
344 assert_eq!(ToolProfile::parse("POWER"), Some(ToolProfile::Power));
345 }
346
347 #[test]
348 fn parse_unknown_returns_none() {
349 assert_eq!(ToolProfile::parse("unknown"), None);
350 assert_eq!(ToolProfile::parse(""), None);
351 }
352
353 #[test]
354 fn minimal_profile_schema_budget() {
355 const MINIMAL_SCHEMA_BUDGET_TOKENS: usize = 2800;
359 let defs = crate::server::registry::build_registry().tool_defs();
360 let total: usize = defs
361 .iter()
362 .filter(|t| MINIMAL_TOOLS.contains(&t.name.as_ref()))
363 .map(crate::core::context_overhead::tool_tokens)
364 .sum();
365 assert!(total > 0, "minimal tools must exist in the registry");
366 assert!(
367 total <= MINIMAL_SCHEMA_BUDGET_TOKENS,
368 "minimal-profile tool schemas = {total} tok, budget {MINIMAL_SCHEMA_BUDGET_TOKENS}"
369 );
370 }
371
372 #[test]
373 fn minimal_is_subset_of_standard() {
374 for tool in MINIMAL_TOOLS {
375 assert!(
376 STANDARD_TOOLS.contains(tool),
377 "minimal tool {tool} missing from standard"
378 );
379 }
380 }
381
382 #[test]
383 fn power_enables_everything() {
384 let profile = ToolProfile::Power;
385 assert!(profile.is_tool_enabled("ctx_read"));
386 assert!(profile.is_tool_enabled("ctx_anything"));
387 assert!(profile.is_tool_enabled("nonexistent_tool"));
388 }
389
390 #[test]
391 fn minimal_filters_correctly() {
392 let profile = ToolProfile::Minimal;
393 assert!(profile.is_tool_enabled("ctx_read"));
394 assert!(profile.is_tool_enabled("ctx_shell"));
395 assert!(profile.is_tool_enabled("ctx_search"));
396 assert!(profile.is_tool_enabled("ctx_glob"));
397 assert!(profile.is_tool_enabled("ctx_tree"));
398 assert!(!profile.is_tool_enabled("ctx_callgraph"));
401 }
402
403 #[test]
404 fn standard_filters_correctly() {
405 let profile = ToolProfile::Standard;
406 assert!(profile.is_tool_enabled("ctx_read"));
407 assert!(profile.is_tool_enabled("ctx_compose"));
408 assert!(profile.is_tool_enabled("ctx_glob"));
409 assert!(profile.is_tool_enabled("ctx_callgraph"));
410 assert!(profile.is_tool_enabled("ctx_graph"));
411 assert!(profile.is_tool_enabled("ctx_session"));
412 assert!(profile.is_tool_enabled("ctx_delta"));
413 assert!(profile.is_tool_enabled("ctx_expand"));
414 assert!(profile.is_tool_enabled("ctx_execute"));
415 assert!(profile.is_tool_enabled("ctx_url_read"));
419 assert!(profile.is_tool_enabled("ctx_patch"));
421 assert!(!profile.is_tool_enabled("ctx_edit"));
422 }
423
424 #[test]
425 fn custom_profile_uses_provided_list() {
426 let profile = ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()]);
427 assert!(profile.is_tool_enabled("ctx_read"));
428 assert!(profile.is_tool_enabled("ctx_shell"));
429 assert!(!profile.is_tool_enabled("ctx_search"));
430 }
431
432 #[test]
433 fn profile_display_counts_match_tool_arrays() {
434 let profiles = list_profiles();
438 assert_eq!(
439 profiles[0].tool_count.parse::<usize>().unwrap(),
440 MINIMAL_TOOLS.len(),
441 "minimal count must match MINIMAL_TOOLS length",
442 );
443 assert_eq!(
444 profiles[1].tool_count.parse::<usize>().unwrap(),
445 STANDARD_TOOLS.len(),
446 "standard count must match STANDARD_TOOLS length",
447 );
448 assert_eq!(profiles[2].tool_count, "all");
449 }
450
451 #[test]
452 fn custom_empty_enables_nothing() {
453 let profile = ToolProfile::Custom(vec![]);
454 assert!(!profile.is_tool_enabled("ctx_read"));
455 }
456
457 #[test]
458 fn display_matches_as_str() {
459 assert_eq!(format!("{}", ToolProfile::Minimal), "minimal");
460 assert_eq!(format!("{}", ToolProfile::Standard), "standard");
461 assert_eq!(format!("{}", ToolProfile::Power), "power");
462 assert_eq!(
463 format!("{}", ToolProfile::Custom(vec!["ctx_read".into()])),
464 "custom"
465 );
466 }
467
468 #[test]
469 fn tool_count_matches_list_length() {
470 assert_eq!(ToolProfile::Minimal.tool_count(), MINIMAL_TOOLS.len());
471 assert_eq!(ToolProfile::Standard.tool_count(), STANDARD_TOOLS.len());
472 assert_eq!(ToolProfile::Power.tool_count(), 0);
473 assert_eq!(ToolProfile::Auto.tool_count(), MINIMAL_TOOLS.len());
474 }
475
476 #[test]
477 fn from_config_defaults_to_power_for_backward_compat() {
478 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
479 return;
480 }
481 let cfg = crate::core::config::Config {
482 tool_profile: None,
483 tools_enabled: vec![],
484 ..Default::default()
485 };
486 assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Power);
487 }
488
489 #[test]
490 fn from_config_respects_tool_profile_field() {
491 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
492 return;
493 }
494 let cfg = crate::core::config::Config {
495 tool_profile: Some("minimal".to_string()),
496 tools_enabled: vec![],
497 ..Default::default()
498 };
499 assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Minimal);
500 }
501
502 #[test]
503 fn from_config_tools_enabled_creates_custom() {
504 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
505 return;
506 }
507 let cfg = crate::core::config::Config {
508 tool_profile: None,
509 tools_enabled: vec!["ctx_read".to_string(), "ctx_shell".to_string()],
510 ..Default::default()
511 };
512 let profile = ToolProfile::from_config(&cfg);
513 assert_eq!(
514 profile,
515 ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()])
516 );
517 }
518
519 #[test]
520 fn tool_profile_takes_precedence_over_tools_enabled() {
521 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
522 return;
523 }
524 let cfg = crate::core::config::Config {
525 tool_profile: Some("standard".to_string()),
526 tools_enabled: vec!["ctx_read".to_string()],
527 ..Default::default()
528 };
529 assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Standard);
530 }
531
532 #[test]
533 fn empty_tool_profile_is_unpinned_so_tools_enabled_applies() {
534 assert!(is_unpinned_alias(""));
539 assert!(is_unpinned_alias(" "));
540
541 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
542 return;
543 }
544 let cfg = crate::core::config::Config {
545 tool_profile: Some(String::new()),
546 tools_enabled: vec!["ctx_read".to_string()],
547 ..Default::default()
548 };
549 assert_eq!(
550 ToolProfile::from_config(&cfg),
551 ToolProfile::Custom(vec!["ctx_read".to_string()]),
552 "empty tool_profile must unpin so tools_enabled takes effect"
553 );
554 }
555
556 #[test]
557 fn all_profile_names_are_parseable() {
558 for name in PROFILE_NAMES {
559 assert!(
560 ToolProfile::parse(name).is_some(),
561 "profile name '{name}' should be parseable"
562 );
563 }
564 }
565
566 #[test]
567 fn list_profiles_returns_four_entries() {
568 let profiles = list_profiles();
569 assert_eq!(profiles.len(), 4);
570 }
571
572 #[test]
573 fn resolve_auto_short_session_returns_minimal() {
574 assert_eq!(
575 ToolProfile::resolve_auto(0, false, 500),
576 ToolProfile::Minimal
577 );
578 assert_eq!(
579 ToolProfile::resolve_auto(1, false, 1500),
580 ToolProfile::Minimal
581 );
582 }
583
584 #[test]
585 fn resolve_auto_ctx_tools_used_returns_standard() {
586 assert_eq!(
587 ToolProfile::resolve_auto(1, true, 500),
588 ToolProfile::Standard
589 );
590 assert_eq!(ToolProfile::resolve_auto(0, true, 0), ToolProfile::Standard);
591 }
592
593 #[test]
594 fn resolve_auto_long_session_returns_power() {
595 assert_eq!(
596 ToolProfile::resolve_auto(10, false, 500),
597 ToolProfile::Power
598 );
599 assert_eq!(
600 ToolProfile::resolve_auto(20, false, 3000),
601 ToolProfile::Power
602 );
603 }
604
605 #[test]
606 fn resolve_auto_medium_session_returns_standard() {
607 assert_eq!(
608 ToolProfile::resolve_auto(5, false, 3000),
609 ToolProfile::Standard
610 );
611 }
612
613 #[test]
614 fn auto_profile_display() {
615 assert_eq!(ToolProfile::Auto.as_str(), "auto");
616 assert_eq!(format!("{}", ToolProfile::Auto), "auto");
617 }
618
619 #[test]
620 fn standard_includes_all_core_tools() {
621 let profile = ToolProfile::Standard;
622 assert!(
623 profile.is_tool_enabled("ctx_graph"),
624 "ctx_graph must be in standard"
625 );
626 assert!(
627 profile.is_tool_enabled("ctx_delta"),
628 "ctx_delta must be in standard"
629 );
630 assert!(
631 profile.is_tool_enabled("ctx_expand"),
632 "ctx_expand must be in standard"
633 );
634 assert!(
635 profile.is_tool_enabled("ctx_execute"),
636 "ctx_execute must be in standard (sandboxed code execution)"
637 );
638 assert!(
641 !profile.is_tool_enabled("ctx_edit"),
642 "ctx_edit must NOT be in standard (ctx_patch is the standard editor)"
643 );
644 assert!(
645 profile.is_tool_enabled("ctx_patch"),
646 "ctx_patch must be in standard (#1008 anchored editing)"
647 );
648 }
649
650 #[test]
651 fn standard_includes_url_read() {
652 let profile = ToolProfile::Standard;
653 assert!(
654 profile.is_tool_enabled("ctx_url_read"),
655 "ctx_url_read must be in standard (web/research context)"
656 );
657 }
658
659 #[test]
660 fn clear_profile_removes_key_and_is_idempotent() {
661 let iso = crate::core::data_dir::isolated_data_dir();
662 set_profile_in_config("power").unwrap();
663 let config_path = iso.path().join("config.toml");
664 assert!(
665 std::fs::read_to_string(&config_path)
666 .unwrap()
667 .contains("tool_profile"),
668 "set_profile_in_config must write the key"
669 );
670
671 clear_profile_in_config().unwrap();
672 assert!(
673 !std::fs::read_to_string(&config_path)
674 .unwrap()
675 .contains("tool_profile"),
676 "clear_profile_in_config must remove the key (lean default, #575)"
677 );
678
679 clear_profile_in_config().unwrap();
681 }
682
683 #[test]
684 fn clear_profile_on_missing_config_is_ok() {
685 let _iso = crate::core::data_dir::isolated_data_dir();
686 clear_profile_in_config().unwrap();
687 }
688
689 #[test]
690 fn without_tool_removes_from_power() {
691 let filtered = ToolProfile::Power.without_tool("ctx_patch");
692 assert!(!filtered.is_tool_enabled("ctx_patch"));
693 assert!(filtered.is_tool_enabled("ctx_read"));
694 assert!(filtered.is_tool_enabled("ctx_search"));
695 }
696
697 #[test]
698 fn without_tool_removes_from_standard() {
699 let filtered = ToolProfile::Standard.without_tool("ctx_patch");
700 assert!(!filtered.is_tool_enabled("ctx_patch"));
701 assert!(filtered.is_tool_enabled("ctx_read"));
702 assert!(filtered.is_tool_enabled("ctx_compose"));
703 }
704
705 #[test]
706 fn without_tool_noop_for_already_missing() {
707 let filtered = ToolProfile::Minimal.without_tool("ctx_patch");
708 assert!(!filtered.is_tool_enabled("ctx_patch"));
709 assert!(filtered.is_tool_enabled("ctx_read"));
710 }
711}