bamboo-engine 2026.10.13

Execution engine and orchestration 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
use crate::runtime::config::AgentLoopConfig;
use bamboo_agent_core::tools::{ToolExecutor, ToolSchema};
use bamboo_agent_core::Session;
use bamboo_domain::{
    resolve_disabled_tool_reference_name, CapabilityLoadingClass, CapabilityLoadingMode,
    ClassifiedToolIdentity, ClassifiedToolSchema, EffectiveCallableSet, SessionKind,
};
#[cfg(test)]
use bamboo_skills::runtime_metadata::{
    SKILL_RUNTIME_SELECTED_SKILL_IDS_KEY, SKILL_RUNTIME_SELECTION_SOURCE_KEY,
};
use bamboo_tools::exposure::{activated_discoverable_tools, expandable_tool_short_description};

const EXPOSURE_SIGNATURE: &str = "prompt_tool_exposure_signature";
const EXPOSURE_ACTIVATED: &str = "prompt_tool_exposure_activated";
const PHYSICAL_SUBAGENT_TOOLS: [&str; 3] = ["ask_agent", "deploy_agent", "cluster"];

pub(crate) fn effective_guide_activation(
    config: &AgentLoopConfig,
    session: &Session,
) -> std::collections::BTreeSet<String> {
    let mut activated = if config.freeze_tool_exposure_for_cache {
        session
            .metadata
            .get(EXPOSURE_ACTIVATED)
            .and_then(|raw| serde_json::from_str(raw).ok())
            .unwrap_or_else(|| activated_discoverable_tools(session))
    } else {
        activated_discoverable_tools(session)
    };
    // Ultra Roots and trusted Supervisors rely on delegation, so its contract
    // must be visible even if guide exposure froze before the mode was selected.
    // This derived presentation policy neither persists user activation nor
    // changes the live catalog or execution authority.
    if session.model_orchestration_only_enabled() {
        activated.insert("SubAgent".to_string());
    }
    activated
}

/// Capture presentation only; the catalog and execution authority are rebuilt live.
pub(crate) fn resolve_tool_schemas_for_round(
    config: &AgentLoopConfig,
    tools: &dyn ToolExecutor,
    session: &mut Session,
) -> Vec<ToolSchema> {
    if config.freeze_tool_exposure_for_cache {
        use sha2::{Digest, Sha256};
        let catalog = resolve_catalog_with_activation(
            config,
            tools,
            session,
            &std::collections::BTreeSet::new(),
        );
        let schemas = catalog
            .iter()
            .map(|entry| entry.schema())
            .collect::<Vec<_>>();
        let value = serde_json::to_value(schemas).expect("tool schemas serialize");
        let bytes =
            bamboo_llm::providers::common::tool_schema::canonicalize_json_value(&value).to_string();
        let signature = Sha256::digest(bytes.as_bytes())
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>();
        if session.metadata.get(EXPOSURE_SIGNATURE) != Some(&signature) {
            session
                .metadata
                .insert(EXPOSURE_SIGNATURE.into(), signature);
            session.metadata.insert(
                EXPOSURE_ACTIVATED.into(),
                serde_json::to_string(&activated_discoverable_tools(session))
                    .expect("activation names serialize"),
            );
        }
    } else {
        session.metadata.remove(EXPOSURE_SIGNATURE);
        session.metadata.remove(EXPOSURE_ACTIVATED);
    }
    resolve_available_tool_schemas_for_session(config, tools, session)
}

/// A persisted session already inside the legacy PlanMode state machine keeps
/// `ExitPlanMode` as its recovery path. New sessions use delegated `Plan` only.
fn prefer_delegated_plan_tool(
    session: &Session,
    catalog: &mut std::collections::BTreeMap<String, ClassifiedToolSchema>,
) {
    if !catalog.contains_key("Plan") {
        return;
    }

    let legacy_plan_active = session
        .agent_runtime_state
        .as_ref()
        .is_some_and(|state| state.plan_mode.is_some());
    if legacy_plan_active {
        catalog.remove("Plan");
    } else {
        catalog.remove("ExitPlanMode");
    }
}

