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/// Computes the tool set this install advertises to a default client
205/// (no client quirks, no role restriction, no workflow gate, static tool list),
206/// including the live description compression. Offline counterpart of the
207/// `tools/list` handler for `doctor overhead` / `ContextOverhead::measure` —
208/// kept next to the pure gates so measurement cannot drift from policy.
209/// "No quirks" is the worst case: a client without a native editor sees
210/// `ctx_patch` too, so the reported overhead never understates.
211#[must_use]
212pub fn advertised_tool_defs_default() -> Vec<rmcp::model::Tool> {
213    let cfg = crate::core::config::Config::load();
214    let disabled = cfg.disabled_tools_effective();
215    let profile = cfg.tool_profile_effective();
216    let full_mode = crate::tool_defs::is_full_mode();
217    let registry = crate::server::registry::build_registry();
218
219    let candidate = candidate_set(&CandidateInputs {
220        full_mode,
221        unified_env: std::env::var("LEAN_CTX_UNIFIED").is_ok(),
222        explicit_profile: explicit_profile(&cfg),
223        hook_covered: false, // offline measurement uses worst-case (no hook coverage)
224    });
225    let pool: Vec<rmcp::model::Tool> = match candidate {
226        CandidateSet::Full | CandidateSet::ProfileAuthoritative => registry.tool_defs(),
227        CandidateSet::Unified => crate::tool_defs::unified_tool_defs(),
228        // GH #1474: ShadowOnly no longer returned; treat as LazyCore.
229        CandidateSet::ShadowOnly | CandidateSet::LazyCore => {
230            let core = crate::tool_defs::core_tool_names();
231            registry
232                .tool_defs()
233                .into_iter()
234                .filter(|t| core.contains(&t.name.as_ref()))
235                .collect()
236        }
237    };
238
239    let mut tools: Vec<_> = pool
240        .into_iter()
241        .filter(|t| {
242            is_tool_visible(
243                t.name.as_ref(),
244                &profile,
245                &disabled,
246                ClientQuirks::default(),
247                true,
248            )
249        })
250        .collect();
251
252    let already = tools.iter().any(|t| t.name.as_ref() == INVOKER);
253    if needs_invoker(full_mode, already, true, &disabled)
254        && let Some(def) = registry
255            .tool_defs()
256            .into_iter()
257            .find(|t| t.name.as_ref() == INVOKER)
258    {
259        tools.push(def);
260    }
261
262    let level = crate::core::config::CompressionLevel::effective(&cfg);
263    let mode = crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(&level);
264    if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
265        return tools;
266    }
267    tools
268        .into_iter()
269        .map(|mut t| {
270            let compressed = crate::core::terse::mcp_compress::compress_description(
271                t.name.as_ref(),
272                t.description.as_deref().unwrap_or(""),
273                mode,
274            );
275            t.description = Some(compressed.into());
276            t
277        })
278        .collect()
279}
280
281/// Whether the lazy per-category gate should filter the advertised tool set.
282///
283/// The dynamic-tools category gate (load tools on demand, signalled via
284/// `notifications/tools/list_changed`) exists to keep the *default* lean-core
285/// surface small for capable clients. An explicit profile is the user's chosen,
286/// authoritative surface, so it must be advertised in full — otherwise category
287/// gating silently drops profile-enabled tools (e.g. Standard's
288/// `ctx_architecture` / `ctx_semantic_search`) for clients like Codex, and the
289/// advertised set stops matching `lean-ctx tools show` (#358).
290#[must_use]
291pub fn category_gate_applies(supports_list_changed: bool, explicit_profile: bool) -> bool {
292    supports_list_changed && !explicit_profile
293}
294
295/// Whether [`INVOKER`] must be force-added to the advertised set.
296///
297/// True only in non-full mode when it isn't already present, the role permits
298/// it, and it isn't explicitly disabled. In full mode every tool is already
299/// listed, so no gateway is needed.
300#[must_use]
301pub fn needs_invoker(
302    full_mode: bool,
303    already_present: bool,
304    invoker_role_allowed: bool,
305    disabled: &[String],
306) -> bool {
307    !full_mode && !already_present && invoker_role_allowed && !disabled.iter().any(|d| d == INVOKER)
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    /// No client quirks — the default/measurement client.
315    fn no_quirks() -> ClientQuirks {
316        ClientQuirks::default()
317    }
318
319    #[test]
320    fn internal_tools_never_visible_even_in_power() {
321        // Power enables everything, but Internal/meta tools must still be hidden.
322        let p = ToolProfile::Power;
323        assert!(!is_tool_visible("ctx_metrics", &p, &[], no_quirks(), true));
324        assert!(!is_tool_visible("ctx_cost", &p, &[], no_quirks(), true));
325        assert!(!is_tool_visible(
326            "ctx_discover_tools",
327            &p,
328            &[],
329            no_quirks(),
330            true
331        ));
332    }
333
334    #[test]
335    fn deprecated_aliases_never_visible_even_in_power() {
336        // #509: folded read-cluster aliases are hidden from tools/list in every
337        // mode (Power enables everything) — but stay registered + callable.
338        let p = ToolProfile::Power;
339        assert!(!is_tool_visible(
340            "ctx_smart_read",
341            &p,
342            &[],
343            no_quirks(),
344            true
345        ));
346        assert!(!is_tool_visible(
347            "ctx_multi_read",
348            &p,
349            &[],
350            no_quirks(),
351            true
352        ));
353    }
354
355    #[test]
356    fn deprecated_aliases_stay_registered_and_callable() {
357        // The non-breaking contract (#509): hidden from the advertised surface,
358        // but still in the registry so direct calls and ctx_call keep working
359        // for one release. Removal is Phase 2.
360        let _guard = crate::core::data_dir::isolated_data_dir();
361        let defs = crate::server::registry::build_registry().registered_tool_defs();
362        for name in [
363            "ctx_smart_read",
364            "ctx_multi_read",
365            "ctx_semantic_search",
366            "ctx_symbol",
367        ] {
368            assert!(
369                defs.iter().any(|t| t.name.as_ref() == name),
370                "{name} must stay registered (callable) even though hidden"
371            );
372            assert!(
373                !is_tool_visible(name, &ToolProfile::Power, &[], no_quirks(), true),
374                "{name} must be hidden from tools/list"
375            );
376        }
377    }
378
379    #[test]
380    fn local_collaboration_tools_stay_callable_but_are_never_advertised() {
381        // The local bus/task/workflow substrate remains installed for existing
382        // local integrations. It is not a public coordination product, even in
383        // an explicitly pinned Power profile.
384        let defs = crate::server::registry::build_registry().registered_tool_defs();
385        for name in super::super::dynamic_tools::LOCAL_COLLABORATION_COMPATIBILITY_TOOLS {
386            assert!(
387                ToolProfile::Power.is_tool_enabled(name),
388                "{name} must remain directly compatible with Power callers"
389            );
390            assert!(
391                defs.iter().any(|tool| tool.name.as_ref() == *name),
392                "{name} must stay registered for local compatibility"
393            );
394            assert!(
395                !is_tool_visible(name, &ToolProfile::Power, &[], no_quirks(), true),
396                "{name} must not be advertised from tools/list"
397            );
398        }
399    }
400
401    #[test]
402    fn core_tool_visible_under_power() {
403        assert!(is_tool_visible(
404            "ctx_read",
405            &ToolProfile::Power,
406            &[],
407            no_quirks(),
408            true
409        ));
410    }
411
412    #[test]
413    fn standard_exposes_its_advertised_tools() {
414        // These are in STANDARD_TOOLS but were dropped by the old
415        // `core ∩ standard` intersection. Profile-authoritative resolution must
416        // surface them.
417        let p = ToolProfile::Standard;
418        assert!(is_tool_visible("ctx_execute", &p, &[], no_quirks(), true));
419        assert!(is_tool_visible("ctx_explore", &p, &[], no_quirks(), true));
420        assert!(is_tool_visible("ctx_callgraph", &p, &[], no_quirks(), true));
421        assert!(is_tool_visible("ctx_graph", &p, &[], no_quirks(), true));
422        // #1008: anchored editing ships with the pinned Standard profile.
423        assert!(is_tool_visible("ctx_patch", &p, &[], no_quirks(), true));
424    }
425
426    #[test]
427    fn folded_search_aliases_never_visible() {
428        // #509: ctx_semantic_search + ctx_symbol are consolidated into ctx_search
429        // (action=…). Hidden from tools/list in every mode, but stay callable.
430        let p = ToolProfile::Power;
431        assert!(!is_tool_visible(
432            "ctx_semantic_search",
433            &p,
434            &[],
435            no_quirks(),
436            true
437        ));
438        assert!(!is_tool_visible("ctx_symbol", &p, &[], no_quirks(), true));
439        assert!(is_tool_visible("ctx_search", &p, &[], no_quirks(), true));
440    }
441
442    #[test]
443    fn minimal_hides_non_minimal_tools() {
444        let p = ToolProfile::Minimal;
445        assert!(is_tool_visible("ctx_read", &p, &[], no_quirks(), true));
446        assert!(!is_tool_visible(
447            "ctx_architecture",
448            &p,
449            &[],
450            no_quirks(),
451            true
452        ));
453    }
454
455    #[test]
456    fn disabled_list_filters() {
457        let disabled = vec!["ctx_read".to_string()];
458        assert!(!is_tool_visible(
459            "ctx_read",
460            &ToolProfile::Power,
461            &disabled,
462            no_quirks(),
463            true
464        ));
465    }
466
467    #[test]
468    fn zed_hides_ctx_edit_only() {
469        let p = ToolProfile::Power;
470        let zed = ClientQuirks {
471            hide_ctx_edit: true,
472            hide_ctx_patch: false,
473        };
474        assert!(!is_tool_visible("ctx_edit", &p, &[], zed, true));
475        assert!(is_tool_visible("ctx_read", &p, &[], zed, true));
476    }
477
478    #[test]
479    fn native_editor_quirk_hides_ctx_patch_only() {
480        // #1008: a native-editor client in the lazy default drops ctx_patch —
481        // and nothing else.
482        let p = ToolProfile::Power;
483        let native = ClientQuirks {
484            hide_ctx_edit: false,
485            hide_ctx_patch: true,
486        };
487        assert!(!is_tool_visible("ctx_patch", &p, &[], native, true));
488        assert!(is_tool_visible("ctx_read", &p, &[], native, true));
489        assert!(is_tool_visible("ctx_edit", &p, &[], native, true));
490    }
491
492    #[test]
493    fn quirks_resolution_is_client_and_candidate_aware() {
494        // Native-editor clients skip ctx_patch in the lazy default…
495        for client in ["Cursor", "zed 0.164", "Windsurf", "antigravity", "opencode"] {
496            let q = ClientQuirks::resolve(client, CandidateSet::LazyCore);
497            assert!(q.hide_ctx_patch, "{client}: lazy core must hide ctx_patch");
498        }
499        // …clients without a reliable native editor get it (#637: Claude Code's
500        // read-before-write guard breaks under the read-redirect hook).
501        for client in ["claude-code", "CodeBuddy", "pi", "", "my-sdk-harness"] {
502            let q = ClientQuirks::resolve(client, CandidateSet::LazyCore);
503            assert!(
504                !q.hide_ctx_patch,
505                "{client:?}: lazy core must show ctx_patch"
506            );
507        }
508        // A pinned profile is client-agnostic — never hide ctx_patch there.
509        for candidate in [
510            CandidateSet::ProfileAuthoritative,
511            CandidateSet::Full,
512            CandidateSet::Unified,
513        ] {
514            let q = ClientQuirks::resolve("Cursor", candidate);
515            assert!(
516                !q.hide_ctx_patch,
517                "{candidate:?}: pinned/full surfaces are client-agnostic"
518            );
519        }
520        // The Zed ctx_edit quirk is independent of the candidate set.
521        assert!(ClientQuirks::resolve("zed", CandidateSet::Full).hide_ctx_edit);
522        assert!(!ClientQuirks::resolve("Cursor", CandidateSet::Full).hide_ctx_edit);
523    }
524
525    #[test]
526    fn role_block_hides_tool() {
527        assert!(!is_tool_visible(
528            "ctx_read",
529            &ToolProfile::Power,
530            &[],
531            no_quirks(),
532            false
533        ));
534    }
535
536    #[test]
537    fn category_gate_only_in_default_lean_mode() {
538        // Lazy gate applies only when the client supports list_changed AND no
539        // explicit profile is set.
540        assert!(category_gate_applies(true, false));
541        // Explicit profile is authoritative — never gated (#358).
542        assert!(!category_gate_applies(true, true));
543        // Static-list clients are never gated regardless of profile.
544        assert!(!category_gate_applies(false, false));
545        assert!(!category_gate_applies(false, true));
546    }
547
548    #[test]
549    fn invoker_added_when_missing_in_lazy_mode() {
550        assert!(needs_invoker(false, false, true, &[]));
551    }
552
553    #[test]
554    fn invoker_not_added_in_full_mode() {
555        assert!(!needs_invoker(true, false, true, &[]));
556    }
557
558    #[test]
559    fn invoker_not_duplicated_when_present() {
560        assert!(!needs_invoker(false, true, true, &[]));
561    }
562
563    #[test]
564    fn invoker_respects_role_and_disabled() {
565        assert!(!needs_invoker(false, false, false, &[]));
566        assert!(!needs_invoker(
567            false,
568            false,
569            true,
570            &["ctx_call".to_string()]
571        ));
572    }
573
574    /// #576 schema diet: the lazy-core surface is the default fixed cost every
575    /// session pays — keep it bounded. Per-tool cap keeps any single schema
576    /// from bloating; the total cap keeps the whole advertised surface lean.
577    /// (Raw registry defs, before description compression — worst case.)
578    ///
579    /// The total grew with the 14th core tool, `ctx_semantic_search` (#422):
580    /// it joined the lean core so agents discover semantic search by default
581    /// instead of never reaching for it. The per-tool cap (300) still guards
582    /// individual bloat; the total budget is sized to that 14-tool surface.
583    ///
584    /// Bumped to 2260 for #432: `ctx_read` now advertises the `offset`/`limit`
585    /// aliases (so agents trained on the native Read tool discover them), a
586    /// deliberate +~32 tok. Descriptions are kept terse to limit the cost.
587    ///
588    /// Bumped to 2275 for #451: `ctx_shell` now states it runs the system shell
589    /// profile-free (no rc/profile sourced), a deliberate +~13 tok so agents stop
590    /// mistaking it for a config-loaded interactive bash. Kept to one terse clause.
591    ///
592    /// Bumped to per-tool 335 / total 2310 for #513: `ctx_read` now documents the
593    /// verbatim escape hatch (`raw=true` arg + `raw` mode) so agents — especially
594    /// non-Opus models that fought the compression — discover how to get exact
595    /// bytes for review/audit instead of guessing. `ctx_read` is the richest core
596    /// tool and is the only one that crosses 300; the per-tool cap still guards
597    /// every other tool from bloat. Kept to terse clauses (+~33 tok on ctx_read).
598    ///
599    /// Bumped to per-tool 360 / total 2340 for #509: `ctx_read` absorbs the
600    /// `ctx_multi_read` batch capability via a `paths` array, so two tools collapse
601    /// into one (`ctx_smart_read` + `ctx_multi_read` are now deprecated aliases
602    /// hidden from the surface). The net effect REDUCES the advertised surface; the
603    /// only local cost is +~18 tok on `ctx_read`'s schema for the new `paths` arg.
604    ///
605    /// #509 search consolidation (cont.): `ctx_search` now subsumes semantic
606    /// search + symbol lookup via an `action` enum, so `ctx_semantic_search` left
607    /// the core set (it + `ctx_symbol` are deprecated aliases). `ctx_search` grew
608    /// (~196 → ~318 tok) but the core total DROPPED (~2298 → ~2150, one fewer
609    /// tool), so the budgets were left unchanged with comfortable headroom.
610    ///
611    /// #578 schema diet: redundant per-property descriptions dropped (names +
612    /// enums self-explain), teaching paragraphs tightened, and `ctx_callgraph`
613    /// (~147 tok) replaced `ctx_graph` (~300 tok) in the lazy core so the
614    /// advertised set matches the injected INTENT playbook. Measured ~1685 tok
615    /// → budgets lowered 360→300 per tool, 2340→1780 total. What remains is
616    /// functional teaching (ctx_read mode enum, ctx_search action routing,
617    /// compose-first) — cut below this only with A/B efficacy evidence.
618    ///
619    /// Bumped to 2050 total for #1008: `ctx_patch` (anchored editing, ~263 tok
620    /// after its schema diet) joined the lazy core so the injected "edit after
621    /// reading → ctx_patch" rule points at an advertised tool. This is the
622    /// worst case (no client quirks): clients with a reliable native editor
623    /// (Cursor, Zed, Windsurf, …) skip `ctx_patch` via `ClientQuirks` and stay
624    /// at the previous ~1685-tok surface.
625    ///
626    /// Bumped to 2060 for #870: `ctx_search` gained `exclude`/`exclude_pattern`
627    /// negative filters (+~7 tok on its schema).
628    ///
629    /// Bumped to 370/2500 for #871: `ctx_search` gained `queries` batch mode
630    /// and restored full action descriptions. Tool correctness > token savings —
631    /// incomplete descriptions cause agents to misuse parameters.
632    ///
633    /// Bumped to 410/3000 for #1020: `ctx_patch` gained per-op JSON Schema
634    /// if/then conditionals so required params are discoverable pre-call.
635    #[test]
636    fn core_tool_surface_stays_within_budget() {
637        const PER_TOOL_BUDGET: usize = 410;
638        const TOTAL_BUDGET: usize = 3000;
639
640        let _guard = crate::core::data_dir::isolated_data_dir();
641        let core = crate::tool_defs::core_tool_names();
642        let defs: Vec<_> = crate::server::registry::build_registry()
643            .tool_defs()
644            .into_iter()
645            .filter(|t| core.contains(&t.name.as_ref()))
646            .collect();
647        assert_eq!(defs.len(), core.len(), "every core tool must be registered");
648
649        let mut total = 0usize;
650        for t in &defs {
651            let desc = t.description.as_deref().unwrap_or("");
652            let schema = serde_json::to_string(&t.input_schema).unwrap_or_default();
653            let cost = crate::core::tokens::count_tokens(desc)
654                + crate::core::tokens::count_tokens(&schema);
655            eprintln!("{:24} {cost:4} tok", t.name.as_ref());
656            assert!(
657                cost <= PER_TOOL_BUDGET,
658                "{} costs {cost} tok (budget {PER_TOOL_BUDGET}) — trim its description/schema",
659                t.name
660            );
661            total += cost;
662        }
663        eprintln!("CORE TOTAL: {total} tok / {} tools", defs.len());
664        assert!(
665            total <= TOTAL_BUDGET,
666            "core surface costs {total} tok (budget {TOTAL_BUDGET})"
667        );
668    }
669
670    #[test]
671    fn resolve_auto_returns_non_auto_unchanged() {
672        assert_eq!(
673            resolve_auto_profile(&ToolProfile::Power),
674            ToolProfile::Power
675        );
676        assert_eq!(
677            resolve_auto_profile(&ToolProfile::Minimal),
678            ToolProfile::Minimal
679        );
680    }
681
682    #[test]
683    fn resolve_auto_resolves_to_concrete_profile() {
684        let resolved = resolve_auto_profile(&ToolProfile::Auto);
685        assert_ne!(resolved, ToolProfile::Auto);
686    }
687
688    // ── Hook-covered clients get LazyCore (#1474) ──────────────
689
690    #[test]
691    fn hook_covered_gets_lazy_core_not_shadow_only() {
692        // GH #1474: hook_covered=true no longer restricts to ShadowOnly
693        let c = candidate_set(&CandidateInputs {
694            full_mode: false,
695            unified_env: false,
696            explicit_profile: false,
697            hook_covered: true,
698        });
699        assert_eq!(c, CandidateSet::LazyCore);
700    }
701
702    #[test]
703    fn shadow_only_overridden_by_full_mode() {
704        let c = candidate_set(&CandidateInputs {
705            full_mode: true,
706            unified_env: false,
707            explicit_profile: false,
708            hook_covered: true,
709        });
710        assert_eq!(
711            c,
712            CandidateSet::Full,
713            "LEAN_CTX_FULL_TOOLS=1 must override shadow-only"
714        );
715    }
716
717    #[test]
718    fn shadow_only_overridden_by_explicit_profile() {
719        let c = candidate_set(&CandidateInputs {
720            full_mode: false,
721            unified_env: false,
722            explicit_profile: true,
723            hook_covered: true,
724        });
725        assert_eq!(
726            c,
727            CandidateSet::ProfileAuthoritative,
728            "explicit profile must override shadow-only"
729        );
730    }
731
732    #[test]
733    fn lazy_core_when_not_hook_covered() {
734        let c = candidate_set(&CandidateInputs {
735            full_mode: false,
736            unified_env: false,
737            explicit_profile: false,
738            hook_covered: false,
739        });
740        assert_eq!(
741            c,
742            CandidateSet::LazyCore,
743            "non-hook client must get LazyCore"
744        );
745    }
746}