bamboo-domain 2026.10.21

Domain models and shared types for the Bamboo agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Provider-neutral capability loading policy and classified tool catalogs.
//!
//! Provider adapters lower these logical classes to their own wire protocols.
//! The schema itself deliberately stays free of Anthropic/OpenAI fields.

use std::collections::{BTreeMap, BTreeSet};

use crate::{
    canonical_tool_name, FunctionSchema, ToolSchema, DISCOVER_CAPABILITY_NAME,
    MAX_DISCOVERY_QUERY_CHARS, MAX_DISCOVERY_RESULTS,
};

/// The loading class of a callable function schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CapabilityLoadingClass {
    /// Always present in the initial callable function set.
    Core,
    /// Eligible for discovery/loading; legacy providers may still receive it.
    Deferred,
    /// Retained for host compatibility but never advertised to a model.
    HostOnly,
}

/// How the current provider surface interprets eligible function schemas.
///
/// The default deliberately preserves Bamboo's existing full-catalog behavior.
/// Provider adapters opt into `Progressive` explicitly; an empty loaded-name
/// set cannot distinguish a progressive first round from a legacy request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CapabilityLoadingMode {
    #[default]
    LegacyFullCatalog,
    Progressive,
    /// Compatibility path for providers without native deferred-tool search.
    /// The top-level catalog stays fixed at Core plus Bamboo's synthetic
    /// discovery function while loaded definitions live in conversation
    /// history.
    StickyFallback,
}

/// The complete and intentionally small always-resident function surface.
///
/// `session_history_current` is a distinct least-privilege identity. Keeping it
/// Core guarantees exact current-Session recall after older activation traces
/// leave the active context without making the broad Root `session_history`
/// viewer Core.
pub const CORE_TOOL_NAMES: [&str; 13] = [
    "exec_command",
    "write_stdin",
    "Read",
    "Grep",
    "Edit",
    "Write",
    "session_history_current",
    // Host registers these only when the opt-in Supervisor scope exists.
    "work_overview",
    "work_search",
    "work_inspect",
    "work_changes",
    "work_update",
    "work_dispatch",
];

/// Host protocol helpers that must not enter model catalogs or discovery.
pub const HOST_ONLY_TOOL_NAMES: [&str; 6] = [
    "Workspace",
    "request_permissions",
    "Bash",
    "BashInput",
    "BashOutput",
    "KillShell",
];

/// Examples whose deferred status is part of the public migration contract.
pub const EXPLICIT_DEFERRED_TOOL_NAMES: [&str; 8] = [
    "Glob",
    "GetFileInfo",
    "ViewImage",
    "load_skill",
    "workflow_run",
    "update_goal",
    "loop_control",
    "session_message",
];

/// Reserved provider-safe function name used only by Bamboo's compatibility
/// fallback adapter. Native provider search items map to the logical gateway
/// directly and do not use this function identity.
pub const DISCOVERY_CONTROL_FALLBACK_TOOL_NAME: &str = "discover_capabilities";

/// Complete, bounded function schema used by the compatibility fallback.
///
/// This schema is synthesized after ordinary catalog classification because
/// its reserved name must never be accepted as an executor-backed tool.
pub fn discovery_control_fallback_schema() -> ToolSchema {
    ToolSchema {
        schema_type: "function".to_string(),
        function: FunctionSchema {
            name: DISCOVERY_CONTROL_FALLBACK_TOOL_NAME.to_string(),
            description: "Search eligible Deferred tools by name, description, and parameter metadata; load complete callable definitions into conversation history. Explicit kinds may request the legacy Skill/Workflow catalog.".to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "additionalProperties": false,
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Capability name or concise task description.",
                        "maxLength": MAX_DISCOVERY_QUERY_CHARS
                    },
                    "kinds": {
                        "type": "array",
                        "description": "Defaults to Tools. Include skill or workflow explicitly for compatibility catalog lookup.",
                        "items": {
                            "type": "string",
                            "enum": ["tool", "skill", "workflow"]
                        },
                        "maxItems": 3,
                        "uniqueItems": true
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of relevant matches.",
                        "minimum": 1,
                        "maximum": MAX_DISCOVERY_RESULTS
                    }
                },
                "required": ["query"]
            }),
        },
    }
}

