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        lazy_core_surface(cfg.tool_profile_effective(), candidate),
219        &cfg.disabled_tools_effective(),
220        ClientQuirks::resolve(client_name, candidate),
221    )
222}
223
224/// The unpinned default resolves to `Power`, but `tools/list` advertises only
225/// `CORE_TOOL_NAMES` there; the rest is reached through `ctx_call`. Guidance
226/// written for `Power` named tools such as `ctx_knowledge` that OpenCode and
227/// other lazy-core clients never saw, and agents called them directly.
228fn 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/// Pure core of [`guidance_profile`]: `profile` minus every tool the surface
242/// withholds. `Auto` is taken at its starting point (minimal) — guidance is
243/// written once per session and must not promise a tool before escalation.
244#[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/// Computes the tool set this install advertises to a default client
268/// (no client quirks, no role restriction, no workflow gate, static tool list),
269/// including the live description compression. Offline counterpart of the
270/// `tools/list` handler for `doctor overhead` / `ContextOverhead::measure` —
271/// kept next to the pure gates so measurement cannot drift from policy.
272/// "No quirks" is the worst case: a client without a native editor sees
273/// `ctx_patch` too, so the reported overhead never understates.
274#[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, // offline measurement uses worst-case (no hook coverage)
287    });
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        // GH #1474: ShadowOnly no longer returned; treat as LazyCore.
292        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/// Whether the lazy per-category gate should filter the advertised tool set.
345///
346/// The dynamic-tools category gate (load tools on demand, signalled via
347/// `notifications/tools/list_changed`) exists to keep the *default* lean-core
348/// surface small for capable clients. An explicit profile is the user's chosen,
349/// authoritative surface, so it must be advertised in full — otherwise category
350/// gating silently drops profile-enabled tools (e.g. Standard's
351/// `ctx_architecture` / `ctx_semantic_search`) for clients like Codex, and the
352/// advertised set stops matching `lean-ctx tools show` (#358).
353#[must_use]
354pub fn category_gate_applies(supports_list_changed: bool, explicit_profile: bool) -> bool {
355    supports_list_changed && !explicit_profile
356}
357
358/// Whether [`INVOKER`] must be force-added to the advertised set.
359///
360/// True only in non-full mode when it isn't already present, the role permits
361/// it, and it isn't explicitly disabled. In full mode every tool is already
362/// listed, so no gateway is needed.
363#[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    /// No client quirks — the default/measurement client.
378    fn no_quirks() -> ClientQuirks {
379        ClientQuirks::default()
380    }
381
382    #[test]
383    fn internal_tools_never_visible_even_in_power() {
384        // Power enables everything, but Internal/meta tools must still be hidden.
385        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        // The local bus/task/workflow substrate remains installed for existing
400        // local integrations. It is not a public coordination product, even in
401        // an explicitly pinned Power profile.
402        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        // These are in STANDARD_TOOLS but were dropped by the old
433        // `core ∩ standard` intersection. Profile-authoritative resolution must
434        // surface them.
435        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        // #1008: anchored editing ships with the pinned Standard profile.
441        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        // #1008: a native-editor client in the lazy default drops ctx_patch —
477        // and nothing else.
478        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    /// Every tool the guidance names under `profile`, checked against the
489    /// same gate `tools/list` applies (#1849).
490    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        // #1849: `disabled_tools = ["ctx_callgraph"]` hid the tool from
508        // `tools/list`, but the instructions still said "ctx_callgraph (callers)".
509        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        // Nothing else is lost on the way.
528        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        // The unpinned default is `Power`, yet a lazy-core session (OpenCode,
535        // Cursor, …) is offered only CORE_TOOL_NAMES. Its rules named
536        // ctx_knowledge, which the agent then called and could not find.
537        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        // A pinned profile is authoritative and keeps its full set.
551        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        // #1849: `prefer_native_editor` folds ctx_patch into the disabled
560        // list; the native-editor quirk hides it on the lazy surface. Either
561        // way "if denied, use ctx_patch" points at a tool the agent lacks.
562        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        // Guidance is written once per session; Auto must not promise the
586        // tools it only escalates to later.
587        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        // Native-editor clients skip ctx_patch in the lazy default…
609        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        // …clients without a reliable native editor get it (#637: Claude Code's
614        // read-before-write guard breaks under the read-redirect hook).
615        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        // A pinned profile is client-agnostic — never hide ctx_patch there.
623        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        // The Zed ctx_edit quirk is independent of the candidate set.
635        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        // Lazy gate applies only when the client supports list_changed AND no
653        // explicit profile is set.
654        assert!(category_gate_applies(true, false));
655        // Explicit profile is authoritative — never gated (#358).
656        assert!(!category_gate_applies(true, true));
657        // Static-list clients are never gated regardless of profile.
658        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    /// #576 schema diet: the lazy-core surface is the default fixed cost every
689    /// session pays — keep it bounded. Per-tool cap keeps any single schema
690    /// from bloating; the total cap keeps the whole advertised surface lean.
691    /// (Raw registry defs, before description compression — worst case.)
692    ///
693    /// The total grew with the 14th core tool, `ctx_semantic_search` (#422):
694    /// it joined the lean core so agents discover semantic search by default
695    /// instead of never reaching for it. The per-tool cap (300) still guards
696    /// individual bloat; the total budget is sized to that 14-tool surface.
697    ///
698    /// Bumped to 2260 for #432: `ctx_read` now advertises the `offset`/`limit`
699    /// aliases (so agents trained on the native Read tool discover them), a
700    /// deliberate +~32 tok. Descriptions are kept terse to limit the cost.
701    ///
702    /// Bumped to 2275 for #451: `ctx_shell` now states it runs the system shell
703    /// profile-free (no rc/profile sourced), a deliberate +~13 tok so agents stop
704    /// mistaking it for a config-loaded interactive bash. Kept to one terse clause.
705    ///
706    /// Bumped to per-tool 335 / total 2310 for #513: `ctx_read` now documents the
707    /// verbatim escape hatch (`raw=true` arg + `raw` mode) so agents — especially
708    /// non-Opus models that fought the compression — discover how to get exact
709    /// bytes for review/audit instead of guessing. `ctx_read` is the richest core
710    /// tool and is the only one that crosses 300; the per-tool cap still guards
711    /// every other tool from bloat. Kept to terse clauses (+~33 tok on ctx_read).
712    ///
713    /// Bumped to per-tool 360 / total 2340 for #509: `ctx_read` absorbs the
714    /// `ctx_multi_read` batch capability via a `paths` array, so two tools collapse
715    /// into one (`ctx_smart_read` + `ctx_multi_read` are now deprecated aliases
716    /// hidden from the surface). The net effect REDUCES the advertised surface; the
717    /// only local cost is +~18 tok on `ctx_read`'s schema for the new `paths` arg.
718    ///
719    /// #509 search consolidation (cont.): `ctx_search` now subsumes semantic
720    /// search + symbol lookup via an `action` enum, so `ctx_semantic_search` left
721    /// the core set (it + `ctx_symbol` are deprecated aliases). `ctx_search` grew
722    /// (~196 → ~318 tok) but the core total DROPPED (~2298 → ~2150, one fewer
723    /// tool), so the budgets were left unchanged with comfortable headroom.
724    ///
725    /// #578 schema diet: redundant per-property descriptions dropped (names +
726    /// enums self-explain), teaching paragraphs tightened, and `ctx_callgraph`
727    /// (~147 tok) replaced `ctx_graph` (~300 tok) in the lazy core so the
728    /// advertised set matches the injected INTENT playbook. Measured ~1685 tok
729    /// → budgets lowered 360→300 per tool, 2340→1780 total. What remains is
730    /// functional teaching (ctx_read mode enum, ctx_search action routing,
731    /// compose-first) — cut below this only with A/B efficacy evidence.
732    ///
733    /// Bumped to 2050 total for #1008: `ctx_patch` (anchored editing, ~263 tok
734    /// after its schema diet) joined the lazy core so the injected "edit after
735    /// reading → ctx_patch" rule points at an advertised tool. This is the
736    /// worst case (no client quirks): clients with a reliable native editor
737    /// (Cursor, Zed, Windsurf, …) skip `ctx_patch` via `ClientQuirks` and stay
738    /// at the previous ~1685-tok surface.
739    ///
740    /// Bumped to 2060 for #870: `ctx_search` gained `exclude`/`exclude_pattern`
741    /// negative filters (+~7 tok on its schema).
742    ///
743    /// Bumped to 370/2500 for #871: `ctx_search` gained `queries` batch mode
744    /// and restored full action descriptions. Tool correctness > token savings —
745    /// incomplete descriptions cause agents to misuse parameters.
746    ///
747    /// Bumped to 410/3000 for #1020: `ctx_patch` gained per-op JSON Schema
748    /// if/then conditionals so required params are discoverable pre-call.
749    #[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    // ── Hook-covered clients get LazyCore (#1474) ──────────────
803
804    #[test]
805    fn hook_covered_gets_lazy_core_not_shadow_only() {
806        // GH #1474: hook_covered=true no longer restricts to ShadowOnly
807        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}