pub(crate) fn resolve_available_tool_schemas_for_session(
    config: &AgentLoopConfig,
    tools: &dyn ToolExecutor,
    session: &Session,
) -> Vec<ToolSchema> {
    let catalog = resolve_classified_tool_catalog_for_session(config, tools, session);
    let effective = EffectiveCallableSet::from_catalog(
        &catalog,
        CapabilityLoadingMode::LegacyFullCatalog,
        std::iter::empty::<&str>(),
    );
    catalog
        .into_iter()
        .filter(|entry| effective.contains_execution_name(entry.execution_name()))
        .map(ClassifiedToolSchema::into_schema)
        .collect()
}

/// Resolve the provider-neutral logical catalog for one round.
///
/// Legacy providers project every model-visible Deferred entry from this
/// catalog. Native/fallback progressive-loading adapters later consume the same
/// classification and may project only initially visible entries. HostOnly
/// entries remain represented for host compatibility but never cross the model
/// catalog projection above.
pub(crate) fn resolve_classified_tool_catalog_for_session(
    config: &AgentLoopConfig,
    tools: &dyn ToolExecutor,
    session: &Session,
) -> Vec<ClassifiedToolSchema> {
    resolve_catalog_with_activation(
        config,
        tools,
        session,
        &effective_guide_activation(config, session),
    )
}