/// Trusted marker for Bamboo's separate, always-resident discovery gateway.
///
/// It is intentionally not constructed from a function schema or inferred by
/// name: a custom function called `discover` must remain ordinary Deferred
/// input and must not gain control-plane privileges.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DiscoveryControlGateway {
    _private: (),
}

impl DiscoveryControlGateway {
    pub const fn logical_name(self) -> &'static str {
        DISCOVER_CAPABILITY_NAME
    }

    pub const fn fallback_tool_name(self) -> &'static str {
        DISCOVERY_CONTROL_FALLBACK_TOOL_NAME
    }

    pub const fn is_initially_visible(self) -> bool {
        true
    }
}

pub const DISCOVERY_CONTROL_GATEWAY: DiscoveryControlGateway =
    DiscoveryControlGateway { _private: () };

/// Classify a host/model reference after canonical alias resolution.
///
/// This function is intentionally reference-oriented: callers that classify a
/// registered schema, build a logical catalog, or make admission decisions must
/// use [`ClassifiedToolIdentity`] / [`ClassifiedToolSchema`] instead. Their
/// exact-first registration semantics prevent a custom exact `bash` or
/// `apply_patch` registration from inheriting Core policy from a builtin alias.
/// Unknown references deliberately remain Deferred so a new builtin, server
/// overlay, plugin, desktop, MCP, or custom tool cannot silently expand the
/// always-resident surface.
pub fn capability_loading_class_for_reference(name: &str) -> CapabilityLoadingClass {
    let canonical = canonical_tool_name(name);
    if CORE_TOOL_NAMES
        .iter()
        .any(|core| core.eq_ignore_ascii_case(&canonical))
    {
        CapabilityLoadingClass::Core
    } else if HOST_ONLY_TOOL_NAMES
        .iter()
        .any(|host_only| host_only.eq_ignore_ascii_case(&canonical))
    {
        CapabilityLoadingClass::HostOnly
    } else {
        CapabilityLoadingClass::Deferred
    }
}

/// Immutable policy identity derived from a registered schema name.
///
/// Logical catalog identity, and the intended executor key, follow the
/// registered schema name exactly. Concrete executor routing is migrated in a
/// follow-up slice before loaded-state admission is enabled.
/// Alias fallback is retained separately because the shared resolution contract
/// is exact-first. Thus a custom exact `apply_patch` is a Deferred custom tool,
/// while an unshadowed invocation reference `apply_patch` may still resolve to
/// builtin `Edit`.
///
/// Classification is lexical policy, not implementation provenance: exact
/// reserved spellings select Bamboo's reserved loading class, but this wrapper
/// does not attest that the underlying implementation is a framework builtin.
/// Current registrars are host-trusted; any future untrusted registrar needs an
/// authoritative origin boundary before it may claim reserved names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClassifiedToolIdentity {
    execution_name: String,
    alias_fallback_name: String,
    loading_class: CapabilityLoadingClass,
}

impl ClassifiedToolIdentity {
    pub fn from_schema_name(schema_name: &str) -> Option<Self> {
        let registered_name = schema_name.trim();
        if registered_name.is_empty() || registered_name != schema_name {
            return None;
        }
        let alias_fallback_name = canonical_tool_name(registered_name);
        if alias_fallback_name == DISCOVERY_CONTROL_FALLBACK_TOOL_NAME {
            return None;
        }
        let exact_framework_identity = crate::BUILTIN_TOOL_NAMES
            .iter()
            .chain(crate::SERVER_CAPABILITY_NAMES.iter())
            .any(|known| *known == registered_name);
        let loading_class = if exact_framework_identity {
            capability_loading_class_for_reference(registered_name)
        } else if capability_loading_class_for_reference(&alias_fallback_name)
            == CapabilityLoadingClass::HostOnly
        {
            // Host protocol identities and their legacy aliases stay outside
            // every model catalog even when an exact custom registration would
            // otherwise shadow alias fallback.
            CapabilityLoadingClass::HostOnly
        } else {
            CapabilityLoadingClass::Deferred
        };
        Some(Self {
            execution_name: registered_name.to_string(),
            alias_fallback_name,
            loading_class,
        })
    }

