1use std::fmt;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum ToolProfile {
17 Minimal,
18 Standard,
19 Power,
20 Custom(Vec<String>),
21}
22
23impl ToolProfile {
24 pub fn parse(s: &str) -> Option<Self> {
25 match s.to_lowercase().as_str() {
26 "minimal" | "min" => Some(Self::Minimal),
27 "standard" | "std" | "default" => Some(Self::Standard),
28 "power" | "full" | "all" => Some(Self::Power),
29 _ => None,
30 }
31 }
32
33 pub fn as_str(&self) -> &str {
34 match self {
35 Self::Minimal => "minimal",
36 Self::Standard => "standard",
37 Self::Power => "power",
38 Self::Custom(_) => "custom",
39 }
40 }
41
42 pub fn description(&self) -> &str {
43 match self {
44 Self::Minimal => "5 surgical tools — each irreplaceable (recommended)",
45 Self::Standard => "15 balanced tools (adds compose, explore, callgraph, execute, more)",
46 Self::Power => "All tools exposed",
47 Self::Custom(v) => {
48 if v.is_empty() {
49 "Custom tool list (empty)"
50 } else {
51 "Custom tool list"
52 }
53 }
54 }
55 }
56
57 pub fn is_tool_enabled(&self, tool_name: &str) -> bool {
58 match self {
59 Self::Power => true,
60 Self::Minimal => MINIMAL_TOOLS.contains(&tool_name),
61 Self::Standard => STANDARD_TOOLS.contains(&tool_name),
62 Self::Custom(list) => list.iter().any(|t| t == tool_name),
63 }
64 }
65
66 pub fn tool_count(&self) -> usize {
67 match self {
68 Self::Minimal => MINIMAL_TOOLS.len(),
69 Self::Standard => STANDARD_TOOLS.len(),
70 Self::Power => 0, Self::Custom(list) => list.len(),
72 }
73 }
74
75 pub fn tool_names(&self) -> Vec<&str> {
76 match self {
77 Self::Minimal => MINIMAL_TOOLS.to_vec(),
78 Self::Standard => STANDARD_TOOLS.to_vec(),
79 Self::Power | Self::Custom(_) => vec![],
80 }
81 }
82
83 pub fn from_config(cfg: &super::config::Config) -> Self {
89 if let Ok(val) = std::env::var("LEAN_CTX_TOOL_PROFILE") {
90 let trimmed = val.trim();
91 if let Some(profile) = Self::parse(trimmed) {
92 return profile;
93 }
94 if !trimmed.is_empty() && !is_unpinned_alias(trimmed) {
96 tracing::warn!("Unknown LEAN_CTX_TOOL_PROFILE value '{trimmed}', using config");
97 }
98 }
99
100 if let Some(ref profile_name) = cfg.tool_profile {
101 if let Some(profile) = Self::parse(profile_name) {
102 return profile;
103 }
104 if !is_unpinned_alias(profile_name) {
110 tracing::warn!("Unknown tool_profile '{profile_name}' in config, using default");
111 }
112 }
113
114 if !cfg.tools_enabled.is_empty() {
115 return Self::Custom(cfg.tools_enabled.clone());
116 }
117
118 Self::Power
119 }
120}
121
122impl fmt::Display for ToolProfile {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 write!(f, "{}", self.as_str())
125 }
126}
127
128pub fn is_unpinned_alias(name: &str) -> bool {
136 matches!(
137 name.trim().to_ascii_lowercase().as_str(),
138 "" | "lean" | "lazy" | "reset"
139 )
140}
141
142const MINIMAL_TOOLS: &[&str] = &[
148 "ctx_read",
149 "ctx_shell",
150 "ctx_search",
151 "ctx_glob",
152 "ctx_tree",
153];
154
155const STANDARD_TOOLS: &[&str] = &[
161 "ctx_read",
162 "ctx_shell",
163 "ctx_search",
164 "ctx_glob",
165 "ctx_tree",
166 "ctx_compose",
167 "ctx_explore",
168 "ctx_knowledge",
169 "ctx_callgraph",
170 "ctx_graph",
171 "ctx_delta",
172 "ctx_execute",
173 "ctx_expand",
174 "ctx_overview",
175 "ctx_url_read",
176];
177
178pub const PROFILE_NAMES: &[&str] = &["minimal", "standard", "power"];
180
181pub struct ProfileInfo {
182 pub name: &'static str,
183 pub tool_count: &'static str,
184 pub description: &'static str,
185}
186
187pub fn list_profiles() -> Vec<ProfileInfo> {
188 vec![
189 ProfileInfo {
190 name: "minimal",
191 tool_count: "5",
192 description: "Surgical core — each tool irreplaceable (recommended)",
193 },
194 ProfileInfo {
195 name: "standard",
196 tool_count: "15",
197 description: "Balanced set — adds compose, explore, callgraph, execute, delta, more",
198 },
199 ProfileInfo {
200 name: "power",
201 tool_count: "all",
202 description: "Every tool exposed (backward compatible)",
203 },
204 ]
205}
206
207pub fn set_profile_in_config(profile_name: &str) -> Result<(), String> {
210 let config_path = crate::core::config::Config::path()
214 .ok_or_else(|| "Cannot determine config dir".to_string())?;
215
216 let mut doc = crate::config_io::load_toml_document(&config_path);
217 doc["tool_profile"] = toml_edit::value(profile_name);
218 crate::config_io::write_toml_document(&config_path, &doc)?;
219 Ok(())
220}
221
222pub fn clear_profile_in_config() -> Result<(), String> {
227 let config_path = crate::core::config::Config::path()
228 .ok_or_else(|| "Cannot determine config dir".to_string())?;
229 if !config_path.exists() {
230 return Ok(());
231 }
232
233 let mut doc = crate::config_io::load_toml_document(&config_path);
234 if doc.remove("tool_profile").is_none() {
235 return Ok(());
236 }
237 crate::config_io::write_toml_document(&config_path, &doc)?;
238 Ok(())
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 #[test]
246 fn parse_known_profiles() {
247 assert_eq!(ToolProfile::parse("minimal"), Some(ToolProfile::Minimal));
248 assert_eq!(ToolProfile::parse("min"), Some(ToolProfile::Minimal));
249 assert_eq!(ToolProfile::parse("standard"), Some(ToolProfile::Standard));
250 assert_eq!(ToolProfile::parse("std"), Some(ToolProfile::Standard));
251 assert_eq!(ToolProfile::parse("default"), Some(ToolProfile::Standard));
252 assert_eq!(ToolProfile::parse("power"), Some(ToolProfile::Power));
253 assert_eq!(ToolProfile::parse("full"), Some(ToolProfile::Power));
254 assert_eq!(ToolProfile::parse("all"), Some(ToolProfile::Power));
255 }
256
257 #[test]
258 fn parse_case_insensitive() {
259 assert_eq!(ToolProfile::parse("MINIMAL"), Some(ToolProfile::Minimal));
260 assert_eq!(ToolProfile::parse("Standard"), Some(ToolProfile::Standard));
261 assert_eq!(ToolProfile::parse("POWER"), Some(ToolProfile::Power));
262 }
263
264 #[test]
265 fn parse_unknown_returns_none() {
266 assert_eq!(ToolProfile::parse("unknown"), None);
267 assert_eq!(ToolProfile::parse(""), None);
268 }
269
270 #[test]
271 fn minimal_profile_schema_budget() {
272 const MINIMAL_SCHEMA_BUDGET_TOKENS: usize = 2800;
276 let defs = crate::server::registry::build_registry().tool_defs();
277 let total: usize = defs
278 .iter()
279 .filter(|t| MINIMAL_TOOLS.contains(&t.name.as_ref()))
280 .map(crate::core::context_overhead::tool_tokens)
281 .sum();
282 assert!(total > 0, "minimal tools must exist in the registry");
283 assert!(
284 total <= MINIMAL_SCHEMA_BUDGET_TOKENS,
285 "minimal-profile tool schemas = {total} tok, budget {MINIMAL_SCHEMA_BUDGET_TOKENS}"
286 );
287 }
288
289 #[test]
290 fn minimal_is_subset_of_standard() {
291 for tool in MINIMAL_TOOLS {
292 assert!(
293 STANDARD_TOOLS.contains(tool),
294 "minimal tool {tool} missing from standard"
295 );
296 }
297 }
298
299 #[test]
300 fn power_enables_everything() {
301 let profile = ToolProfile::Power;
302 assert!(profile.is_tool_enabled("ctx_read"));
303 assert!(profile.is_tool_enabled("ctx_anything"));
304 assert!(profile.is_tool_enabled("nonexistent_tool"));
305 }
306
307 #[test]
308 fn minimal_filters_correctly() {
309 let profile = ToolProfile::Minimal;
310 assert!(profile.is_tool_enabled("ctx_read"));
311 assert!(profile.is_tool_enabled("ctx_shell"));
312 assert!(profile.is_tool_enabled("ctx_search"));
313 assert!(profile.is_tool_enabled("ctx_glob"));
314 assert!(profile.is_tool_enabled("ctx_tree"));
315 assert!(!profile.is_tool_enabled("ctx_symbol"));
318 assert!(!profile.is_tool_enabled("ctx_semantic_search"));
319 assert!(!profile.is_tool_enabled("ctx_callgraph"));
320 assert!(!profile.is_tool_enabled("ctx_benchmark"));
321 }
322
323 #[test]
324 fn standard_filters_correctly() {
325 let profile = ToolProfile::Standard;
326 assert!(profile.is_tool_enabled("ctx_read"));
327 assert!(profile.is_tool_enabled("ctx_compose"));
328 assert!(profile.is_tool_enabled("ctx_explore"));
329 assert!(profile.is_tool_enabled("ctx_glob"));
330 assert!(profile.is_tool_enabled("ctx_callgraph"));
331 assert!(profile.is_tool_enabled("ctx_graph"));
332 assert!(profile.is_tool_enabled("ctx_delta"));
333 assert!(profile.is_tool_enabled("ctx_expand"));
334 assert!(profile.is_tool_enabled("ctx_execute"));
335 assert!(profile.is_tool_enabled("ctx_overview"));
336 assert!(!profile.is_tool_enabled("ctx_symbol"));
339 assert!(!profile.is_tool_enabled("ctx_semantic_search"));
340 assert!(!profile.is_tool_enabled("ctx_multi_read"));
341 assert!(profile.is_tool_enabled("ctx_url_read"));
342 assert!(!profile.is_tool_enabled("ctx_benchmark"));
343 assert!(!profile.is_tool_enabled("ctx_analyze"));
344 assert!(!profile.is_tool_enabled("ctx_refactor"));
345 assert!(!profile.is_tool_enabled("ctx_edit"));
346 }
347
348 #[test]
349 fn custom_profile_uses_provided_list() {
350 let profile = ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()]);
351 assert!(profile.is_tool_enabled("ctx_read"));
352 assert!(profile.is_tool_enabled("ctx_shell"));
353 assert!(!profile.is_tool_enabled("ctx_search"));
354 }
355
356 #[test]
357 fn profile_display_counts_match_tool_arrays() {
358 let profiles = list_profiles();
362 assert_eq!(
363 profiles[0].tool_count.parse::<usize>().unwrap(),
364 MINIMAL_TOOLS.len(),
365 "minimal count must match MINIMAL_TOOLS length",
366 );
367 assert_eq!(
368 profiles[1].tool_count.parse::<usize>().unwrap(),
369 STANDARD_TOOLS.len(),
370 "standard count must match STANDARD_TOOLS length",
371 );
372 assert_eq!(profiles[2].tool_count, "all");
373 }
374
375 #[test]
376 fn custom_empty_enables_nothing() {
377 let profile = ToolProfile::Custom(vec![]);
378 assert!(!profile.is_tool_enabled("ctx_read"));
379 }
380
381 #[test]
382 fn display_matches_as_str() {
383 assert_eq!(format!("{}", ToolProfile::Minimal), "minimal");
384 assert_eq!(format!("{}", ToolProfile::Standard), "standard");
385 assert_eq!(format!("{}", ToolProfile::Power), "power");
386 assert_eq!(
387 format!("{}", ToolProfile::Custom(vec!["ctx_read".into()])),
388 "custom"
389 );
390 }
391
392 #[test]
393 fn tool_count_matches_list_length() {
394 assert_eq!(ToolProfile::Minimal.tool_count(), MINIMAL_TOOLS.len());
395 assert_eq!(ToolProfile::Standard.tool_count(), STANDARD_TOOLS.len());
396 assert_eq!(ToolProfile::Power.tool_count(), 0);
397 }
398
399 #[test]
400 fn from_config_defaults_to_power_for_backward_compat() {
401 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
402 return;
403 }
404 let cfg = crate::core::config::Config {
405 tool_profile: None,
406 tools_enabled: vec![],
407 ..Default::default()
408 };
409 assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Power);
410 }
411
412 #[test]
413 fn from_config_respects_tool_profile_field() {
414 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
415 return;
416 }
417 let cfg = crate::core::config::Config {
418 tool_profile: Some("minimal".to_string()),
419 tools_enabled: vec![],
420 ..Default::default()
421 };
422 assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Minimal);
423 }
424
425 #[test]
426 fn from_config_tools_enabled_creates_custom() {
427 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
428 return;
429 }
430 let cfg = crate::core::config::Config {
431 tool_profile: None,
432 tools_enabled: vec!["ctx_read".to_string(), "ctx_shell".to_string()],
433 ..Default::default()
434 };
435 let profile = ToolProfile::from_config(&cfg);
436 assert_eq!(
437 profile,
438 ToolProfile::Custom(vec!["ctx_read".to_string(), "ctx_shell".to_string()])
439 );
440 }
441
442 #[test]
443 fn tool_profile_takes_precedence_over_tools_enabled() {
444 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
445 return;
446 }
447 let cfg = crate::core::config::Config {
448 tool_profile: Some("standard".to_string()),
449 tools_enabled: vec!["ctx_read".to_string()],
450 ..Default::default()
451 };
452 assert_eq!(ToolProfile::from_config(&cfg), ToolProfile::Standard);
453 }
454
455 #[test]
456 fn empty_tool_profile_is_unpinned_so_tools_enabled_applies() {
457 assert!(is_unpinned_alias(""));
462 assert!(is_unpinned_alias(" "));
463
464 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
465 return;
466 }
467 let cfg = crate::core::config::Config {
468 tool_profile: Some(String::new()),
469 tools_enabled: vec!["ctx_read".to_string()],
470 ..Default::default()
471 };
472 assert_eq!(
473 ToolProfile::from_config(&cfg),
474 ToolProfile::Custom(vec!["ctx_read".to_string()]),
475 "empty tool_profile must unpin so tools_enabled takes effect"
476 );
477 }
478
479 #[test]
480 fn all_profile_names_are_parseable() {
481 for name in PROFILE_NAMES {
482 assert!(
483 ToolProfile::parse(name).is_some(),
484 "profile name '{name}' should be parseable"
485 );
486 }
487 }
488
489 #[test]
490 fn list_profiles_returns_three_entries() {
491 let profiles = list_profiles();
492 assert_eq!(profiles.len(), 3);
493 }
494
495 #[test]
496 fn standard_includes_all_core_tools() {
497 let profile = ToolProfile::Standard;
498 assert!(
499 profile.is_tool_enabled("ctx_graph"),
500 "ctx_graph must be in standard"
501 );
502 assert!(
503 profile.is_tool_enabled("ctx_delta"),
504 "ctx_delta must be in standard"
505 );
506 assert!(
507 profile.is_tool_enabled("ctx_expand"),
508 "ctx_expand must be in standard"
509 );
510 assert!(
511 profile.is_tool_enabled("ctx_execute"),
512 "ctx_execute must be in standard (sandboxed code execution)"
513 );
514 assert!(
516 !profile.is_tool_enabled("ctx_edit"),
517 "ctx_edit must NOT be in standard (native Edit preferred)"
518 );
519 }
520
521 #[test]
522 fn standard_includes_url_read() {
523 let profile = ToolProfile::Standard;
524 assert!(
525 profile.is_tool_enabled("ctx_url_read"),
526 "ctx_url_read must be in standard (web/research context)"
527 );
528 }
529
530 #[test]
531 fn clear_profile_removes_key_and_is_idempotent() {
532 let iso = crate::core::data_dir::isolated_data_dir();
533 set_profile_in_config("power").unwrap();
534 let config_path = iso.path().join("config.toml");
535 assert!(
536 std::fs::read_to_string(&config_path)
537 .unwrap()
538 .contains("tool_profile"),
539 "set_profile_in_config must write the key"
540 );
541
542 clear_profile_in_config().unwrap();
543 assert!(
544 !std::fs::read_to_string(&config_path)
545 .unwrap()
546 .contains("tool_profile"),
547 "clear_profile_in_config must remove the key (lean default, #575)"
548 );
549
550 clear_profile_in_config().unwrap();
552 }
553
554 #[test]
555 fn clear_profile_on_missing_config_is_ok() {
556 let _iso = crate::core::data_dir::isolated_data_dir();
557 clear_profile_in_config().unwrap();
558 }
559}