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 file_name = format!("{name}.toml");
289 if !matches!(
290 std::path::Path::new(&file_name)
291 .components()
292 .collect::<Vec<_>>()
293 .as_slice(),
294 [std::path::Component::Normal(_)]
295 ) {
296 eprintln!("Profile name must be a plain name without path separators: {name}");
297 std::process::exit(1);
298 }
299 let toml_content = profiles::format_as_toml(&new_profile);
300
301 let written = if global {
302 let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
303 eprintln!("Cannot determine global data directory.");
304 std::process::exit(1);
305 };
306 let dir = data_dir.join("profiles");
307 if let Err(e) = std::fs::create_dir_all(&dir) {
308 eprintln!("Cannot create directory {}: {e}", dir.display());
309 std::process::exit(1);
310 }
311 let path = dir.join(&file_name);
312 std::fs::write(&path, &toml_content)
313 .map(|()| path.clone())
314 .map_err(|e| format!("Error writing {}: {e}", path.display()))
315 } else {
316 lean_ctx::core::pathjail_write::write_below(
319 &std::env::current_dir().unwrap_or_default(),
320 &std::path::Path::new(".lean-ctx")
321 .join("profiles")
322 .join(&file_name),
323 toml_content.as_bytes(),
324 0o644,
325 )
326 };
327 let path = match written {
328 Ok(path) => path,
329 Err(e) => {
330 eprintln!("{e}");
331 std::process::exit(1);
332 }
333 };
334
335 println!("Created profile '{name}' at {}", path.display());
336 if let Some(b) = base {
337 println!(" Based on: {b}");
338 }
339 println!("\nEdit the file to customize, then activate with:");
340 println!(" LEAN_CTX_PROFILE={name}");
341}
342
343fn cmd_profile_set(name: &str) {
344 if profiles::load_profile(name).is_none() {
345 eprintln!("Profile '{name}' not found. Available profiles:");
346 for p in profiles::list_profiles() {
347 eprintln!(" {}", p.name);
348 }
349 std::process::exit(1);
350 }
351
352 println!("To activate profile '{name}', run:\n");
353 println!(" export LEAN_CTX_PROFILE={name}\n");
354 println!(
355 "Or add it to your shell config ({}).",
356 lean_ctx::shell_hook::shell_rc_file()
357 );
358}
359
360fn cmd_tool_profile(args: &[String]) {
363 let action = args.first().map_or("show", String::as_str);
364
365 match action {
366 "list" | "ls" => cmd_tool_profile_list(),
367 "show" | "current" => cmd_tool_profile_show(),
368 "minimal" | "min" | "standard" | "std" | "power" | "full" | "all" | "lean" | "lazy"
369 | "reset" => {
370 cmd_tool_profile_switch(action);
371 }
372 _ => {
373 if ToolProfile::parse(action).is_some() {
374 cmd_tool_profile_switch(action);
375 } else {
376 eprintln!("Unknown tool profile '{action}'.");
377 eprintln!("Available: lean (default), minimal, standard, power");
378 std::process::exit(1);
379 }
380 }
381 }
382}
383
384fn cmd_tool_profile_show() {
385 let cfg = lean_ctx::core::config::Config::load();
386 let profile = cfg.tool_profile_effective();
387 let registry_count = lean_ctx_server::server::registry::tool_count();
388 let pinned = cfg.tool_profile.is_some()
389 || std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok()
390 || !cfg.tools_enabled.is_empty();
391
392 if !pinned {
393 let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
394 println!("Tool Profile: lean (default)");
395 println!(" Tools advertised: {lazy_count} (lazy core)");
396 println!(" All {registry_count} registered tools stay callable via ctx_call.");
397 println!("\n Advertised tools:");
398 for name in lean_ctx::tool_defs::core_tool_names() {
399 println!(" {name}");
400 }
401 println!("\n Switch with: lean-ctx tools <minimal|standard|power>");
402 return;
403 }
404
405 let count_str = match &profile {
406 ToolProfile::Power => format!("{registry_count}"),
407 ToolProfile::Custom(list) => format!("{}", list.len()),
408 other => format!("{}", other.tool_count()),
409 };
410
411 println!("Tool Profile: {}", profile.as_str());
412 println!(" Tools exposed: {count_str}");
413 println!(" Description: {}", profile.description());
414
415 if let Some(ref cfg_val) = cfg.tool_profile {
416 println!(" Source: config.toml (tool_profile = \"{cfg_val}\")");
417 }
418 if std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok() {
419 println!(" Source: LEAN_CTX_TOOL_PROFILE env var (overrides config)");
420 }
421
422 if !matches!(profile, ToolProfile::Power) {
423 println!("\n Enabled tools:");
424 let names = profile.tool_names();
425 for name in &names {
426 println!(" {name}");
427 }
428 }
429
430 println!("\n Switch with: lean-ctx tools <lean|minimal|standard|power>");
431 if matches!(profile, ToolProfile::Power) {
432 println!(" Tip: `lean-ctx tools lean` advertises only the lazy core (lowest overhead).");
433 }
434}
435
436fn cmd_tool_profile_list() {
437 let cfg = lean_ctx::core::config::Config::load();
438 let active = cfg.tool_profile_effective();
439 let registry_count = lean_ctx_server::server::registry::tool_count();
440 let pinned = cfg
443 .tool_profile
444 .as_deref()
445 .is_some_and(|p| !tool_profiles::is_unpinned_alias(p))
446 || std::env::var("LEAN_CTX_TOOL_PROFILE")
447 .is_ok_and(|v| !v.trim().is_empty() && !tool_profiles::is_unpinned_alias(v.trim()))
448 || !cfg.tools_enabled.is_empty();
449 let active_name = if pinned { active.as_str() } else { "lean" };
450 let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
451
452 println!("Tool Profiles:\n");
453 println!(" {:<12} {:<8} Description", "Name", "Tools");
454 println!(" {}", "\u{2500}".repeat(60));
455
456 let lean_marker = if active_name == "lean" { "* " } else { " " };
457 println!(
458 "{lean_marker}{:<12} {lazy_count:<8} Lazy core advertised, all tools via ctx_call (default)",
459 "lean"
460 );
461 for info in tool_profiles::list_profiles() {
462 let marker = if info.name == active_name { "* " } else { " " };
463 let count = if info.name == "power" {
464 format!("{registry_count}")
465 } else {
466 info.tool_count.to_string()
467 };
468 println!(
469 "{marker}{:<12} {:<8} {}",
470 info.name, count, info.description
471 );
472 }
473
474 println!("\n Active: {active_name}");
475 println!(" Switch: lean-ctx profile <name>");
476 println!(" Env: LEAN_CTX_TOOL_PROFILE=<name>");
477}
478
479fn cmd_tool_profile_switch(name: &str) {
480 if tool_profiles::is_unpinned_alias(name) {
484 if let Err(e) = tool_profiles::clear_profile_in_config() {
485 eprintln!("Error saving profile: {e}");
486 std::process::exit(1);
487 }
488 let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
489 println!("Tool profile set to: lean (default)");
490 println!(" Tools advertised: {lazy_count} (lazy core)");
491 println!(" All other tools stay callable via ctx_call.");
492 println!("\n Changes take effect on the next tool call (auto-detected).");
493 return;
494 }
495
496 let Some(profile) = ToolProfile::parse(name) else {
497 eprintln!("Unknown tool profile '{name}'.");
498 eprintln!("Available: lean (default), minimal, standard, power");
499 std::process::exit(1);
500 };
501
502 let canonical = profile.as_str();
503
504 if let Err(e) = tool_profiles::set_profile_in_config(canonical) {
505 eprintln!("Error saving profile: {e}");
506 std::process::exit(1);
507 }
508
509 let registry_count = lean_ctx_server::server::registry::tool_count();
510 let count_str = match &profile {
511 ToolProfile::Power => format!("{registry_count}"),
512 other => format!("{}", other.tool_count()),
513 };
514
515 println!("Tool profile set to: {canonical}");
516 println!(" Tools exposed: {count_str}");
517 println!(" Description: {}", profile.description());
518
519 if !matches!(profile, ToolProfile::Power) {
520 println!("\n Enabled tools:");
521 for name in profile.tool_names() {
522 println!(" {name}");
523 }
524 }
525
526 println!("\n Changes take effect on the next tool call (auto-detected).");
527}
528
529fn print_profile_help() {
530 eprintln!(
531 "lean-ctx has two kinds of profiles — here is which command to use:
532
533TOOL PROFILES — how many MCP tools your agent sees:
534 lean-ctx tools Show current tool profile
535 lean-ctx tools lean Lazy core advertised, all via ctx_call (default)
536 lean-ctx tools minimal 5 essential tools
537 lean-ctx tools standard 16 balanced tools
538 lean-ctx tools power All tools (highest context overhead)
539 lean-ctx tools list List tool profiles with counts
540
541CONTEXT PROFILES — how lean-ctx compresses and reads (this command):
542 lean-ctx profile list List available context profiles
543 lean-ctx profile show [name] Show context profile details (default: active)
544 lean-ctx profile active Show the currently active context profile
545 lean-ctx profile diff <a> <b> Compare two context profiles side by side
546 lean-ctx profile create <name> [--from <base>] [--global]
547 lean-ctx profile set <name> Show how to activate a context profile
548 lean-ctx profile suggest Recommend a profile from repo signals (read-only) [--json]"
549 );
550}