fn resolve_catalog_with_activation(
    config: &AgentLoopConfig,
    tools: &dyn ToolExecutor,
    session: &Session,
    activated: &std::collections::BTreeSet<String>,
) -> Vec<ClassifiedToolSchema> {
    let mut tool_schemas = config.tool_registry.list_tools();
    if tool_schemas.is_empty() {
        tool_schemas = tools.list_tools();
    }

    tool_schemas.extend(config.additional_tool_schemas.clone());
    tool_schemas.sort_by(|left, right| left.function.name.cmp(&right.function.name));
    tool_schemas.dedup_by(|left, right| left.function.name == right.function.name);
    if config.ticket_worker_plan.is_some() {
        // Ticket native execution has a Host file capability rather than the
        // ambient Builtin Read/Write schema. Keep catalog and executor identical.
        tool_schemas = tools.list_tools();
        for schema in tool_schemas
            .iter_mut()
            .filter(|s| s.function.name == "Task")
        {
            schema.function.description = "Update only this Assignment's private Steps. Include question:{prompt} with tasks to durably ask a User question and end this one-shot run. Answers arrive in a fresh Assignment's versioned context; a question never confers approval.".into();
            schema.function.parameters["properties"]["question"] = serde_json::json!({"type":"object","additionalProperties":false,"required":["prompt"],"properties":{"prompt":{"type":"string","minLength":1,"maxLength":2048}}});
        }
    }
    // Resolve the disabled set LIVE each round (#136): when a resolver is wired
    // (server path) a tool disabled/re-enabled mid-run takes effect on the next
    // round, because this list is rebuilt unfiltered every round; with no resolver
    // (SDK/tests) this is the frozen per-run snapshot (#44), unchanged.
    let (disabled_tools, _disabled_skill_ids) = config.resolve_disabled_filters();
    // Self control is host-opt-in and uses ordinary authority filtering below.
    if config.loop_control.is_none() {
        tool_schemas.retain(|schema| {
            schema.function.name != bamboo_tools::tools::loop_control::LOOP_CONTROL_TOOL_NAME
        });
    }
    // The `update_goal` self-report tool is only meaningful while the autonomous
    // goal loop is active; hide it from every ordinary session so it never
    // tempts the model when no goal is set.
    if !config.goal_loop_active() {
        tool_schemas.retain(|schema| {
            schema.function.name != bamboo_tools::tools::goal::UPDATE_GOAL_TOOL_NAME
        });
    }

    super::legacy_instruction::retain_terminal_activation_tools(session, &mut tool_schemas);

    // Legacy providers keep Deferred schemas visible during migration;
    // activation only controls the depth of the existing tool-guide summaries.
    for schema in &mut tool_schemas {
        let Some(identity) = ClassifiedToolIdentity::from_schema_name(&schema.function.name) else {
            continue;
        };
        let guide_name = identity.alias_fallback_name();
        if identity.loading_class() == CapabilityLoadingClass::Deferred
            && !activated.contains(guide_name)
        {
            if let Some(short) = expandable_tool_short_description(guide_name) {
                schema.function.description =
                    format!("[Discoverable — not fully activated] {}", short);
            }
        }
    }

    if session.supervisor_incarnation_id().is_some() {
        for schema in tool_schemas
            .iter_mut()
            .filter(|schema| schema.function.name == "SubAgent")
        {
            schema.function.description = format!(
                "Supervisor: delegate execution, including simple implementation tasks; retain only necessary dedicated read-only acquisition and orchestration here. If no suitable authorized worker is available, report the actual recoverable blocker instead of self-executing or repeatedly creating children. {}",
                schema.function.description,
            );
        }
        for schema in tool_schemas
            .iter_mut()
            .filter(|schema| schema.function.name == "session_history")
        {
            schema.function.description = "Bounded history/metadata readback for this Supervisor or an explicitly attached independent Root in its current valid Project/lifetime scope. Use read_messages/get_meta. Global list/search is not available; use session_history_current for current-turn paging.".into();
            schema.function.parameters["properties"]["action"]["enum"] =
                serde_json::json!(["read_messages", "get_meta"]);
        }
    }

    let mut by_execution_name = std::collections::BTreeMap::<String, ClassifiedToolSchema>::new();
    for entry in tool_schemas
        .into_iter()
        .filter_map(ClassifiedToolSchema::new)
    {
        let key = entry.execution_name().to_string();
        match by_execution_name.entry(key) {
            std::collections::btree_map::Entry::Vacant(slot) => {
                slot.insert(entry);
            }
            std::collections::btree_map::Entry::Occupied(_) => {}
        }
    }
    let disabled_execution_names = disabled_tools
        .iter()
        .filter_map(|reference| {
            resolve_disabled_tool_reference_name(reference, |name| {
                by_execution_name.contains_key(name)
            })
        })
        .flat_map(|name| {
            let replacement = bamboo_domain::legacy_shell_replacement(&name).map(str::to_owned);
            std::iter::once(name).chain(replacement)
        })
        .collect::<std::collections::BTreeSet<_>>();
    by_execution_name.retain(|name, _| !disabled_execution_names.contains(name));
    prefer_delegated_plan_tool(session, &mut by_execution_name);
    // Root and Child models delegate through the logical SubAgent facade. Keep the
    // physical broker/deployment tools registered for existing direct callers,
    // but omit their schemas (including namespaced aliases) from every Root/Child
    // model catalog and capability-discovery projection.
    if matches!(session.kind, SessionKind::Root | SessionKind::Child) {
        by_execution_name
            .retain(|_, entry| !PHYSICAL_SUBAGENT_TOOLS.contains(&entry.alias_fallback_name()));
    }
    // Apply the durable Root authority to exact registered execution names.
    // This catalog feeds both provider schemas and capability discovery, so
    // aliases and custom registrations cannot reintroduce a denied tool.
    by_execution_name.retain(|name, _| session.allows_model_tool_execution(name));

    let mut catalog = by_execution_name.into_values().collect::<Vec<_>>();
    catalog.sort_by(|left, right| {
        left.schema()
            .function
            .name
            .cmp(&right.schema().function.name)
    });

    catalog
}

#[cfg(test)]
mod live_disabled_tests {
    use super::*;
    use bamboo_agent_core::tools::{
        FunctionSchema, ToolCall, ToolError, ToolExecutionContext, ToolResult,
    };
    use std::collections::BTreeSet;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

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

