1use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
15
16use super::dynamic_tools::{ToolCategory, categorize_tool};
17use crate::core::tool_profiles::ToolProfile;
18
19static AUTO_TURN_COUNT: AtomicU64 = AtomicU64::new(0);
22static AUTO_CTX_TOOLS_USED: AtomicBool = AtomicBool::new(false);
23static AUTO_SYSTEM_PROMPT_TOKENS: AtomicUsize = AtomicUsize::new(0);
24
25pub fn record_auto_turn() {
27 AUTO_TURN_COUNT.fetch_add(1, Ordering::Relaxed);
28}
29
30pub fn mark_auto_ctx_tool_used() {
32 AUTO_CTX_TOOLS_USED.store(true, Ordering::Relaxed);
33}
34
35#[must_use]
38pub fn resolve_auto_profile(profile: &ToolProfile) -> ToolProfile {
39 if *profile != ToolProfile::Auto {
40 return profile.clone();
41 }
42 ToolProfile::resolve_auto(
43 AUTO_TURN_COUNT.load(Ordering::Relaxed),
44 AUTO_CTX_TOOLS_USED.load(Ordering::Relaxed),
45 AUTO_SYSTEM_PROMPT_TOKENS.load(Ordering::Relaxed),
46 )
47}
48
49pub const INVOKER: &str = "ctx_call";
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum CandidateSet {
56 Full,
58 Unified,
60 ProfileAuthoritative,
63 LazyCore,
66 #[allow(dead_code)]
70 ShadowOnly,
71}
72
73pub struct CandidateInputs {
75 pub full_mode: bool,
76 pub unified_env: bool,
77 pub explicit_profile: bool,
78 pub hook_covered: bool,
79}
80
81#[must_use]
85pub fn candidate_set(inp: &CandidateInputs) -> CandidateSet {
86 if inp.full_mode {
87 CandidateSet::Full
88 } else if inp.unified_env {
89 CandidateSet::Unified
90 } else if inp.explicit_profile {
91 CandidateSet::ProfileAuthoritative
92 } else {
93 CandidateSet::LazyCore
97 }
98}
99
100#[allow(dead_code)]
102fn is_shadow_surface_enabled() -> bool {
103 if let Ok(v) = std::env::var("LEAN_CTX_TOOL_SURFACE") {
104 return v.eq_ignore_ascii_case("shadow") || v.eq_ignore_ascii_case("auto");
105 }
106 let cfg = crate::core::config::Config::load();
107 !matches!(cfg.tool_surface.as_deref(), Some("mcp"))
110}
111
112#[must_use]
115pub fn explicit_profile(cfg: &crate::core::config::Config) -> bool {
116 cfg.tool_profile.is_some()
117 || !cfg.tools_enabled.is_empty()
118 || std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok()
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
127pub struct ClientQuirks {
128 pub hide_ctx_edit: bool,
130 pub hide_ctx_patch: bool,
135}
136
137impl ClientQuirks {
138 #[must_use]
140 pub fn resolve(client_name: &str, candidate: CandidateSet) -> Self {
141 let lower = client_name.to_lowercase();
142 Self {
143 hide_ctx_edit: lower.contains("zed"),
144 hide_ctx_patch: candidate == CandidateSet::LazyCore && has_native_editor(&lower),
145 }
146 }
147}
148
149fn has_native_editor(lower_client_name: &str) -> bool {
156 [
157 "cursor",
158 "zed",
159 "windsurf",
160 "codeium",
161 "antigravity",
162 "opencode",
163 ]
164 .iter()
165 .any(|c| lower_client_name.contains(c))
166}
167
168#[must_use]
174pub fn is_tool_visible(
175 name: &str,
176 profile: &ToolProfile,
177 disabled: &[String],
178 quirks: ClientQuirks,
179 role_allows: bool,
180) -> bool {
181 if categorize_tool(name) == ToolCategory::Internal {
182 return false;
183 }
184 if !super::dynamic_tools::is_publicly_advertised_tool(name) {
187 return false;
188 }
189 if !profile.is_tool_enabled(name) {
190 return false;
191 }
192 if disabled.iter().any(|d| d == name) {
193 return false;
194 }
195 if quirks.hide_ctx_edit && name == "ctx_edit" {
196 return false;
197 }
198 if quirks.hide_ctx_patch && name == "ctx_patch" {
199 return false;
200 }
201 role_allows
202}
203
204#[must_use]
210pub fn guidance_profile(cfg: &crate::core::config::Config, client_name: &str) -> ToolProfile {
211 let candidate = candidate_set(&CandidateInputs {
212 full_mode: crate::tool_defs::is_full_mode(),
213 unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
214 explicit_profile: explicit_profile(cfg),
215 hook_covered: false, });
217 narrow_to_surface(
218 lazy_core_surface(cfg.tool_profile_effective(), candidate),
219 &cfg.disabled_tools_effective(),
220 ClientQuirks::resolve(client_name, candidate),
221 )
222}
223
224fn lazy_core_surface(profile: ToolProfile, candidate: CandidateSet) -> ToolProfile {
229 if candidate != CandidateSet::LazyCore {
230 return profile;
231 }
232 ToolProfile::Custom(
233 crate::tool_defs::CORE_TOOL_NAMES
234 .iter()
235 .filter(|name| profile.is_tool_enabled(name))
236 .map(|name| (*name).to_string())
237 .collect(),
238 )
239}
240
241#[must_use]
245pub fn narrow_to_surface(
246 profile: ToolProfile,
247 disabled: &[String],
248 quirks: ClientQuirks,
249) -> ToolProfile {
250 let profile = if profile == ToolProfile::Auto {
251 ToolProfile::Minimal
252 } else {
253 profile
254 };
255 let mut hidden: Vec<&str> = disabled.iter().map(String::as_str).collect();
256 if quirks.hide_ctx_edit {
257 hidden.push("ctx_edit");
258 }
259 if quirks.hide_ctx_patch {
260 hidden.push("ctx_patch");
261 }
262 hidden
263 .into_iter()
264 .fold(profile, |p, name| p.without_tool(name))
265}
266
267#[must_use]
275pub fn advertised_tool_defs_default() -> Vec<rmcp::model::Tool> {
276 let cfg = crate::core::config::Config::load();
277 let disabled = cfg.disabled_tools_effective();
278 let profile = cfg.tool_profile_effective();
279 let full_mode = crate::tool_defs::is_full_mode();
280 let registry = crate::server::registry::build_registry();
281
282 let candidate = candidate_set(&CandidateInputs {
283 full_mode,
284 unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
285 explicit_profile: explicit_profile(&cfg),
286 hook_covered: false, });
288 let pool: Vec<rmcp::model::Tool> = match candidate {
289 CandidateSet::Full | CandidateSet::ProfileAuthoritative => registry.tool_defs(),
290 CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
291 CandidateSet::ShadowOnly | CandidateSet::LazyCore => {
293 let core = crate::tool_defs::core_tool_names();
294 registry
295 .tool_defs()
296 .into_iter()
297 .filter(|t| core.contains(&t.name.as_ref()))
298 .collect()
299 }
300 };
301
302 let mut tools: Vec<_> = pool
303 .into_iter()
304 .filter(|t| {
305 is_tool_visible(
306 t.name.as_ref(),
307 &profile,
308 &disabled,
309 ClientQuirks::default(),
310 true,
311 )
312 })
313 .collect();
314
315 let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
316 if needs_invoker(full_mode, already, true, &disabled)
317 && let Some(def) = registry
318 .tool_defs()
319 .into_iter()
320 .find(|t| t.name.as_ref() == INVOKER)
321 {
322 tools.push(def);
323 }
324
325 let level = crate::core::config::CompressionLevel::effective(&cfg);
326 let mode = crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(&level);
327 if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
328 return tools;
329 }
330 tools
331 .into_iter()
332 .map(|mut t| {
333 let compressed = crate::core::terse::mcp_compress::compress_description(
334 t.name.as_ref(),
335 t.description.as_deref().unwrap_or(""),
336 mode,
337 );
338 t.description = Some(compressed.into());
339 t
340 })
341 .collect()
342}
343
344#[must_use]
354pub fn category_gate_applies(supports_list_changed: bool, explicit_profile: bool) -> bool {
355 supports_list_changed && !explicit_profile
356}
357
358#[must_use]
364pub fn needs_invoker(
365 full_mode: bool,
366 already_present: bool,
367 invoker_role_allowed: bool,
368 disabled: &[String],
369) -> bool {
370 !full_mode && !already_present && invoker_role_allowed && !disabled.iter().any(|d| d == INVOKER)
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376
377 fn no_quirks() -> ClientQuirks {
379 ClientQuirks::default()
380 }
381
382 #[test]
383 fn internal_tools_never_visible_even_in_power() {
384 let p = ToolProfile::Power;
386 assert!(!is_tool_visible("ctx_metrics", &p, &[], no_quirks(), true));
387 assert!(!is_tool_visible("ctx_cost", &p, &[], no_quirks(), true));
388 assert!(!is_tool_visible(
389 "ctx_discover_tools",
390 &p,
391 &[],
392 no_quirks(),
393 true
394 ));
395 }
396
397 #[test]
398 fn local_collaboration_tools_stay_callable_but_are_never_advertised() {
399 let defs = crate::server::registry::build_registry().registered_tool_defs();
403 for name in super::super::dynamic_tools::LOCAL_COLLABORATION_COMPATIBILITY_TOOLS {
404 assert!(
405 ToolProfile::Power.is_tool_enabled(name),
406 "{name} must remain directly compatible with Power callers"
407 );
408 assert!(
409 defs.iter().any(|tool| tool.name.as_ref() == *name),
410 "{name} must stay registered for local compatibility"
411 );
412 assert!(
413 !is_tool_visible(name, &ToolProfile::Power, &[], no_quirks(), true),
414 "{name} must not be advertised from tools/list"
415 );
416 }
417 }
418
419 #[test]
420 fn core_tool_visible_under_power() {
421 assert!(is_tool_visible(
422 "ctx_read",
423 &ToolProfile::Power,
424 &[],
425 no_quirks(),
426 true
427 ));
428 }
429
430 #[test]
431 fn standard_exposes_its_advertised_tools() {
432 let p = ToolProfile::Standard;
436 assert!(is_tool_visible("ctx_execute", &p, &[], no_quirks(), true));
437 assert!(is_tool_visible("ctx_compose", &p, &[], no_quirks(), true));
438 assert!(is_tool_visible("ctx_callgraph", &p, &[], no_quirks(), true));
439 assert!(is_tool_visible("ctx_graph", &p, &[], no_quirks(), true));
440 assert!(is_tool_visible("ctx_patch", &p, &[], no_quirks(), true));
442 }
443
444 #[test]
445 fn minimal_hides_non_minimal_tools() {
446 let p = ToolProfile::Minimal;
447 assert!(is_tool_visible("ctx_read", &p, &[], no_quirks(), true));
448 assert!(!is_tool_visible("ctx_index", &p, &[], no_quirks(), true));
449 }
450
451 #[test]
452 fn disabled_list_filters() {
453 let disabled = vec!["ctx_read".to_string()];
454 assert!(!is_tool_visible(
455 "ctx_read",
456 &ToolProfile::Power,
457 &disabled,
458 no_quirks(),
459 true
460 ));
461 }
462
463 #[test]
464 fn zed_hides_ctx_edit_only() {
465 let p = ToolProfile::Power;
466 let zed = ClientQuirks {
467 hide_ctx_edit: true,
468 hide_ctx_patch: false,
469 };
470 assert!(!is_tool_visible("ctx_edit", &p, &[], zed, true));
471 assert!(is_tool_visible("ctx_read", &p, &[], zed, true));
472 }
473
474 #[test]
475 fn native_editor_quirk_hides_ctx_patch_only() {
476 let p = ToolProfile::Power;
479 let native = ClientQuirks {
480 hide_ctx_edit: false,
481 hide_ctx_patch: true,
482 };
483 assert!(!is_tool_visible("ctx_patch", &p, &[], native, true));
484 assert!(is_tool_visible("ctx_read", &p, &[], native, true));
485 assert!(is_tool_visible("ctx_edit", &p, &[], native, true));
486 }
487
488 fn guidance_names(profile: &ToolProfile) -> String {
491 use crate::core::config::CompressionLevel;
492 use crate::core::rules_canonical::{Wrapper, render};
493 let mut text = String::new();
494 for shadow in [true, false] {
495 text.push_str(&render(
496 shadow,
497 Wrapper::Bare,
498 CompressionLevel::Off,
499 profile,
500 ));
501 }
502 text
503 }
504
505 #[test]
506 fn disabled_tools_leave_the_guidance() {
507 let disabled = vec!["ctx_callgraph".to_string()];
510 let p = narrow_to_surface(ToolProfile::Power, &disabled, ClientQuirks::default());
511 assert!(!p.is_tool_enabled("ctx_callgraph"));
512 assert!(
513 !is_tool_visible(
514 "ctx_callgraph",
515 &ToolProfile::Power,
516 &disabled,
517 ClientQuirks::default(),
518 true
519 ),
520 "precondition: tools/list hides it"
521 );
522 let text = guidance_names(&p);
523 assert!(
524 !text.contains("ctx_callgraph"),
525 "guidance names a disabled tool:\n{text}"
526 );
527 assert!(text.contains("ctx_patch"));
529 assert!(text.contains("ctx_compose"));
530 }
531
532 #[test]
533 fn lazy_core_guidance_names_only_core_tools() {
534 let core = lazy_core_surface(ToolProfile::Power, CandidateSet::LazyCore);
538 let native = ClientQuirks {
539 hide_ctx_edit: false,
540 hide_ctx_patch: true,
541 };
542 let surface = narrow_to_surface(core, &[], native);
543 let text = guidance_names(&surface);
544 for absent in ["ctx_knowledge", "ctx_patch", "ctx_graph", "ctx_overview"] {
545 assert!(!text.contains(absent), "names {absent}:\n{text}");
546 }
547 for present in ["ctx_compose", "ctx_session", "ctx_callgraph", "ctx_call("] {
548 assert!(text.contains(present), "misses {present}:\n{text}");
549 }
550 assert_eq!(
552 lazy_core_surface(ToolProfile::Power, CandidateSet::ProfileAuthoritative),
553 ToolProfile::Power
554 );
555 }
556
557 #[test]
558 fn a_hidden_ctx_patch_leaves_the_guidance() {
559 let quirk = ClientQuirks {
563 hide_ctx_edit: false,
564 hide_ctx_patch: true,
565 };
566 let by_quirk = narrow_to_surface(ToolProfile::Power, &[], quirk);
567 let disabled = vec!["ctx_edit".to_string(), "ctx_patch".to_string()];
568 let by_config =
569 narrow_to_surface(ToolProfile::Standard, &disabled, ClientQuirks::default());
570 for p in [by_quirk, by_config] {
571 let text = guidance_names(&p);
572 assert!(
573 !text.contains("ctx_patch"),
574 "{p}: guidance names ctx_patch:\n{text}"
575 );
576 assert!(
577 text.contains("the host's native edit tool"),
578 "{p}: edit line lost"
579 );
580 }
581 }
582
583 #[test]
584 fn auto_guidance_starts_at_minimal() {
585 let p = narrow_to_surface(ToolProfile::Auto, &[], ClientQuirks::default());
588 assert_eq!(p, ToolProfile::Minimal);
589 assert!(!guidance_names(&p).contains("ctx_compose"));
590 }
591
592 #[test]
593 fn an_unrestricted_surface_keeps_the_profile() {
594 for p in [
595 ToolProfile::Power,
596 ToolProfile::Standard,
597 ToolProfile::Minimal,
598 ] {
599 assert_eq!(
600 narrow_to_surface(p.clone(), &[], ClientQuirks::default()),
601 p
602 );
603 }
604 }
605
606 #[test]
607 fn quirks_resolution_is_client_and_candidate_aware() {
608 for client in ["Cursor", "zed 0.164", "Windsurf", "antigravity", "opencode"] {
610 let q = ClientQuirks::resolve(client, CandidateSet::LazyCore);
611 assert!(q.hide_ctx_patch, "{client}: lazy core must hide ctx_patch");
612 }
613 for client in ["claude-code", "CodeBuddy", "pi", "", "my-sdk-harness"] {
616 let q = ClientQuirks::resolve(client, CandidateSet::LazyCore);
617 assert!(
618 !q.hide_ctx_patch,
619 "{client:?}: lazy core must show ctx_patch"
620 );
621 }
622 for candidate in [
624 CandidateSet::ProfileAuthoritative,
625 CandidateSet::Full,
626 CandidateSet::Unified,
627 ] {
628 let q = ClientQuirks::resolve("Cursor", candidate);
629 assert!(
630 !q.hide_ctx_patch,
631 "{candidate:?}: pinned/full surfaces are client-agnostic"
632 );
633 }
634 assert!(ClientQuirks::resolve("zed", CandidateSet::Full).hide_ctx_edit);
636 assert!(!ClientQuirks::resolve("Cursor", CandidateSet::Full).hide_ctx_edit);
637 }
638
639 #[test]
640 fn role_block_hides_tool() {
641 assert!(!is_tool_visible(
642 "ctx_read",
643 &ToolProfile::Power,
644 &[],
645 no_quirks(),
646 false
647 ));
648 }
649
650 #[test]
651 fn category_gate_only_in_default_lean_mode() {
652 assert!(category_gate_applies(true, false));
655 assert!(!category_gate_applies(true, true));
657 assert!(!category_gate_applies(false, false));
659 assert!(!category_gate_applies(false, true));
660 }
661
662 #[test]
663 fn invoker_added_when_missing_in_lazy_mode() {
664 assert!(needs_invoker(false, false, true, &[]));
665 }
666
667 #[test]
668 fn invoker_not_added_in_full_mode() {
669 assert!(!needs_invoker(true, false, true, &[]));
670 }
671
672 #[test]
673 fn invoker_not_duplicated_when_present() {
674 assert!(!needs_invoker(false, true, true, &[]));
675 }
676
677 #[test]
678 fn invoker_respects_role_and_disabled() {
679 assert!(!needs_invoker(false, false, false, &[]));
680 assert!(!needs_invoker(
681 false,
682 false,
683 true,
684 &["ctx_call".to_string()]
685 ));
686 }
687
688 #[test]
750 fn core_tool_surface_stays_within_budget() {
751 const PER_TOOL_BUDGET: usize = 410;
752 const TOTAL_BUDGET: usize = 3000;
753
754 let _guard = crate::core::data_dir::isolated_data_dir();
755 let core = crate::tool_defs::core_tool_names();
756 let defs: Vec<_> = crate::server::registry::build_registry()
757 .tool_defs()
758 .into_iter()
759 .filter(|t| core.contains(&t.name.as_ref()))
760 .collect();
761 assert_eq!(defs.len(), core.len(), "every core tool must be registered");
762
763 let mut total = 0usize;
764 for t in &defs {
765 let desc = t.description.as_deref().unwrap_or("");
766 let schema = serde_json::to_string(&t.input_schema).unwrap_or_default();
767 let cost = crate::core::tokens::count_tokens(desc)
768 + crate::core::tokens::count_tokens(&schema);
769 eprintln!("{:24} {cost:4} tok", t.name.as_ref());
770 assert!(
771 cost <= PER_TOOL_BUDGET,
772 "{} costs {cost} tok (budget {PER_TOOL_BUDGET}) — trim its description/schema",
773 t.name
774 );
775 total += cost;
776 }
777 eprintln!("CORE TOTAL: {total} tok / {} tools", defs.len());
778 assert!(
779 total <= TOTAL_BUDGET,
780 "core surface costs {total} tok (budget {TOTAL_BUDGET})"
781 );
782 }
783
784 #[test]
785 fn resolve_auto_returns_non_auto_unchanged() {
786 assert_eq!(
787 resolve_auto_profile(&ToolProfile::Power),
788 ToolProfile::Power
789 );
790 assert_eq!(
791 resolve_auto_profile(&ToolProfile::Minimal),
792 ToolProfile::Minimal
793 );
794 }
795
796 #[test]
797 fn resolve_auto_resolves_to_concrete_profile() {
798 let resolved = resolve_auto_profile(&ToolProfile::Auto);
799 assert_ne!(resolved, ToolProfile::Auto);
800 }
801
802 #[test]
805 fn hook_covered_gets_lazy_core_not_shadow_only() {
806 let c = candidate_set(&CandidateInputs {
808 full_mode: false,
809 unified_env: false,
810 explicit_profile: false,
811 hook_covered: true,
812 });
813 assert_eq!(c, CandidateSet::LazyCore);
814 }
815
816 #[test]
817 fn shadow_only_overridden_by_full_mode() {
818 let c = candidate_set(&CandidateInputs {
819 full_mode: true,
820 unified_env: false,
821 explicit_profile: false,
822 hook_covered: true,
823 });
824 assert_eq!(
825 c,
826 CandidateSet::Full,
827 "LEAN_CTX_FULL_TOOLS=1 must override shadow-only"
828 );
829 }
830
831 #[test]
832 fn shadow_only_overridden_by_explicit_profile() {
833 let c = candidate_set(&CandidateInputs {
834 full_mode: false,
835 unified_env: false,
836 explicit_profile: true,
837 hook_covered: true,
838 });
839 assert_eq!(
840 c,
841 CandidateSet::ProfileAuthoritative,
842 "explicit profile must override shadow-only"
843 );
844 }
845
846 #[test]
847 fn lazy_core_when_not_hook_covered() {
848 let c = candidate_set(&CandidateInputs {
849 full_mode: false,
850 unified_env: false,
851 explicit_profile: false,
852 hook_covered: false,
853 });
854 assert_eq!(
855 c,
856 CandidateSet::LazyCore,
857 "non-hook client must get LazyCore"
858 );
859 }
860}