    /// Exact registered name used as the logical catalog and executor key.
    /// This is deliberately not alias-canonicalized.
    pub fn execution_name(&self) -> &str {
        &self.execution_name
    }

    pub fn loading_class(&self) -> CapabilityLoadingClass {
        self.loading_class
    }

    pub fn alias_fallback_name(&self) -> &str {
        &self.alias_fallback_name
    }
}

/// Resolve a reference against the exact registered execution identities in a
/// catalog. Exact registrations win; only a missing exact name may fall back to
/// the shared legacy/builtin alias resolver.
///
/// The caller supplies the catalog membership predicate so config, discovery,
/// provider projection, and later admission can share these semantics without
/// coupling the domain policy to one collection type.
pub fn resolve_tool_reference_name(
    reference: &str,
    mut contains_registered_name: impl FnMut(&str) -> bool,
) -> Option<String> {
    let exact = reference.trim();
    if exact.is_empty() {
        return None;
    }
    if contains_registered_name(exact) {
        return Some(exact.to_string());
    }

    let unqualified = exact.rsplit("::").next().unwrap_or(exact).trim();
    if unqualified != exact && contains_registered_name(unqualified) {
        return Some(unqualified.to_string());
    }

    let legacy_normalized = crate::normalize_builtin_alias(unqualified);
    if legacy_normalized != unqualified && contains_registered_name(legacy_normalized) {
        return Some(legacy_normalized.to_string());
    }

    let fallback = canonical_tool_name(exact);
    (!fallback.is_empty() && contains_registered_name(&fallback)).then_some(fallback)
}

/// A logical catalog entry carrying provider-neutral loading policy alongside
/// an otherwise unchanged function schema.
#[derive(Clone)]
pub struct ClassifiedToolSchema {
    identity: ClassifiedToolIdentity,
    schema: ToolSchema,
}

impl std::fmt::Debug for ClassifiedToolSchema {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ClassifiedToolSchema")
            .field("execution_name", &self.execution_name())
            .field("loading_class", &self.loading_class())
            .finish_non_exhaustive()
    }
}

impl ClassifiedToolSchema {
    /// Classify one non-empty function schema. Blank names fail closed rather
    /// than entering a provider or discovery catalog.
    pub fn new(schema: ToolSchema) -> Option<Self> {
        let identity = ClassifiedToolIdentity::from_schema_name(&schema.function.name)?;
        Some(Self { identity, schema })
    }

    pub fn execution_name(&self) -> &str {
        self.identity.execution_name()
    }

    pub fn loading_class(&self) -> CapabilityLoadingClass {
        self.identity.loading_class()
    }

    pub fn alias_fallback_name(&self) -> &str {
        self.identity.alias_fallback_name()
    }

    pub fn schema(&self) -> &ToolSchema {
        &self.schema
    }

    pub fn into_schema(self) -> ToolSchema {
        self.schema
    }

    pub fn is_model_visible(&self) -> bool {
        self.loading_class() != CapabilityLoadingClass::HostOnly
    }

    pub fn is_initially_visible(&self) -> bool {
        self.loading_class() == CapabilityLoadingClass::Core
    }
}

/// Provider-neutral callable membership at one conversation position.
///
/// Function identities use exact registered execution names. The complete
/// catalog name set is retained separately from the callable subset so an
/// unloaded exact registration still shadows legacy alias fallback. Bamboo's
/// trusted discovery gateway is intentionally exposed through its typed marker
/// rather than inserted as a string: an ordinary custom function named
/// `discover` remains Deferred.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectiveCallableSet {
    catalog_execution_names: BTreeSet<String>,
    callable_execution_names: BTreeSet<String>,
}