    fn plan_catalog() -> std::collections::BTreeMap<String, ClassifiedToolSchema> {
        ["Plan", "ExitPlanMode", "Read"]
            .into_iter()
            .map(schema)
            .filter_map(ClassifiedToolSchema::new)
            .map(|entry| (entry.execution_name().to_string(), entry))
            .collect()
    }

    #[test]
    fn delegated_plan_hides_legacy_exit_for_inactive_sessions() {
        let session = Session::new("s", "m");
        let mut catalog = plan_catalog();

        prefer_delegated_plan_tool(&session, &mut catalog);

        assert_eq!(
            catalog.keys().map(String::as_str).collect::<Vec<_>>(),
            vec!["Plan", "Read"]
        );
    }

    #[test]
    fn delegated_plan_preserves_exit_for_an_active_legacy_session() {
        let mut session = Session::new("s", "m");
        let runtime = session
            .agent_runtime_state
            .get_or_insert_with(bamboo_domain::AgentRuntimeState::default);
        runtime.plan_mode = Some(bamboo_domain::PlanModeState {
            entered_at: chrono::Utc::now(),
            pre_permission_mode: "default".to_string(),
            plan_file_path: None,
            status: bamboo_domain::PlanModeStatus::Exploring,
        });
        let mut catalog = plan_catalog();

        prefer_delegated_plan_tool(&session, &mut catalog);

        assert_eq!(
            catalog.keys().map(String::as_str).collect::<Vec<_>>(),
            vec!["ExitPlanMode", "Read"]
        );
    }

    #[test]
    fn legacy_exit_remains_when_plan_is_not_available() {
        let session = Session::new("s", "m");
        let mut catalog = plan_catalog();
        catalog.remove("Plan");

        prefer_delegated_plan_tool(&session, &mut catalog);

        assert!(catalog.contains_key("ExitPlanMode"));
    }

    struct TwoTools;
    #[async_trait::async_trait]
    impl ToolExecutor for TwoTools {
        async fn execute(&self, _call: &ToolCall) -> Result<ToolResult, ToolError> {
            unreachable!("not invoked in this test")
        }
        async fn execute_with_context(
            &self,
            call: &ToolCall,
            _ctx: ToolExecutionContext<'_>,
        ) -> Result<ToolResult, ToolError> {
            self.execute(call).await
        }
        fn list_tools(&self) -> Vec<ToolSchema> {
            [
                "alpha_tool",
                "beta_tool",
                "load_skill",
                "Bash",
                "BashOutput",
                "exec_command",
                "write_stdin",
                "vendor::Bash",
            ]
            .into_iter()
            .map(schema)
            .collect()
        }
    }

    fn offered(config: &AgentLoopConfig, tools: &TwoTools, session: &Session, name: &str) -> bool {
        resolve_available_tool_schemas_for_session(config, tools, session)
            .iter()
            .any(|s| s.function.name == name)
    }

    #[test]
    fn live_disabled_resolver_filters_tools_on_the_next_round() {
        // A resolver whose disabled set flips mid-run: round 1 nothing disabled,
        // round 2 "beta_tool" disabled — mirrors a user disabling a tool mid-run.
        let disabled = Arc::new(AtomicBool::new(false));
        let d = disabled.clone();
        let mut config = AgentLoopConfig::default();
        config.disabled_filter_resolver = Some(Arc::new(move || {
            let tools = if d.load(Ordering::SeqCst) {
                BTreeSet::from(["beta_tool".to_string()])
            } else {
                BTreeSet::new()
            };
            (tools, BTreeSet::new())
        }));
        let session = Session::new("s", "m");
        let tools = TwoTools;

        // Round 1: nothing disabled -> beta_tool is offered.
        assert!(offered(&config, &tools, &session, "beta_tool"));

        // Disable beta_tool mid-run (NO new execution).
        disabled.store(true, Ordering::SeqCst);

        // Round 2 (same run): the live disable took effect -> beta_tool gone,
        // alpha_tool still offered. Re-enable would restore it (list rebuilt fresh).
        assert!(!offered(&config, &tools, &session, "beta_tool"));
        assert!(offered(&config, &tools, &session, "alpha_tool"));
    }

