Skip to main content

lean_ctx/server/
tool_visibility.rs

1//! Pure tool-visibility policy for the MCP `tools/list` response.
2//!
3//! Extracted from the (async, server-bound) `list_tools` handler so the policy
4//! is unit-testable in isolation. The handler resolves the candidate set
5//! (lazy-core vs profile-authoritative vs full registry) and the per-call gates
6//! (role, workflow), then defers to these helpers for the stable rules:
7//!   * Internal/meta tools are never advertised.
8//!   * The active profile, `disabled_tools`, and the per-client
9//!     [`ClientQuirks`] (Zed `ctx_edit`, native-editor `ctx_patch`) filter the
10//!     candidates.
11//!   * The universal invoker (`ctx_call`) is force-advertised in non-full mode so
12//!     tools hidden by lazy/profile filtering stay reachable.
13
14use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
15
16use super::dynamic_tools::{ToolCategory, categorize_tool};
17use crate::core::tool_profiles::ToolProfile;
18
19// ── Auto-profile session signals ─────────────────────────────
20
21static 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
25/// Increment the Auto-profile turn counter (call once per tools/list request).
26pub fn record_auto_turn() {
27    AUTO_TURN_COUNT.fetch_add(1, Ordering::Relaxed);
28}
29
30/// Mark that the agent has invoked a ctx_* MCP tool in this session.
31pub fn mark_auto_ctx_tool_used() {
32    AUTO_CTX_TOOLS_USED.store(true, Ordering::Relaxed);
33}
34
35/// Resolve `ToolProfile::Auto` to a concrete profile using session signals.
36/// Non-Auto profiles are returned as-is.
37#[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
49/// The universal invoker tool name. A static-list MCP client can call any
50/// registered tool through it, even when that tool isn't advertised.
51pub const INVOKER: &str = "ctx_call";
52
53/// Which candidate pool `tools/list` starts from, before per-tool gates run.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum CandidateSet {
56    /// Full registry (`LEAN_CTX_FULL_TOOLS=1` / `LEAN_CTX_LAZY_TOOLS=0`).
57    Full,
58    /// Consolidated unified surface (`LEAN_CTX_UNIFIED`).
59    Unified,
60    /// The user pinned a profile — it is authoritative and resolves against
61    /// the full registry (#358), so `standard` advertises its complete set.
62    ProfileAuthoritative,
63    /// Lean default: only `CORE_TOOL_NAMES` are advertised; everything else
64    /// stays reachable through [`INVOKER`] (#575).
65    LazyCore,
66    /// Deprecated (GH #1474): was the hook-covered-only surface (just ctx_call).
67    /// Never returned by `candidate_set` anymore — kept only for exhaustive
68    /// match compatibility until fully removed.
69    #[allow(dead_code)]
70    ShadowOnly,
71}
72
73/// Inputs to [`candidate_set`]. Avoids a long bool parameter list (#clippy::fn_params_excessive_bools).
74pub 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/// Decides the candidate pool. Single source of truth for the `tools/list`
82/// handler AND offline measurement (`doctor overhead`), so the advertised
83/// surface and the reported overhead can never drift apart.
84#[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        // GH #1474: all MCP-connected clients (hook-covered or not) get the
94        // lazy-core surface. Shadow-only (ctx_call alone) caused agent confusion
95        // because they could not discover ctx_read/ctx_search/etc. by name.
96        CandidateSet::LazyCore
97    }
98}
99
100/// Whether the shadow-only tool surface is enabled (config or env).
101#[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    // Only "mcp" explicitly disables shadow surface; "auto", "shadow", and
108    // unset all enable it (when the caller already confirmed hook_covered).
109    !matches!(cfg.tool_surface.as_deref(), Some("mcp"))
110}
111
112/// Whether the user explicitly pinned a tool profile (config key, custom tool
113/// list, or env var) — the trigger for [`CandidateSet::ProfileAuthoritative`].
114#[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/// Client-specific advertising quirks, resolved once per `tools/list` from the
122/// MCP `clientInfo` name and the candidate set.
123///
124/// [`ClientQuirks::default`] (no quirks) is the "default client" used by
125/// offline measurement — the worst-case surface, nothing hidden.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
127pub struct ClientQuirks {
128    /// Zed cannot handle `ctx_edit` (schema quirk) — hide it there.
129    pub hide_ctx_edit: bool,
130    /// Lazy-core only (#1008): the client ships a reliable native str-replace
131    /// editor, so the *default* surface skips `ctx_patch` — those sessions pay
132    /// zero extra schema tokens. A pinned profile is the user's explicit,
133    /// client-agnostic choice and always advertises its full set.
134    pub hide_ctx_patch: bool,
135}
136
137impl ClientQuirks {
138    /// Resolve the quirks for one `tools/list` answer.
139    #[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
149/// Clients whose built-in edit tool is reliable enough that the default
150/// (lazy-core) surface need not advertise `ctx_patch`: Cursor, Zed,
151/// Windsurf/Codeium, Antigravity, OpenCode. Everyone else gets the anchored
152/// editor — Claude Code (the hook read-redirect breaks its native
153/// read-before-write guard, #637), CodeBuddy, pi/SDK harnesses and
154/// unknown/headless clients that have no native editor at all.
155fn 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/// Decides whether a tool name should appear in `tools/list`.
169///
170/// `role_allows` is supplied by the caller (it depends on the active role, which
171/// is resolved outside this pure function). Internal tools are hidden
172/// unconditionally — they're invoked automatically or via [`INVOKER`].
173#[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    // Deprecated aliases and the local-only collaboration substrate are hidden
185    // from every advertised surface but remain registered and directly callable.
186    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/// The tool set agent-facing guidance may name for `client_name`: the MCP
205/// `instructions` and the injected rule files (#1849). It passes the same
206/// gates as `tools/list` — the effective profile, `disabled_tools` (which
207/// folds in `prefer_native_editor`) and the client's quirks — so the text
208/// never points the agent at a tool its session cannot call.
209#[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, // no longer affects the candidate set (GH #1474)
216    });
217    narrow_to_surface(
218        cfg.tool_profile_effective(),
219        &cfg.disabled_tools_effective(),
220        ClientQuirks::resolve(client_name, candidate),
221    )
222}
223
224/// Pure core of [`guidance_profile`]: `profile` minus every tool the surface
225/// withholds. `Auto` is taken at its starting point (minimal) — guidance is
226/// written once per session and must not promise a tool before escalation.
227#[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/// Computes the tool set this install advertises to a default client
251/// (no client quirks, no role restriction, no workflow gate, static tool list),
252/// including the live description compression. Offline counterpart of the
253/// `tools/list` handler for `doctor overhead` / `ContextOverhead::measure` —
254/// kept next to the pure gates so measurement cannot drift from policy.
255/// "No quirks" is the worst case: a client without a native editor sees
256/// `ctx_patch` too, so the reported overhead never understates.
257#[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, // offline measurement uses worst-case (no hook coverage)
270    });
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        // GH #1474: ShadowOnly no longer returned; treat as LazyCore.
275        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/// Whether the lazy per-category gate should filter the advertised tool set.
328///
329/// The dynamic-tools category gate (load tools on demand, signalled via
330/// `notifications/tools/list_changed`) exists to keep the *default* lean-core
331/// surface small for capable clients. An explicit profile is the user's chosen,
332/// authoritative surface, so it must be advertised in full — otherwise category
333/// gating silently drops profile-enabled tools (e.g. Standard's
334/// `ctx_architecture` / `ctx_semantic_search`) for clients like Codex, and the
335/// advertised set stops matching `lean-ctx tools show` (#358).
336#[must_use]
337pub fn category_gate_applies(supports_list_changed: bool, explicit_profile: bool) -> bool {
338    supports_list_changed && !explicit_profile
339}
340
341/// Whether [`INVOKER`] must be force-added to the advertised set.
342///
343/// True only in non-full mode when it isn't already present, the role permits
344/// it, and it isn't explicitly disabled. In full mode every tool is already
345/// listed, so no gateway is needed.
346#[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    /// No client quirks — the default/measurement client.
361    fn no_quirks() -> ClientQuirks {
362        ClientQuirks::default()
363    }
364
365    #[test]
366    fn internal_tools_never_visible_even_in_power() {
367        // Power enables everything, but Internal/meta tools must still be hidden.
368        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        // #509: folded read-cluster aliases are hidden from tools/list in every
383        // mode (Power enables everything) — but stay registered + callable.
384        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        // The non-breaking contract (#509): hidden from the advertised surface,
404        // but still in the registry so direct calls and ctx_call keep working
405        // for one release. Removal is Phase 2.
406        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        // The local bus/task/workflow substrate remains installed for existing
428        // local integrations. It is not a public coordination product, even in
429        // an explicitly pinned Power profile.
430        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        // These are in STANDARD_TOOLS but were dropped by the old
461        // `core ∩ standard` intersection. Profile-authoritative resolution must
462        // surface them.
463        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        // #1008: anchored editing ships with the pinned Standard profile.
469        assert!(is_tool_visible("ctx_patch", &p, &[], no_quirks(), true));
470    }
471
472    #[test]
473    fn folded_search_aliases_never_visible() {
474        // #509: ctx_semantic_search + ctx_symbol are consolidated into ctx_search
475        // (action=…). Hidden from tools/list in every mode, but stay callable.
476        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        // #1008: a native-editor client in the lazy default drops ctx_patch —
527        // and nothing else.
528        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    /// Every tool the guidance names under `profile`, checked against the
539    /// same gate `tools/list` applies (#1849).
540    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        // #1849: `disabled_tools = ["ctx_callgraph"]` hid the tool from
558        // `tools/list`, but the instructions still said "ctx_callgraph (callers)".
559        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        // Nothing else is lost on the way.
578        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        // #1849: `prefer_native_editor` folds ctx_patch into the disabled
585        // list; the native-editor quirk hides it on the lazy surface. Either
586        // way "if denied, use ctx_patch" points at a tool the agent lacks.
587        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        // Guidance is written once per session; Auto must not promise the
611        // tools it only escalates to later.
612        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        // Native-editor clients skip ctx_patch in the lazy default…
634        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        // …clients without a reliable native editor get it (#637: Claude Code's
639        // read-before-write guard breaks under the read-redirect hook).
640        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        // A pinned profile is client-agnostic — never hide ctx_patch there.
648        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        // The Zed ctx_edit quirk is independent of the candidate set.
660        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        // Lazy gate applies only when the client supports list_changed AND no
678        // explicit profile is set.
679        assert!(category_gate_applies(true, false));
680        // Explicit profile is authoritative — never gated (#358).
681        assert!(!category_gate_applies(true, true));
682        // Static-list clients are never gated regardless of profile.
683        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    /// #576 schema diet: the lazy-core surface is the default fixed cost every
714    /// session pays — keep it bounded. Per-tool cap keeps any single schema
715    /// from bloating; the total cap keeps the whole advertised surface lean.
716    /// (Raw registry defs, before description compression — worst case.)
717    ///
718    /// The total grew with the 14th core tool, `ctx_semantic_search` (#422):
719    /// it joined the lean core so agents discover semantic search by default
720    /// instead of never reaching for it. The per-tool cap (300) still guards
721    /// individual bloat; the total budget is sized to that 14-tool surface.
722    ///
723    /// Bumped to 2260 for #432: `ctx_read` now advertises the `offset`/`limit`
724    /// aliases (so agents trained on the native Read tool discover them), a
725    /// deliberate +~32 tok. Descriptions are kept terse to limit the cost.
726    ///
727    /// Bumped to 2275 for #451: `ctx_shell` now states it runs the system shell
728    /// profile-free (no rc/profile sourced), a deliberate +~13 tok so agents stop
729    /// mistaking it for a config-loaded interactive bash. Kept to one terse clause.
730    ///
731    /// Bumped to per-tool 335 / total 2310 for #513: `ctx_read` now documents the
732    /// verbatim escape hatch (`raw=true` arg + `raw` mode) so agents — especially
733    /// non-Opus models that fought the compression — discover how to get exact
734    /// bytes for review/audit instead of guessing. `ctx_read` is the richest core
735    /// tool and is the only one that crosses 300; the per-tool cap still guards
736    /// every other tool from bloat. Kept to terse clauses (+~33 tok on ctx_read).
737    ///
738    /// Bumped to per-tool 360 / total 2340 for #509: `ctx_read` absorbs the
739    /// `ctx_multi_read` batch capability via a `paths` array, so two tools collapse
740    /// into one (`ctx_smart_read` + `ctx_multi_read` are now deprecated aliases
741    /// hidden from the surface). The net effect REDUCES the advertised surface; the
742    /// only local cost is +~18 tok on `ctx_read`'s schema for the new `paths` arg.
743    ///
744    /// #509 search consolidation (cont.): `ctx_search` now subsumes semantic
745    /// search + symbol lookup via an `action` enum, so `ctx_semantic_search` left
746    /// the core set (it + `ctx_symbol` are deprecated aliases). `ctx_search` grew
747    /// (~196 → ~318 tok) but the core total DROPPED (~2298 → ~2150, one fewer
748    /// tool), so the budgets were left unchanged with comfortable headroom.
749    ///
750    /// #578 schema diet: redundant per-property descriptions dropped (names +
751    /// enums self-explain), teaching paragraphs tightened, and `ctx_callgraph`
752    /// (~147 tok) replaced `ctx_graph` (~300 tok) in the lazy core so the
753    /// advertised set matches the injected INTENT playbook. Measured ~1685 tok
754    /// → budgets lowered 360→300 per tool, 2340→1780 total. What remains is
755    /// functional teaching (ctx_read mode enum, ctx_search action routing,
756    /// compose-first) — cut below this only with A/B efficacy evidence.
757    ///
758    /// Bumped to 2050 total for #1008: `ctx_patch` (anchored editing, ~263 tok
759    /// after its schema diet) joined the lazy core so the injected "edit after
760    /// reading → ctx_patch" rule points at an advertised tool. This is the
761    /// worst case (no client quirks): clients with a reliable native editor
762    /// (Cursor, Zed, Windsurf, …) skip `ctx_patch` via `ClientQuirks` and stay
763    /// at the previous ~1685-tok surface.
764    ///
765    /// Bumped to 2060 for #870: `ctx_search` gained `exclude`/`exclude_pattern`
766    /// negative filters (+~7 tok on its schema).
767    ///
768    /// Bumped to 370/2500 for #871: `ctx_search` gained `queries` batch mode
769    /// and restored full action descriptions. Tool correctness > token savings —
770    /// incomplete descriptions cause agents to misuse parameters.
771    ///
772    /// Bumped to 410/3000 for #1020: `ctx_patch` gained per-op JSON Schema
773    /// if/then conditionals so required params are discoverable pre-call.
774    #[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    // ── Hook-covered clients get LazyCore (#1474) ──────────────
828
829    #[test]
830    fn hook_covered_gets_lazy_core_not_shadow_only() {
831        // GH #1474: hook_covered=true no longer restricts to ShadowOnly
832        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}