1use lean_ctx::core::profiles;
3use lean_ctx::core::tool_profiles::{self, ToolProfile};
4
5pub fn cmd_profile(args: &[String]) {
6 let action = args.first().map_or("list", String::as_str);
7
8 match action {
9 "tools" => cmd_tool_profile(&args[1..]),
10 "minimal" | "min" | "standard" | "std" | "power" | "full" | "all" | "lean" | "lazy"
11 | "reset" => {
12 cmd_tool_profile_switch(action);
13 println!(" \x1b[2mTip: the canonical command is `lean-ctx tools {action}`.\x1b[0m");
14 }
15
16 "list" | "ls" => cmd_profile_list(),
17 "show" => {
18 let name = args
19 .get(1)
20 .map_or_else(profiles::active_profile_name, Clone::clone);
21 cmd_profile_show(&name);
22 }
23 "active" | "current" => cmd_profile_active(),
24 "diff" => {
25 if args.len() < 3 {
26 eprintln!("Usage: lean-ctx profile diff <profile-a> <profile-b>");
27 std::process::exit(1);
28 }
29 cmd_profile_diff(&args[1], &args[2]);
30 }
31 "create" => {
32 if args.len() < 2 {
33 eprintln!("Usage: lean-ctx profile create <name> [--from <base>] [--global]");
34 std::process::exit(1);
35 }
36 let name = &args[1];
37 let base = args
38 .iter()
39 .position(|a| a == "--from")
40 .and_then(|i| args.get(i + 1))
41 .map(String::as_str);
42 let global = args.iter().any(|a| a == "--global");
43 cmd_profile_create(name, base, global);
44 }
45 "set" => {
46 if args.len() < 2 {
47 eprintln!("Usage: lean-ctx profile set <name>");
48 eprintln!(" Sets LEAN_CTX_PROFILE for the current shell.");
49 std::process::exit(1);
50 }
51 cmd_profile_set(&args[1]);
52 }
53 "suggest" => cmd_profile_suggest(&args[1..]),
54 _ => {
55 if profiles::load_profile(action).is_some() {
56 cmd_profile_show(action);
57 } else {
58 print_profile_help();
59 std::process::exit(1);
60 }
61 }
62 }
63}
64
65fn cmd_profile_suggest(args: &[String]) {
70 use lean_ctx::core::profile_suggest;
71
72 let root = super::common::detect_project_root(args);
73 let signals = profile_suggest::analyze(&root);
74 let suggestion = profile_suggest::suggest(&signals);
75
76 if args.iter().any(|a| a == "--json") {
77 let payload = serde_json::json!({ "signals": signals, "suggestion": suggestion });
78 println!(
79 "{}",
80 serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_string())
81 );
82 return;
83 }
84
85 render_profile_suggestion(&signals, &suggestion);
86}
87
88fn render_profile_suggestion(
89 signals: &lean_ctx::core::profile_suggest::RepoSignals,
90 suggestion: &lean_ctx::core::profile_suggest::Suggestion,
91) {
92 const BOLD: &str = "\x1b[1m";
93 const DIM: &str = "\x1b[2m";
94 const CYAN: &str = "\x1b[36m";
95 const RST: &str = "\x1b[0m";
96
97 println!(
98 "{BOLD}Profile suggestion{RST} {DIM}for {}{RST}",
99 signals.root
100 );
101 println!();
102
103 let langs = if signals.languages.is_empty() {
104 "(none detected)".to_string()
105 } else {
106 signals
107 .languages
108 .iter()
109 .take(6)
110 .map(|l| format!("{} {}", l.language, l.files))
111 .collect::<Vec<_>>()
112 .join(", ")
113 };
114 println!(" {BOLD}Detected{RST}");
115 println!(" languages {langs}");
116 println!(" files {} source files", signals.source_files);
117 println!(
118 " monorepo {}",
119 if signals.monorepo {
120 let m = if signals.workspace_markers.is_empty() {
121 "nested project roots".to_string()
122 } else {
123 signals.workspace_markers.join(", ")
124 };
125 format!("yes ({m})")
126 } else {
127 "no".to_string()
128 }
129 );
130 if !signals.build_markers.is_empty() {
131 println!(" build {}", signals.build_markers.join(", "));
132 }
133 println!(" CI {}", if signals.ci { "yes" } else { "no" });
134 let providers = if signals.providers.is_empty() {
135 "(none detected)".to_string()
136 } else {
137 signals.providers.join(", ")
138 };
139 println!(" providers {providers}");
140 println!();
141
142 println!(
143 " {BOLD}Suggested profile:{RST} {CYAN}{}{RST}",
144 suggestion.profile
145 );
146 for reason in &suggestion.rationale {
147 println!(" • {reason}");
148 }
149 println!();
150
151 println!(" {BOLD}Recommended settings{RST}");
152 println!(" profile {}", suggestion.profile);
153 if let Some(hm) = &suggestion.settings.history_mode {
154 println!(" proxy.history_mode {hm}");
155 }
156 println!(
157 " output_density {}",
158 suggestion.settings.output_density
159 );
160 match &suggestion.settings.effort {
161 Some(e) => println!(" proxy.effort {e}"),
162 None => println!(" proxy.effort {DIM}off (opt-in; raise per task){RST}"),
163 }
164 println!();
165
166 println!(" {BOLD}Apply{RST} {DIM}(you choose — nothing is changed automatically){RST}");
167 println!(
168 " {DIM}# session-only:{RST} export LEAN_CTX_PROFILE={}",
169 suggestion.profile
170 );
171 println!(
172 " {DIM}# persistent: {RST} lean-ctx config set profile {}",
173 suggestion.profile
174 );
175 if let Some(hm) = &suggestion.settings.history_mode {
176 println!(" lean-ctx config set proxy.history_mode {hm}");
177 }
178 println!(
179 " lean-ctx config set output_density {}",
180 suggestion.settings.output_density
181 );
182 println!();
183
184 if !suggestion.alternatives.is_empty() {
185 println!(" {BOLD}Task profiles you can switch to{RST}");
186 for alt in &suggestion.alternatives {
187 println!(" {:<9} {DIM}— {}{RST}", alt.profile, alt.when);
188 }
189 }
190}
191
192fn cmd_profile_list() {
193 let list = profiles::list_profiles();
194 let active = profiles::active_profile_name();
195
196 let header = format!(" {:<16} {:<10} {}", "Name", "Source", "Description");
197 let sep = format!(" {}", "\u{2500}".repeat(60));
198 println!("Available profiles:\n");
199 println!("{header}");
200 println!("{sep}");
201
202 for p in &list {
203 let marker = if p.name == active { " *" } else { " " };
204 println!("{marker}{:<16} {:<10} {}", p.name, p.source, p.description);
205 }
206
207 println!("\n Active: {active}");
208 println!(" Set via: LEAN_CTX_PROFILE=<name> or lean-ctx profile set <name>");
209}
210
211fn cmd_profile_show(name: &str) {
212 if let Some(profile) = profiles::load_profile(name) {
213 println!("Profile: {name}\n");
214 println!("{}", profiles::format_as_toml(&profile));
215 } else {
216 eprintln!("Profile '{name}' not found.");
217 eprintln!("Run 'lean-ctx profile list' to see available profiles.");
218 std::process::exit(1);
219 }
220}
221
222fn cmd_profile_active() {
223 let name = profiles::active_profile_name();
224 let profile = profiles::active_profile();
225 println!("Active profile: {name}\n");
226 println!("{}", profiles::format_as_toml(&profile));
227}
228
229fn cmd_profile_diff(name_a: &str, name_b: &str) {
230 let Some(a) = profiles::load_profile(name_a) else {
231 eprintln!("Profile '{name_a}' not found.");
232 std::process::exit(1);
233 };
234 let Some(b) = profiles::load_profile(name_b) else {
235 eprintln!("Profile '{name_b}' not found.");
236 std::process::exit(1);
237 };
238
239 println!("Profile diff: {name_a} vs {name_b}\n");
240
241 let diffs = collect_diffs(&a, &b);
242 if diffs.is_empty() {
243 println!(" No differences.");
244 } else {
245 println!(" {:<32} {:<20} {:<20}", "Field", name_a, name_b);
246 println!(" {}", "\u{2500}".repeat(72));
247 for (field, val_a, val_b) in &diffs {
248 println!(" {field:<32} {val_a:<20} {val_b:<20}");
249 }
250 }
251}
252
253fn collect_diffs(a: &profiles::Profile, b: &profiles::Profile) -> Vec<(String, String, String)> {
254 let mut diffs = Vec::new();
255
256 macro_rules! cmp {
257 ($section:ident . $field:ident) => {
258 let va = format!("{:?}", a.$section.$field);
259 let vb = format!("{:?}", b.$section.$field);
260 if va != vb {
261 diffs.push((
262 format!("{}.{}", stringify!($section), stringify!($field)),
263 va,
264 vb,
265 ));
266 }
267 };
268 }
269
270 cmp!(read.default_mode);
271 cmp!(compression.crp_mode);
272 cmp!(autonomy.enabled);
273 cmp!(autonomy.checkpoint_interval);
274
275 diffs
276}
277
278fn cmd_profile_create(name: &str, base: Option<&str>, global: bool) {
279 let base_profile = base
280 .and_then(profiles::load_profile)
281 .unwrap_or_else(profiles::active_profile);
282
283 let mut new_profile = base_profile;
284 new_profile.profile.name = name.to_string();
285 new_profile.profile.inherits = base.map(String::from);
286 new_profile.profile.description = String::new();
287
288 let dir = if global {
289 let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
290 eprintln!("Cannot determine global data directory.");
291 std::process::exit(1);
292 };
293 data_dir.join("profiles")
294 } else {
295 std::env::current_dir()
296 .unwrap_or_default()
297 .join(".lean-ctx")
298 .join("profiles")
299 };
300
301 if let Err(e) = std::fs::create_dir_all(&dir) {
302 eprintln!("Cannot create directory {}: {e}", dir.display());
303 std::process::exit(1);
304 }
305
306 let path = dir.join(format!("{name}.toml"));
307 let toml_content = profiles::format_as_toml(&new_profile);
308
309 if let Err(e) = std::fs::write(&path, &toml_content) {
310 eprintln!("Error writing {}: {e}", path.display());
311 std::process::exit(1);
312 }
313
314 println!("Created profile '{name}' at {}", path.display());
315 if let Some(b) = base {
316 println!(" Based on: {b}");
317 }
318 println!("\nEdit the file to customize, then activate with:");
319 println!(" LEAN_CTX_PROFILE={name}");
320}
321
322fn cmd_profile_set(name: &str) {
323 if profiles::load_profile(name).is_none() {
324 eprintln!("Profile '{name}' not found. Available profiles:");
325 for p in profiles::list_profiles() {
326 eprintln!(" {}", p.name);
327 }
328 std::process::exit(1);
329 }
330
331 println!("To activate profile '{name}', run:\n");
332 println!(" export LEAN_CTX_PROFILE={name}\n");
333 println!(
334 "Or add it to your shell config ({}).",
335 lean_ctx::shell_hook::shell_rc_file()
336 );
337}
338
339fn cmd_tool_profile(args: &[String]) {
342 let action = args.first().map_or("show", String::as_str);
343
344 match action {
345 "list" | "ls" => cmd_tool_profile_list(),
346 "show" | "current" => cmd_tool_profile_show(),
347 "minimal" | "min" | "standard" | "std" | "power" | "full" | "all" | "lean" | "lazy"
348 | "reset" => {
349 cmd_tool_profile_switch(action);
350 }
351 _ => {
352 if ToolProfile::parse(action).is_some() {
353 cmd_tool_profile_switch(action);
354 } else {
355 eprintln!("Unknown tool profile '{action}'.");
356 eprintln!("Available: lean (default), minimal, standard, power");
357 std::process::exit(1);
358 }
359 }
360 }
361}
362
363fn cmd_tool_profile_show() {
364 let cfg = lean_ctx::core::config::Config::load();
365 let profile = cfg.tool_profile_effective();
366 let registry_count = lean_ctx_server::server::registry::tool_count();
367 let pinned = cfg.tool_profile.is_some()
368 || std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok()
369 || !cfg.tools_enabled.is_empty();
370
371 if !pinned {
372 let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
373 println!("Tool Profile: lean (default)");
374 println!(" Tools advertised: {lazy_count} (lazy core)");
375 println!(" All {registry_count} registered tools stay callable via ctx_call.");
376 println!("\n Advertised tools:");
377 for name in lean_ctx::tool_defs::core_tool_names() {
378 println!(" {name}");
379 }
380 println!("\n Switch with: lean-ctx tools <minimal|standard|power>");
381 return;
382 }
383
384 let count_str = match &profile {
385 ToolProfile::Power => format!("{registry_count}"),
386 ToolProfile::Custom(list) => format!("{}", list.len()),
387 other => format!("{}", other.tool_count()),
388 };
389
390 println!("Tool Profile: {}", profile.as_str());
391 println!(" Tools exposed: {count_str}");
392 println!(" Description: {}", profile.description());
393
394 if let Some(ref cfg_val) = cfg.tool_profile {
395 println!(" Source: config.toml (tool_profile = \"{cfg_val}\")");
396 }
397 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
398 println!(" Source: LEAN_CTX_TOOL_PROFILE env var (overrides config)");
399 }
400
401 if !matches!(profile, ToolProfile::Power) {
402 println!("\n Enabled tools:");
403 let names = profile.tool_names();
404 for name in &names {
405 println!(" {name}");
406 }
407 }
408
409 println!("\n Switch with: lean-ctx tools <lean|minimal|standard|power>");
410 if matches!(profile, ToolProfile::Power) {
411 println!(" Tip: `lean-ctx tools lean` advertises only the lazy core (lowest overhead).");
412 }
413}
414
415fn cmd_tool_profile_list() {
416 let cfg = lean_ctx::core::config::Config::load();
417 let active = cfg.tool_profile_effective();
418 let registry_count = lean_ctx_server::server::registry::tool_count();
419 let pinned = cfg
422 .tool_profile
423 .as_deref()
424 .is_some_and(|p| !tool_profiles::is_unpinned_alias(p))
425 || std::env::var("LEAN_CTX_TOOL_PROFILE")
426 .is_ok_and(|v| !v.trim().is_empty() && !tool_profiles::is_unpinned_alias(v.trim()))
427 || !cfg.tools_enabled.is_empty();
428 let active_name = if pinned { active.as_str() } else { "lean" };
429 let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
430
431 println!("Tool Profiles:\n");
432 println!(" {:<12} {:<8} Description", "Name", "Tools");
433 println!(" {}", "\u{2500}".repeat(60));
434
435 let lean_marker = if active_name == "lean" { "* " } else { " " };
436 println!(
437 "{lean_marker}{:<12} {lazy_count:<8} Lazy core advertised, all tools via ctx_call (default)",
438 "lean"
439 );
440 for info in tool_profiles::list_profiles() {
441 let marker = if info.name == active_name { "* " } else { " " };
442 let count = if info.name == "power" {
443 format!("{registry_count}")
444 } else {
445 info.tool_count.to_string()
446 };
447 println!(
448 "{marker}{:<12} {:<8} {}",
449 info.name, count, info.description
450 );
451 }
452
453 println!("\n Active: {active_name}");
454 println!(" Switch: lean-ctx profile <name>");
455 println!(" Env: LEAN_CTX_TOOL_PROFILE=<name>");
456}
457
458fn cmd_tool_profile_switch(name: &str) {
459 if tool_profiles::is_unpinned_alias(name) {
463 if let Err(e) = tool_profiles::clear_profile_in_config() {
464 eprintln!("Error saving profile: {e}");
465 std::process::exit(1);
466 }
467 let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
468 println!("Tool profile set to: lean (default)");
469 println!(" Tools advertised: {lazy_count} (lazy core)");
470 println!(" All other tools stay callable via ctx_call.");
471 println!("\n Changes take effect on the next tool call (auto-detected).");
472 return;
473 }
474
475 let Some(profile) = ToolProfile::parse(name) else {
476 eprintln!("Unknown tool profile '{name}'.");
477 eprintln!("Available: lean (default), minimal, standard, power");
478 std::process::exit(1);
479 };
480
481 let canonical = profile.as_str();
482
483 if let Err(e) = tool_profiles::set_profile_in_config(canonical) {
484 eprintln!("Error saving profile: {e}");
485 std::process::exit(1);
486 }
487
488 let registry_count = lean_ctx_server::server::registry::tool_count();
489 let count_str = match &profile {
490 ToolProfile::Power => format!("{registry_count}"),
491 other => format!("{}", other.tool_count()),
492 };
493
494 println!("Tool profile set to: {canonical}");
495 println!(" Tools exposed: {count_str}");
496 println!(" Description: {}", profile.description());
497
498 if !matches!(profile, ToolProfile::Power) {
499 println!("\n Enabled tools:");
500 for name in profile.tool_names() {
501 println!(" {name}");
502 }
503 }
504
505 println!("\n Changes take effect on the next tool call (auto-detected).");
506}
507
508fn print_profile_help() {
509 eprintln!(
510 "lean-ctx has two kinds of profiles — here is which command to use:
511
512TOOL PROFILES — how many MCP tools your agent sees:
513 lean-ctx tools Show current tool profile
514 lean-ctx tools lean Lazy core advertised, all via ctx_call (default)
515 lean-ctx tools minimal 5 essential tools
516 lean-ctx tools standard 16 balanced tools
517 lean-ctx tools power All tools (highest context overhead)
518 lean-ctx tools list List tool profiles with counts
519
520CONTEXT PROFILES — how lean-ctx compresses and reads (this command):
521 lean-ctx profile list List available context profiles
522 lean-ctx profile show [name] Show context profile details (default: active)
523 lean-ctx profile active Show the currently active context profile
524 lean-ctx profile diff <a> <b> Compare two context profiles side by side
525 lean-ctx profile create <name> [--from <base>] [--global]
526 lean-ctx profile set <name> Show how to activate a context profile
527 lean-ctx profile suggest Recommend a profile from repo signals (read-only) [--json]"
528 );
529}