    #[test]
    fn legacy_disabled_shell_names_filter_replacements_without_foreign_suffix_fallback() {
        let tools = TwoTools;
        let session = Session::new("shell-policy", "m");
        let mut config = AgentLoopConfig::default();
        let present = |config: &AgentLoopConfig, name: &str| {
            resolve_classified_tool_catalog_for_session(config, &tools, &session)
                .iter()
                .any(|entry| entry.execution_name() == name)
        };
        config.disabled_tools = BTreeSet::from(["Bash".into(), "BashOutput".into()]);
        assert!(!present(&config, "exec_command"));
        assert!(!present(&config, "write_stdin"));

        config.disabled_tools = BTreeSet::from(["vendor::Bash".into()]);
        assert!(present(&config, "exec_command"));
        assert!(present(&config, "write_stdin"));
    }

    struct CanonicalShellTools;
    #[async_trait::async_trait]
    impl ToolExecutor for CanonicalShellTools {
        async fn execute(&self, _call: &ToolCall) -> Result<ToolResult, ToolError> {
            unreachable!("catalog projection only")
        }

        fn list_tools(&self) -> Vec<ToolSchema> {
            ["exec_command", "write_stdin", "vendor::Bash"]
                .into_iter()
                .map(schema)
                .collect()
        }
    }

    #[test]
    fn exact_legacy_denials_constrain_a_canonical_only_catalog() {
        let tools = CanonicalShellTools;
        let session = Session::new("canonical-shell-policy", "m");
        for (denied, exec_allowed, stdin_allowed, foreign_allowed) in [
            ("Bash", false, true, true),
            ("BashInput", true, false, true),
            ("BashOutput", true, false, true),
            ("KillShell", true, false, true),
            ("vendor::Bash", true, true, false),
            ("default::Bash", true, true, true),
            ("unregistered::Bash", true, true, true),
        ] {
            let mut config = AgentLoopConfig::default();
            config.disabled_tools = BTreeSet::from([denied.to_owned()]);
            let catalog = resolve_classified_tool_catalog_for_session(&config, &tools, &session);
            let present = |name| catalog.iter().any(|entry| entry.execution_name() == name);
            assert_eq!(present("exec_command"), exec_allowed, "{denied}");
            assert_eq!(present("write_stdin"), stdin_allowed, "{denied}");
            assert_eq!(present("vendor::Bash"), foreign_allowed, "{denied}");
        }
    }