impl EffectiveCallableSet {
    /// Resolve callable membership from an already eligible classified catalog.
    ///
    /// `loaded_execution_names` is the provider-adapter boundary: adapters
    /// extract names from their validated native/fallback history and this pure
    /// resolver canonicalizes them against the exact catalog, deduplicates them,
    /// and ignores unknown or HostOnly references. It neither parses provider
    /// payloads nor persists a second loaded-state representation.
    pub fn from_catalog<'a>(
        catalog: &[ClassifiedToolSchema],
        mode: CapabilityLoadingMode,
        loaded_execution_names: impl IntoIterator<Item = &'a str>,
    ) -> Self {
        let catalog_by_execution_name = catalog
            .iter()
            .map(|entry| (entry.execution_name(), entry))
            .collect::<BTreeMap<_, _>>();
        let catalog_execution_names = catalog_by_execution_name
            .keys()
            .map(|name| (*name).to_string())
            .collect::<BTreeSet<_>>();

        let mut callable_execution_names = catalog
            .iter()
            .filter(|entry| match mode {
                CapabilityLoadingMode::LegacyFullCatalog => entry.is_model_visible(),
                CapabilityLoadingMode::Progressive | CapabilityLoadingMode::StickyFallback => {
                    entry.is_initially_visible()
                }
            })
            .map(|entry| entry.execution_name().to_string())
            .collect::<BTreeSet<_>>();

        if matches!(
            mode,
            CapabilityLoadingMode::Progressive | CapabilityLoadingMode::StickyFallback
        ) {
            for loaded_reference in loaded_execution_names {
                let Some(execution_name) = resolve_tool_reference_name(loaded_reference, |name| {
                    catalog_by_execution_name.contains_key(name)
                }) else {
                    continue;
                };
                let Some(entry) = catalog_by_execution_name.get(execution_name.as_str()) else {
                    continue;
                };
                if entry.loading_class() == CapabilityLoadingClass::Deferred {
                    callable_execution_names.insert(execution_name);
                }
            }
        }

        Self {
            catalog_execution_names,
            callable_execution_names,
        }
    }

    /// Exact execution-name membership for provider projection and admission.
    pub fn contains_execution_name(&self, execution_name: &str) -> bool {
        self.callable_execution_names.contains(execution_name)
    }

    /// Resolve a model reference exact-first against the complete catalog, then
    /// admit it only when that exact identity belongs to the callable subset.
    pub fn resolve_callable_reference(&self, reference: &str) -> Option<String> {
        let execution_name = resolve_tool_reference_name(reference, |name| {
            self.catalog_execution_names.contains(name)
        })?;
        self.callable_execution_names
            .contains(&execution_name)
            .then_some(execution_name)
    }

    /// Callable function execution names in deterministic order.
    pub fn execution_names(&self) -> impl Iterator<Item = &str> {
        self.callable_execution_names.iter().map(String::as_str)
    }

    /// Bamboo's separate trusted discovery control surface.
    pub const fn discovery_gateway(&self) -> DiscoveryControlGateway {
        DISCOVERY_CONTROL_GATEWAY
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        FunctionSchema, BUILTIN_TOOL_ALIASES, BUILTIN_TOOL_NAMES, LEGACY_TOOL_NAME_ALIASES,
        SERVER_CAPABILITY_NAMES,
    };
    use serde_json::json;

    fn schema(name: &str) -> ToolSchema {
        ToolSchema {
            schema_type: "function".to_string(),
            function: FunctionSchema {
                name: name.to_string(),
                description: format!("{name} description"),
                parameters: json!({"type": "object"}),
            },
        }
    }

    #[test]
    fn locks_exact_core_and_separate_discovery_gateway() {
        assert_eq!(
            CORE_TOOL_NAMES,
            [
                "exec_command",
                "write_stdin",
                "Read",
                "Grep",
                "Edit",
                "Write",
                "session_history_current",
                "work_overview",
                "work_search",
                "work_inspect",
                "work_changes",
                "work_update",
                "work_dispatch",
            ]
        );
        for name in CORE_TOOL_NAMES {
            assert_eq!(
                capability_loading_class_for_reference(name),
                CapabilityLoadingClass::Core
            );
        }
        assert_eq!(DISCOVERY_CONTROL_GATEWAY.logical_name(), "discover");
        assert_eq!(
            DISCOVERY_CONTROL_GATEWAY.fallback_tool_name(),
            "discover_capabilities"
        );
        assert_ne!(
            DISCOVERY_CONTROL_GATEWAY.logical_name(),
            DISCOVERY_CONTROL_GATEWAY.fallback_tool_name()
        );
        assert!(DISCOVERY_CONTROL_GATEWAY.is_initially_visible());
        assert_eq!(
            capability_loading_class_for_reference(DISCOVER_CAPABILITY_NAME),
            CapabilityLoadingClass::Deferred,
            "the control gateway is outside the function Core set"
        );
        let ordinary_function = ClassifiedToolSchema::new(schema(DISCOVER_CAPABILITY_NAME))
            .expect("ordinary function schema");
        assert_eq!(
            ordinary_function.loading_class(),
            CapabilityLoadingClass::Deferred
        );
        assert!(!ordinary_function.is_initially_visible());
        assert!(ClassifiedToolSchema::new(schema(DISCOVERY_CONTROL_FALLBACK_TOOL_NAME)).is_none());
        assert!(ClassifiedToolSchema::new(schema("default::discover_capabilities")).is_none());
    }

    #[test]
    fn fallback_discovery_schema_is_reserved_complete_and_bounded() {
        let schema = discovery_control_fallback_schema();
        assert_eq!(schema.schema_type, "function");
        assert_eq!(schema.function.name, DISCOVERY_CONTROL_FALLBACK_TOOL_NAME);
        assert_eq!(
            schema.function.parameters["properties"]["query"]["maxLength"],
            MAX_DISCOVERY_QUERY_CHARS
        );
        assert_eq!(
            schema.function.parameters["properties"]["limit"]["maximum"],
            MAX_DISCOVERY_RESULTS
        );
        assert_eq!(
            schema.function.parameters["properties"]["kinds"]["items"]["enum"],
            serde_json::json!(["tool", "skill", "workflow"])
        );
        assert_eq!(schema.function.parameters["additionalProperties"], false);
        assert!(ClassifiedToolSchema::new(schema).is_none());
    }

    #[test]
    fn every_known_function_has_fail_closed_loading_policy() {
        for name in BUILTIN_TOOL_NAMES {
            let expected = if CORE_TOOL_NAMES.contains(&name) {
                CapabilityLoadingClass::Core
            } else if HOST_ONLY_TOOL_NAMES.contains(&name) {
                CapabilityLoadingClass::HostOnly
            } else {
                CapabilityLoadingClass::Deferred
            };
            assert_eq!(
                capability_loading_class_for_reference(name),
                expected,
                "{name}"
            );
        }
        for name in SERVER_CAPABILITY_NAMES {
            let expected = if CORE_TOOL_NAMES.contains(&name) {
                CapabilityLoadingClass::Core
            } else {
                CapabilityLoadingClass::Deferred
            };
            assert_eq!(
                capability_loading_class_for_reference(name),
                expected,
                "server overlay {name} has the wrong loading class"
            );
        }
        assert_eq!(
            capability_loading_class_for_reference("session_history"),
            CapabilityLoadingClass::Deferred,
            "the privileged Root-compatible identity must remain Deferred"
        );
    }

    #[test]
    fn locks_required_deferred_and_host_only_names() {
        for name in EXPLICIT_DEFERRED_TOOL_NAMES {
            assert_eq!(
                capability_loading_class_for_reference(name),
                CapabilityLoadingClass::Deferred
            );
        }
        for name in HOST_ONLY_TOOL_NAMES {
            assert_eq!(
                capability_loading_class_for_reference(name),
                CapabilityLoadingClass::HostOnly
            );
        }
    }

    #[test]
    fn all_declared_aliases_share_their_target_classification() {
        for (alias, target) in BUILTIN_TOOL_ALIASES {
            assert_eq!(
                canonical_tool_name(alias),
                canonical_tool_name(target),
                "{alias}"
            );
            assert_eq!(
                capability_loading_class_for_reference(alias),
                capability_loading_class_for_reference(target),
                "{alias} -> {target}"
            );
        }
        assert_eq!(
            capability_loading_class_for_reference("applyPatch"),
            CapabilityLoadingClass::Core
        );
        assert_eq!(
            capability_loading_class_for_reference("default::getCurrentDir"),
            CapabilityLoadingClass::HostOnly
        );
        assert_eq!(
            capability_loading_class_for_reference("default::sub_task"),
            CapabilityLoadingClass::Deferred
        );
        for (alias, normalized) in LEGACY_TOOL_NAME_ALIASES {
            assert_eq!(
                canonical_tool_name(alias),
                canonical_tool_name(normalized),
                "legacy spelling {alias}"
            );
            assert_eq!(
                capability_loading_class_for_reference(alias),
                capability_loading_class_for_reference(normalized),
                "legacy spelling {alias}"
            );
        }
    }

    #[test]
    fn unknown_dynamic_and_namespaced_mcp_tools_default_deferred() {
        for name in [
            "future_builtin",
            "default::desktop_capture",
            "plugin_custom_tool",
            "mcp__alpha__read_file",
            "mcp__beta__read_file",
        ] {
            assert_eq!(
                capability_loading_class_for_reference(name),
                CapabilityLoadingClass::Deferred
            );
        }
    }

    #[test]
    fn exact_custom_alias_registrations_remain_deferred_execution_identities() {
        for name in [
            "apply_patch",
            "applyPatch",
            "read_file",
            "Exec_Command",
            "default::exec_command",
        ] {
            let identity = ClassifiedToolIdentity::from_schema_name(name)
                .expect("exact custom registration remains catalogued");
            assert_eq!(identity.execution_name(), name);
            assert_eq!(
                identity.loading_class(),
                CapabilityLoadingClass::Deferred,
                "custom exact registration {name} must not gain reserved policy"
            );
        }
        let host_alias =
            ClassifiedToolIdentity::from_schema_name("GetCurrentDir").expect("host alias identity");
        assert_eq!(host_alias.execution_name(), "GetCurrentDir");
        assert_eq!(host_alias.loading_class(), CapabilityLoadingClass::HostOnly);
        assert_eq!(
            ClassifiedToolIdentity::from_schema_name("exec_command")
                .expect("canonical builtin")
                .loading_class(),
            CapabilityLoadingClass::Core
        );
        assert_eq!(
            ClassifiedToolIdentity::from_schema_name("session_history_current")
                .expect("canonical current-history capability")
                .loading_class(),
            CapabilityLoadingClass::Core
        );
        assert_eq!(
            ClassifiedToolIdentity::from_schema_name("Session_History_Current")
                .expect("case-variant custom registration")
                .loading_class(),
            CapabilityLoadingClass::Deferred,
            "only the exact registered framework identity may inherit Core policy"
        );
    }

    #[test]
    fn legacy_shell_tools_remain_host_only_and_new_terminal_tools_are_core() {
        for name in [
            "Bash",
            "BashInput",
            "BashOutput",
            "KillShell",
            "execute_command",
            "bash",
            "default::Bash",
        ] {
            let identity = ClassifiedToolIdentity::from_schema_name(name).unwrap();
            assert_eq!(
                identity.loading_class(),
                CapabilityLoadingClass::HostOnly,
                "{name}"
            );
            assert!(!ClassifiedToolSchema::new(schema(name))
                .unwrap()
                .is_model_visible());
        }
        for name in ["exec_command", "write_stdin"] {
            let identity = ClassifiedToolIdentity::from_schema_name(name).unwrap();
            assert_eq!(identity.execution_name(), name);
            assert_eq!(identity.loading_class(), CapabilityLoadingClass::Core);
        }
    }

    #[test]
    fn namespaced_custom_registration_stays_exact_and_reference_fallback_is_catalog_aware() {
        let classified = ClassifiedToolSchema::new(schema("default::custom_tool"))
            .expect("generic executors may expose exact namespaced schemas");
        assert_eq!(classified.execution_name(), "default::custom_tool");
        assert_eq!(classified.schema().function.name, "default::custom_tool");
        assert_eq!(classified.alias_fallback_name(), "custom_tool");
        assert_eq!(classified.loading_class(), CapabilityLoadingClass::Deferred);

        let registered = ["Bash", "custom_tool"];
        assert_eq!(
            resolve_tool_reference_name("default::Bash", |name| registered.contains(&name)),
            Some("Bash".to_string())
        );
        assert_eq!(
            resolve_tool_reference_name("default::custom_tool", |name| registered.contains(&name)),
            Some("custom_tool".to_string())
        );
    }

    #[test]
    fn catalog_reference_resolution_is_exact_first_then_alias_fallback() {
        let shadowed = ["Edit", "apply_patch", "default::applyPatch"];
        assert_eq!(
            resolve_tool_reference_name("Edit", |name| shadowed.contains(&name)),
            Some("Edit".to_string())
        );
        assert_eq!(
            resolve_tool_reference_name("apply_patch", |name| shadowed.contains(&name)),
            Some("apply_patch".to_string())
        );
        assert_eq!(
            resolve_tool_reference_name("applyPatch", |name| shadowed.contains(&name)),
            Some("apply_patch".to_string())
        );
        assert_eq!(
            resolve_tool_reference_name("default::applyPatch", |name| shadowed.contains(&name)),
            Some("default::applyPatch".to_string())
        );

        let shadowed_without_namespaced_exact = ["Edit", "apply_patch"];
        assert_eq!(
            resolve_tool_reference_name("default::applyPatch", |name| {
                shadowed_without_namespaced_exact.contains(&name)
            }),
            Some("apply_patch".to_string())
        );

        let unshadowed = ["Edit"];
        assert_eq!(
            resolve_tool_reference_name("apply_patch", |name| unshadowed.contains(&name)),
            Some("Edit".to_string())
        );
        assert_eq!(
            resolve_tool_reference_name("default::applyPatch", |name| unshadowed.contains(&name)),
            Some("Edit".to_string())
        );
        assert_eq!(
            resolve_tool_reference_name("unknown", |name| unshadowed.contains(&name)),
            None
        );
    }

    #[test]
    fn classified_wrapper_keeps_schema_provider_neutral() {
        let classified = ClassifiedToolSchema::new(schema("Edit")).expect("classified schema");
        assert_eq!(classified.execution_name(), "Edit");
        assert_eq!(classified.loading_class(), CapabilityLoadingClass::Core);
        assert!(classified.is_model_visible());
        assert!(classified.is_initially_visible());

        let serialized = serde_json::to_value(classified.schema()).expect("serialize schema");
        assert_eq!(serialized["function"]["name"], "Edit");
        assert!(serialized.get("loading_class").is_none());
        assert!(serialized.get("defer_loading").is_none());
    }

    #[test]
    fn host_only_wrapper_is_not_model_visible() {
        let classified = ClassifiedToolSchema::new(schema("Workspace")).expect("classified schema");
        assert_eq!(classified.execution_name(), "Workspace");
        assert_eq!(classified.loading_class(), CapabilityLoadingClass::HostOnly);
        assert!(!classified.is_model_visible());
        assert!(!classified.is_initially_visible());
    }

    #[test]
    fn blank_schema_names_fail_closed() {
        assert!(ClassifiedToolSchema::new(schema("  ")).is_none());
    }

    #[test]
    fn classified_debug_never_emits_schema_content() {
        const SECRET: &str = "private-classified-schema-sentinel";
        let mut sensitive = schema("custom_tool");
        sensitive.schema_type = SECRET.to_string();
        sensitive.function.description = SECRET.to_string();
        sensitive.function.parameters = json!({"secret": SECRET});
        let classified = ClassifiedToolSchema::new(sensitive).expect("classified schema");
        let debug = format!("{classified:?}");

        assert!(!debug.contains(SECRET));
        assert!(debug.contains("custom_tool"));
        assert!(debug.contains("Deferred"));
    }

    fn classified_catalog(names: &[&str]) -> Vec<ClassifiedToolSchema> {
        names
            .iter()
            .map(|name| schema(name))
            .filter_map(ClassifiedToolSchema::new)
            .collect()
    }

    #[test]
    fn legacy_effective_set_keeps_core_and_deferred_but_excludes_host_only() {
        let catalog = classified_catalog(&["Read", "Glob", "custom_tool", "Workspace"]);
        let effective = EffectiveCallableSet::from_catalog(
            &catalog,
            CapabilityLoadingMode::LegacyFullCatalog,
            std::iter::empty::<&str>(),
        );

        assert_eq!(
            effective.execution_names().collect::<Vec<_>>(),
            vec!["Glob", "Read", "custom_tool"]
        );
        assert_eq!(effective.discovery_gateway(), DISCOVERY_CONTROL_GATEWAY);
        assert!(effective.discovery_gateway().is_initially_visible());
    }

    #[test]
    fn progressive_effective_set_adds_only_loaded_eligible_deferred() {
        let catalog = classified_catalog(&["Read", "Glob", "custom_tool", "Workspace"]);
        let effective = EffectiveCallableSet::from_catalog(
            &catalog,
            CapabilityLoadingMode::Progressive,
            ["Glob", "Workspace", "unknown_tool", "Glob"],
        );

        assert_eq!(
            effective.execution_names().collect::<Vec<_>>(),
            vec!["Glob", "Read"]
        );
        assert!(!effective.contains_execution_name("custom_tool"));
        assert!(!effective.contains_execution_name("Workspace"));
        assert!(!effective.contains_execution_name("unknown_tool"));
    }

    #[test]
    fn sticky_fallback_effective_set_matches_progressive_core_plus_loaded_semantics() {
        let catalog = classified_catalog(&["Read", "Glob", "custom_tool", "Workspace"]);
        let sticky = EffectiveCallableSet::from_catalog(
            &catalog,
            CapabilityLoadingMode::StickyFallback,
            ["Glob", "Workspace", "unknown_tool", "Glob"],
        );

        assert_eq!(
            sticky.execution_names().collect::<Vec<_>>(),
            vec!["Glob", "Read"]
        );
        assert!(!sticky.contains_execution_name("custom_tool"));
        assert!(!sticky.contains_execution_name("Workspace"));
        assert!(!sticky.contains_execution_name("unknown_tool"));
    }

    #[test]
    fn self_history_current_is_core_without_activating_broad_history() {
        let catalog = classified_catalog(&["Read", "session_history", "session_history_current"]);

        for mode in [
            CapabilityLoadingMode::Progressive,
            CapabilityLoadingMode::StickyFallback,
        ] {
            let effective =
                EffectiveCallableSet::from_catalog(&catalog, mode, std::iter::empty::<&str>());
            assert!(effective.contains_execution_name("Read"));
            assert!(effective.contains_execution_name("session_history_current"));
            assert!(!effective.contains_execution_name("session_history"));
            assert_eq!(
                effective.resolve_callable_reference("session_history_current"),
                Some("session_history_current".to_string())
            );
            assert_eq!(
                effective.resolve_callable_reference("session_history"),
                None
            );
        }
    }

    #[test]
    fn callable_reference_resolution_preserves_exact_shadow_before_alias_fallback() {
        let catalog = classified_catalog(&["Edit", "apply_patch"]);
        let core_only = EffectiveCallableSet::from_catalog(
            &catalog,
            CapabilityLoadingMode::Progressive,
            std::iter::empty::<&str>(),
        );

        assert_eq!(
            core_only.resolve_callable_reference("Edit"),
            Some("Edit".to_string())
        );
        assert_eq!(core_only.resolve_callable_reference("apply_patch"), None);
        assert_eq!(core_only.resolve_callable_reference("applyPatch"), None);

        let with_custom = EffectiveCallableSet::from_catalog(
            &catalog,
            CapabilityLoadingMode::Progressive,
            ["apply_patch"],
        );
        assert_eq!(
            with_custom.resolve_callable_reference("apply_patch"),
            Some("apply_patch".to_string())
        );
        assert_eq!(
            with_custom.resolve_callable_reference("applyPatch"),
            Some("apply_patch".to_string())
        );
    }

    #[test]
    fn trusted_discovery_gateway_is_separate_from_deferred_discover_function() {
        let catalog = classified_catalog(&["discover"]);
        let effective = EffectiveCallableSet::from_catalog(
            &catalog,
            CapabilityLoadingMode::Progressive,
            std::iter::empty::<&str>(),
        );

        assert_eq!(effective.resolve_callable_reference("discover"), None);
        assert_eq!(effective.discovery_gateway().logical_name(), "discover");
        assert!(effective.discovery_gateway().is_initially_visible());
    }
}