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