    struct PositiveShellCatalog(&'static [&'static str]);

    #[async_trait::async_trait]
    impl ToolExecutor for PositiveShellCatalog {
        async fn execute(&self, _call: &ToolCall) -> Result<ToolResult, ToolError> {
            unreachable!("catalog projection only")
        }

        fn list_tools(&self) -> Vec<ToolSchema> {
            self.0.iter().map(|name| schema(name)).collect()
        }
    }

    fn shell_policy_catalog(
        tools: &dyn ToolExecutor,
        denied: &str,
    ) -> (BTreeSet<String>, EffectiveCallableSet) {
        let config = AgentLoopConfig {
            disabled_tools: BTreeSet::from([denied.to_owned()]),
            ..Default::default()
        };
        let session = Session::new("positive-shell-policy", "m");
        let catalog = resolve_classified_tool_catalog_for_session(&config, tools, &session);
        let callable = EffectiveCallableSet::from_catalog(
            &catalog,
            CapabilityLoadingMode::LegacyFullCatalog,
            std::iter::empty::<&str>(),
        );
        let names = catalog
            .iter()
            .map(|entry| entry.execution_name().to_owned())
            .collect();
        (names, callable)
    }

    #[test]
    fn supported_unqualified_legacy_alias_denials_constrain_pair_only_catalog_and_admission() {
        let tools = PositiveShellCatalog(&["exec_command", "write_stdin", "Read"]);
        for (denied, legacy, replacement) in [
            ("bash", "Bash", "exec_command"),
            ("bAsH", "Bash", "exec_command"),
            ("execute_command", "Bash", "exec_command"),
            ("bashinput", "BashInput", "write_stdin"),
            ("bAsHiNpUt", "BashInput", "write_stdin"),
            ("bashoutput", "BashOutput", "write_stdin"),
            ("bAsHoUtPuT", "BashOutput", "write_stdin"),
            ("killshell", "KillShell", "write_stdin"),
            ("kIlLsHeLl", "KillShell", "write_stdin"),
        ] {
            // These references are already accepted by the shared resolver;
            // compatibility must not invent an additional alias vocabulary.
            assert_eq!(
                bamboo_domain::resolve_tool_reference_name(denied, |name| name == legacy),
                Some(legacy.to_owned()),
                "unsupported test reference {denied}",
            );
            let (names, callable) = shell_policy_catalog(&tools, denied);
            assert!(!names.contains(replacement), "{denied}: {names:?}");
            assert!(
                callable.resolve_callable_reference(replacement).is_none(),
                "{denied} left {replacement} callable",
            );
            let other = if replacement == "exec_command" {
                "write_stdin"
            } else {
                "exec_command"
            };
            assert!(names.contains(other), "{denied} also disabled {other}");
            assert!(names.contains("Read"));
        }
    }

    #[test]
    fn missing_qualified_legacy_references_do_not_disable_pair_only_catalog_by_suffix() {
        let tools = PositiveShellCatalog(&["exec_command", "write_stdin", "Read"]);
        for denied in [
            "vendor::Bash",
            "vendor::bash",
            "vendor::execute_command",
            "default::Bash",
            "default::bashoutput",
            "vendor::KillShell",
            "EXECUTE_COMMAND",
        ] {
            let (names, _) = shell_policy_catalog(&tools, denied);
            for name in ["exec_command", "write_stdin", "Read"] {
                assert!(names.contains(name), "{denied} disabled {name}");
            }
        }
    }

    #[test]
    fn exact_custom_legacy_spellings_win_over_disabled_alias_fallback() {
        let tools = PositiveShellCatalog(&[
            "exec_command",
            "write_stdin",
            "Read",
            "bash",
            "execute_command",
            "vendor::Bash",
            "default::Bash",
            "default::execute_command",
        ]);
        for denied in [
            "bash",
            "execute_command",
            "vendor::Bash",
            "default::Bash",
            "default::execute_command",
        ] {
            let (names, _) = shell_policy_catalog(&tools, denied);
            assert!(
                !names.contains(denied),
                "exact denial was ignored: {denied}"
            );
            for name in ["exec_command", "write_stdin", "Read"] {
                assert!(names.contains(name), "{denied} disabled {name}");
            }
        }
    }

    #[test]
    fn explicit_degraded_activation_hides_load_skill_after_one_attempt() {
        let config = AgentLoopConfig::default();
        let tools = TwoTools;
        let mut session = Session::new("degraded", "m");
        session.metadata.insert(
            SKILL_RUNTIME_SELECTION_SOURCE_KEY.to_string(),
            "explicit".to_string(),
        );
        session.metadata.insert(
            SKILL_RUNTIME_SELECTED_SKILL_IDS_KEY.to_string(),
            r#"["review"]"#.to_string(),
        );

        assert!(offered(&config, &tools, &session, "load_skill"));
        session.metadata.insert(
            bamboo_skills::runtime_metadata::SKILL_RUNTIME_ACTIVATION_ERROR_KEY.to_string(),
            r#"{"code":"provider_failed"}"#.to_string(),
        );
        assert!(!offered(&config, &tools, &session, "load_skill"));
        assert!(!super::super::skill_context::explicit_activation_pending(
            &session
        ));
    }
}