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 cfg.tool_profile_effective(),
219 &cfg.disabled_tools_effective(),
220 ClientQuirks::resolve(client_name, candidate),
221 )
222}
223
224#[must_use]
228pub fn narrow_to_surface(
229 profile: ToolProfile,
230 disabled: &[String],
231 quirks: ClientQuirks,
232) -> ToolProfile {
233 let profile = if profile == ToolProfile::Auto {
234 ToolProfile::Minimal
235 } else {
236 profile
237 };
238 let mut hidden: Vec<&str> = disabled.iter().map(String::as_str).collect();
239 if quirks.hide_ctx_edit {
240 hidden.push("ctx_edit");
241 }
242 if quirks.hide_ctx_patch {
243 hidden.push("ctx_patch");
244 }
245 hidden
246 .into_iter()
247 .fold(profile, |p, name| p.without_tool(name))
248}
249
250#[must_use]
258pub fn advertised_tool_defs_default() -> Vec<rmcp::model::Tool> {
259 let cfg = crate::core::config::Config::load();
260 let disabled = cfg.disabled_tools_effective();
261 let profile = cfg.tool_profile_effective();
262 let full_mode = crate::tool_defs::is_full_mode();
263 let registry = crate::server::registry::build_registry();
264
265 let candidate = candidate_set(&CandidateInputs {
266 full_mode,
267 unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
268 explicit_profile: explicit_profile(&cfg),
269 hook_covered: false, });
271 let pool: Vec<rmcp::model::Tool> = match candidate {
272 CandidateSet::Full | CandidateSet::ProfileAuthoritative => registry.tool_defs(),
273 CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
274 CandidateSet::ShadowOnly | CandidateSet::LazyCore => {
276 let core = crate::tool_defs::core_tool_names();
277 registry
278 .tool_defs()
279 .into_iter()
280 .filter(|t| core.contains(&t.name.as_ref()))
281 .collect()
282 }
283 };
284
285 let mut tools: Vec<_> = pool
286 .into_iter()
287 .filter(|t| {
288 is_tool_visible(
289 t.name.as_ref(),
290 &profile,
291 &disabled,
292 ClientQuirks::default(),
293 true,
294 )
295 })
296 .collect();
297
298 let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
299 if needs_invoker(full_mode, already, true, &disabled)
300 && let Some(def) = registry
301 .tool_defs()
302 .into_iter()
303 .find(|t| t.name.as_ref() == INVOKER)
304 {
305 tools.push(def);
306 }
307
308 let level = crate::core::config::CompressionLevel::effective(&cfg);
309 let mode = crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(&level);
310 if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
311 return tools;
312 }
313 tools
314 .into_iter()
315 .map(|mut t| {
316 let compressed = crate::core::terse::mcp_compress::compress_description(
317 t.name.as_ref(),
318 t.description.as_deref().unwrap_or(""),
319 mode,
320 );
321 t.description = Some(compressed.into());
322 t
323 })
324 .collect()
325}
326
327#[must_use]
337pub fn category_gate_applies(supports_list_changed: bool, explicit_profile: bool) -> bool {
338 supports_list_changed && !explicit_profile
339}
340
341#[must_use]
347pub fn needs_invoker(
348 full_mode: bool,
349 already_present: bool,
350 invoker_role_allowed: bool,
351 disabled: &[String],
352) -> bool {
353 !full_mode && !already_present && invoker_role_allowed && !disabled.iter().any(|d| d == INVOKER)
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 fn no_quirks() -> ClientQuirks {
362 ClientQuirks::default()
363 }
364
365 #[test]
366 fn internal_tools_never_visible_even_in_power() {
367 let p = ToolProfile::Power;
369 assert!(!is_tool_visible("ctx_metrics", &p, &[], no_quirks(), true));
370 assert!(!is_tool_visible("ctx_cost", &p, &[], no_quirks(), true));
371 assert!(!is_tool_visible(
372 "ctx_discover_tools",
373 &p,
374 &[],
375 no_quirks(),
376 true
377 ));
378 }
379
380 #[test]
381 fn deprecated_aliases_never_visible_even_in_power() {
382 let p = ToolProfile::Power;
385 assert!(!is_tool_visible(
386 "ctx_smart_read",
387 &p,
388 &[],
389 no_quirks(),
390 true
391 ));
392 assert!(!is_tool_visible(
393 "ctx_multi_read",
394 &p,
395 &[],
396 no_quirks(),
397 true
398 ));
399 }
400
401 #[test]
402 fn deprecated_aliases_stay_registered_and_callable() {
403 let _guard = crate::core::data_dir::isolated_data_dir();
407 let defs = crate::server::registry::build_registry().registered_tool_defs();
408 for name in [
409 "ctx_smart_read",
410 "ctx_multi_read",
411 "ctx_semantic_search",
412 "ctx_symbol",
413 ] {
414 assert!(
415 defs.iter().any(|t| t.name.as_ref() == name),
416 "{name} must stay registered (callable) even though hidden"
417 );
418 assert!(
419 !is_tool_visible(name, &ToolProfile::Power, &[], no_quirks(), true),
420 "{name} must be hidden from tools/list"
421 );
422 }
423 }
424
425 #[test]
426 fn local_collaboration_tools_stay_callable_but_are_never_advertised() {
427 let defs = crate::server::registry::build_registry().registered_tool_defs();
431 for name in super::super::dynamic_tools::LOCAL_COLLABORATION_COMPATIBILITY_TOOLS {
432 assert!(
433 ToolProfile::Power.is_tool_enabled(name),
434 "{name} must remain directly compatible with Power callers"
435 );
436 assert!(
437 defs.iter().any(|tool| tool.name.as_ref() == *name),
438 "{name} must stay registered for local compatibility"
439 );
440 assert!(
441 !is_tool_visible(name, &ToolProfile::Power, &[], no_quirks(), true),
442 "{name} must not be advertised from tools/list"
443 );
444 }
445 }
446
447 #[test]
448 fn core_tool_visible_under_power() {
449 assert!(is_tool_visible(
450 "ctx_read",
451 &ToolProfile::Power,
452 &[],
453 no_quirks(),
454 true
455 ));
456 }
457
458 #[test]
459 fn standard_exposes_its_advertised_tools() {
460 let p = ToolProfile::Standard;
464 assert!(is_tool_visible("ctx_execute", &p, &[], no_quirks(), true));
465 assert!(is_tool_visible("ctx_explore", &p, &[], no_quirks(), true));
466 assert!(is_tool_visible("ctx_callgraph", &p, &[], no_quirks(), true));
467 assert!(is_tool_visible("ctx_graph", &p, &[], no_quirks(), true));
468 assert!(is_tool_visible("ctx_patch", &p, &[], no_quirks(), true));
470 }
471
472 #[test]
473 fn folded_search_aliases_never_visible() {
474 let p = ToolProfile::Power;
477 assert!(!is_tool_visible(
478 "ctx_semantic_search",
479 &p,
480 &[],
481 no_quirks(),
482 true
483 ));
484 assert!(!is_tool_visible("ctx_symbol", &p, &[], no_quirks(), true));
485 assert!(is_tool_visible("ctx_search", &p, &[], no_quirks(), true));
486 }
487
488 #[test]
489 fn minimal_hides_non_minimal_tools() {
490 let p = ToolProfile::Minimal;
491 assert!(is_tool_visible("ctx_read", &p, &[], no_quirks(), true));
492 assert!(!is_tool_visible(
493 "ctx_architecture",
494 &p,
495 &[],
496 no_quirks(),
497 true
498 ));
499 }
500
501 #[test]
502 fn disabled_list_filters() {
503 let disabled = vec!["ctx_read".to_string()];
504 assert!(!is_tool_visible(
505 "ctx_read",
506 &ToolProfile::Power,
507 &disabled,
508 no_quirks(),
509 true
510 ));
511 }
512
513 #[test]
514 fn zed_hides_ctx_edit_only() {
515 let p = ToolProfile::Power;
516 let zed = ClientQuirks {
517 hide_ctx_edit: true,
518 hide_ctx_patch: false,
519 };
520 assert!(!is_tool_visible("ctx_edit", &p, &[], zed, true));
521 assert!(is_tool_visible("ctx_read", &p, &[], zed, true));
522 }
523
524 #[test]
525 fn native_editor_quirk_hides_ctx_patch_only() {
526 let p = ToolProfile::Power;
529 let native = ClientQuirks {
530 hide_ctx_edit: false,
531 hide_ctx_patch: true,
532 };
533 assert!(!is_tool_visible("ctx_patch", &p, &[], native, true));
534 assert!(is_tool_visible("ctx_read", &p, &[], native, true));
535 assert!(is_tool_visible("ctx_edit", &p, &[], native, true));
536 }
537
538 fn guidance_names(profile: &ToolProfile) -> String {
541 use crate::core::config::CompressionLevel;
542 use crate::core::rules_canonical::{Wrapper, render};
543 let mut text = String::new();
544 for shadow in [true, false] {
545 text.push_str(&render(
546 shadow,
547 Wrapper::Bare,
548 CompressionLevel::Off,
549 profile,
550 ));
551 }
552 text
553 }
554
555 #[test]
556 fn disabled_tools_leave_the_guidance() {
557 let disabled = vec!["ctx_callgraph".to_string()];
560 let p = narrow_to_surface(ToolProfile::Power, &disabled, ClientQuirks::default());
561 assert!(!p.is_tool_enabled("ctx_callgraph"));
562 assert!(
563 !is_tool_visible(
564 "ctx_callgraph",
565 &ToolProfile::Power,
566 &disabled,
567 ClientQuirks::default(),
568 true
569 ),
570 "precondition: tools/list hides it"
571 );
572 let text = guidance_names(&p);
573 assert!(
574 !text.contains("ctx_callgraph"),
575 "guidance names a disabled tool:\n{text}"
576 );
577 assert!(text.contains("ctx_patch"));
579 assert!(text.contains("ctx_compose"));
580 }
581
582 #[test]
583 fn a_hidden_ctx_patch_leaves_the_guidance() {
584 let quirk = ClientQuirks {
588 hide_ctx_edit: false,
589 hide_ctx_patch: true,
590 };
591 let by_quirk = narrow_to_surface(ToolProfile::Power, &[], quirk);
592 let disabled = vec!["ctx_edit".to_string(), "ctx_patch".to_string()];
593 let by_config =
594 narrow_to_surface(ToolProfile::Standard, &disabled, ClientQuirks::default());
595 for p in [by_quirk, by_config] {
596 let text = guidance_names(&p);
597 assert!(
598 !text.contains("ctx_patch"),
599 "{p}: guidance names ctx_patch:\n{text}"
600 );
601 assert!(
602 text.contains("the host's native edit tool"),
603 "{p}: edit line lost"
604 );
605 }
606 }
607
608 #[test]
609 fn auto_guidance_starts_at_minimal() {
610 let p = narrow_to_surface(ToolProfile::Auto, &[], ClientQuirks::default());
613 assert_eq!(p, ToolProfile::Minimal);
614 assert!(!guidance_names(&p).contains("ctx_compose"));
615 }
616
617 #[test]
618 fn an_unrestricted_surface_keeps_the_profile() {
619 for p in [
620 ToolProfile::Power,
621 ToolProfile::Standard,
622 ToolProfile::Minimal,
623 ] {
624 assert_eq!(
625 narrow_to_surface(p.clone(), &[], ClientQuirks::default()),
626 p
627 );
628 }
629 }
630
631 #[test]
632 fn quirks_resolution_is_client_and_candidate_aware() {
633 for client in ["Cursor", "zed 0.164", "Windsurf", "antigravity", "opencode"] {
635 let q = ClientQuirks::resolve(client, CandidateSet::LazyCore);
636 assert!(q.hide_ctx_patch, "{client}: lazy core must hide ctx_patch");
637 }
638 for client in ["claude-code", "CodeBuddy", "pi", "", "my-sdk-harness"] {
641 let q = ClientQuirks::resolve(client, CandidateSet::LazyCore);
642 assert!(
643 !q.hide_ctx_patch,
644 "{client:?}: lazy core must show ctx_patch"
645 );
646 }
647 for candidate in [
649 CandidateSet::ProfileAuthoritative,
650 CandidateSet::Full,
651 CandidateSet::Unified,
652 ] {
653 let q = ClientQuirks::resolve("Cursor", candidate);
654 assert!(
655 !q.hide_ctx_patch,
656 "{candidate:?}: pinned/full surfaces are client-agnostic"
657 );
658 }
659 assert!(ClientQuirks::resolve("zed", CandidateSet::Full).hide_ctx_edit);
661 assert!(!ClientQuirks::resolve("Cursor", CandidateSet::Full).hide_ctx_edit);
662 }
663
664 #[test]
665 fn role_block_hides_tool() {
666 assert!(!is_tool_visible(
667 "ctx_read",
668 &ToolProfile::Power,
669 &[],
670 no_quirks(),
671 false
672 ));
673 }
674
675 #[test]
676 fn category_gate_only_in_default_lean_mode() {
677 assert!(category_gate_applies(true, false));
680 assert!(!category_gate_applies(true, true));
682 assert!(!category_gate_applies(false, false));
684 assert!(!category_gate_applies(false, true));
685 }
686
687 #[test]
688 fn invoker_added_when_missing_in_lazy_mode() {
689 assert!(needs_invoker(false, false, true, &[]));
690 }
691
692 #[test]
693 fn invoker_not_added_in_full_mode() {
694 assert!(!needs_invoker(true, false, true, &[]));
695 }
696
697 #[test]
698 fn invoker_not_duplicated_when_present() {
699 assert!(!needs_invoker(false, true, true, &[]));
700 }
701
702 #[test]
703 fn invoker_respects_role_and_disabled() {
704 assert!(!needs_invoker(false, false, false, &[]));
705 assert!(!needs_invoker(
706 false,
707 false,
708 true,
709 &["ctx_call".to_string()]
710 ));
711 }
712
713 #[test]
775 fn core_tool_surface_stays_within_budget() {
776 const PER_TOOL_BUDGET: usize = 410;
777 const TOTAL_BUDGET: usize = 3000;
778
779 let _guard = crate::core::data_dir::isolated_data_dir();
780 let core = crate::tool_defs::core_tool_names();
781 let defs: Vec<_> = crate::server::registry::build_registry()
782 .tool_defs()
783 .into_iter()
784 .filter(|t| core.contains(&t.name.as_ref()))
785 .collect();
786 assert_eq!(defs.len(), core.len(), "every core tool must be registered");
787
788 let mut total = 0usize;
789 for t in &defs {
790 let desc = t.description.as_deref().unwrap_or("");
791 let schema = serde_json::to_string(&t.input_schema).unwrap_or_default();
792 let cost = crate::core::tokens::count_tokens(desc)
793 + crate::core::tokens::count_tokens(&schema);
794 eprintln!("{:24} {cost:4} tok", t.name.as_ref());
795 assert!(
796 cost <= PER_TOOL_BUDGET,
797 "{} costs {cost} tok (budget {PER_TOOL_BUDGET}) — trim its description/schema",
798 t.name
799 );
800 total += cost;
801 }
802 eprintln!("CORE TOTAL: {total} tok / {} tools", defs.len());
803 assert!(
804 total <= TOTAL_BUDGET,
805 "core surface costs {total} tok (budget {TOTAL_BUDGET})"
806 );
807 }
808
809 #[test]
810 fn resolve_auto_returns_non_auto_unchanged() {
811 assert_eq!(
812 resolve_auto_profile(&ToolProfile::Power),
813 ToolProfile::Power
814 );
815 assert_eq!(
816 resolve_auto_profile(&ToolProfile::Minimal),
817 ToolProfile::Minimal
818 );
819 }
820
821 #[test]
822 fn resolve_auto_resolves_to_concrete_profile() {
823 let resolved = resolve_auto_profile(&ToolProfile::Auto);
824 assert_ne!(resolved, ToolProfile::Auto);
825 }
826
827 #[test]
830 fn hook_covered_gets_lazy_core_not_shadow_only() {
831 let c = candidate_set(&CandidateInputs {
833 full_mode: false,
834 unified_env: false,
835 explicit_profile: false,
836 hook_covered: true,
837 });
838 assert_eq!(c, CandidateSet::LazyCore);
839 }
840
841 #[test]
842 fn shadow_only_overridden_by_full_mode() {
843 let c = candidate_set(&CandidateInputs {
844 full_mode: true,
845 unified_env: false,
846 explicit_profile: false,
847 hook_covered: true,
848 });
849 assert_eq!(
850 c,
851 CandidateSet::Full,
852 "LEAN_CTX_FULL_TOOLS=1 must override shadow-only"
853 );
854 }
855
856 #[test]
857 fn shadow_only_overridden_by_explicit_profile() {
858 let c = candidate_set(&CandidateInputs {
859 full_mode: false,
860 unified_env: false,
861 explicit_profile: true,
862 hook_covered: true,
863 });
864 assert_eq!(
865 c,
866 CandidateSet::ProfileAuthoritative,
867 "explicit profile must override shadow-only"
868 );
869 }
870
871 #[test]
872 fn lazy_core_when_not_hook_covered() {
873 let c = candidate_set(&CandidateInputs {
874 full_mode: false,
875 unified_env: false,
876 explicit_profile: false,
877 hook_covered: false,
878 });
879 assert_eq!(
880 c,
881 CandidateSet::LazyCore,
882 "non-hook client must get LazyCore"
883 );
884 }
885}