Skip to main content

agent_works/plugin/
loader.rs

1//! Plugin loading (the P2 load surface) — re-verification gate → build tools per form
2//! → disable per tool → three places cleaned on unload.
3//!
4//! Criteria (`notes/tool-socket-design.md`, "Plugin package mechanism" acceptance):
5//!
6//! - **Post-install tampering is refused**: re-verification [`PackageStatus::Tampered`] ⇒ **all** tools
7//!   of that plugin are disabled, reason = "…run `plugin add` again to re-review" ([`VerifyReport::user_message`]);
8//! - **Corruption does not skip the whole package**: missing .wasm (registry reports Broken) or
9//!   compile failure at load time ⇒ **that tool** is disabled, the rest of the same
10//!   package work as usual;
11//! - **Unload cleans three places**: the tool table ([`LoadedPlugin::identity_keys`] handed back to
12//!   the caller for unregistering) / the ledger ([`crate::approval_ledger::ApprovalLedger::remove_prefix`]) /
13//!   the registry ([`super::install::remove_plugin`]) — each has its own test;
14//! - **The mcp form belongs to the plugin**: server pins live in [`PluginMcpServer`] (connections are
15//!   made by the product layer, nothing written to connections.json); key assignment
16//!   disambiguates collisions with numeric suffixes ([`assign_mcp_tool_keys`]).
17//!
18//! The load surface **does not touch the network and does not spawn**: MCP only registers
19//! pins, scripts only register argv pins — the execution surfaces hang separately
20//! ([`crate::script_tool::ScriptTool`] / [`super::wasm::WasmTool`]).
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::path::Path;
24use std::sync::Arc;
25
26use agent_base::Tool;
27
28use super::manifest::{
29    PluginManifest, PluginToolSpec, ScriptToolSpec, WASM_DEFAULT_TIMEOUT_SECS, WasmToolSpec,
30};
31use super::registry::{PluginRegistry, ToolPin, ToolStatus, VerifyReport};
32use crate::script_tool::{ScriptTool, ScriptToolEntry};
33use crate::tool_provider::{NAME_SEGMENT_MAX, normalize_tool_segment};
34
35/// A disabled tool (post-install tampering / missing file / compile failure / not
36/// compiled in), with a reason the panel can report directly.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct DisabledTool {
39    /// identity key `plugin.{plugin}.{tool}`.
40    pub identity: String,
41    /// human-readable reason (shown directly by the panel / `/tools`).
42    pub reason: String,
43}
44
45/// Pin for a plugin-owned MCP server (nothing written to connections.json — it belongs
46/// to the plugin).
47///
48/// env / headers only contain `${ENV:VAR}` references (the registry's law; the product
49/// layer resolves and injects them).
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct PluginMcpServer {
52    /// the server label from the manifest (not part of the identity key).
53    pub label: String,
54    /// stdio form argv (in-package paths already absolutized).
55    pub command: Option<Vec<String>>,
56    /// environment variable overrides (only `${ENV:VAR}` references are stored).
57    pub env: BTreeMap<String, String>,
58    /// remote URL form.
59    pub url: Option<String>,
60    /// remote request headers (only `${ENV:VAR}` references are stored).
61    pub headers: BTreeMap<String, String>,
62}
63
64/// A loaded plugin package: usable tools + disabled list + re-verification report + own server pins.
65pub struct LoadedPlugin {
66    /// plugin name.
67    pub name: String,
68    /// re-verification report for this load (panel display / logging).
69    pub verify: VerifyReport,
70    /// usable tools (can be passed straight to `ToolRegistry::register_arc`).
71    pub tools: Vec<Arc<dyn Tool>>,
72    /// disabled tools (the product of not skipping the whole package on corruption).
73    pub disabled: Vec<DisabledTool>,
74    /// own MCP server pins (connections are made by the product layer).
75    pub mcp_servers: Vec<PluginMcpServer>,
76}
77
78impl LoadedPlugin {
79    /// All identity keys touched by this plugin (usable + disabled) — used to clean the
80    /// tool table on unload.
81    pub fn identity_keys(&self) -> Vec<String> {
82        self.tools
83            .iter()
84            .map(|t| t.name().to_string())
85            .chain(self.disabled.iter().map(|d| d.identity.clone()))
86            .collect()
87    }
88
89    /// One-line panel message (the tamper text from the re-verification report; Trusted = none).
90    pub fn user_message(&self) -> Option<String> {
91        self.verify.user_message()
92    }
93}
94
95/// Plugin loader: shares one wasm runtime across plugins (feature `wasm`).
96#[derive(Default)]
97pub struct PluginLoader {
98    #[cfg(feature = "wasm")]
99    wasm: Option<Arc<super::wasm::WasmRuntime>>,
100}
101
102impl PluginLoader {
103    /// Without a wasm runtime (wasm-form tools are disabled with the reason stated).
104    pub fn new() -> Self {
105        Self::default()
106    }
107
108    /// With a wasm runtime (one per process, shared across plugins).
109    #[cfg(feature = "wasm")]
110    pub fn with_wasm(runtime: Arc<super::wasm::WasmRuntime>) -> Self {
111        Self {
112            wasm: Some(runtime),
113        }
114    }
115
116    /// Load one plugin: re-verify → build tool by tool.
117    ///
118    /// - package-level tampering ⇒ disable everything (`tools` empty), reason = the
119    ///   re-verification text;
120    /// - a single tool missing/corrupt ⇒ that tool is disabled, the rest as usual;
121    /// - the load surface neither touches the network nor spawns: the mcp form only
122    ///   yields server pins.
123    pub fn load(&self, name: &str, registry: &PluginRegistry, plugins_root: &Path) -> LoadedPlugin {
124        let plugin_dir = plugins_root.join(name);
125        let verify = registry.verify_plugin(name, &plugin_dir);
126        let mut loaded = LoadedPlugin {
127            name: name.to_string(),
128            verify,
129            tools: Vec::new(),
130            disabled: Vec::new(),
131            mcp_servers: Vec::new(),
132        };
133
134        let Some(pin) = registry.get(name) else {
135            loaded.disabled.push(DisabledTool {
136                identity: format!("plugin.{name}"),
137                reason: "not installed (no registry pin)".to_string(),
138            });
139            return loaded;
140        };
141
142        // Post-install tampering ⇒ fail-closed, disable everything (don't read the manifest
143        // on disk — it is the very thing that was modified).
144        if loaded.verify.tampered() {
145            let reason = loaded
146                .verify
147                .user_message()
148                .unwrap_or_else(|| "plugin has been modified".to_string());
149            for tool in &pin.tools {
150                loaded.disabled.push(DisabledTool {
151                    identity: tool.identity(name),
152                    reason: reason.clone(),
153                });
154            }
155            return loaded;
156        }
157
158        // Trusted ⇒ the manifest content is what the pinned hash corresponds to
159        // (re-verification already checked the hash).
160        let manifest = match std::fs::read_to_string(plugin_dir.join("plugin.json"))
161            .map_err(|e| e.to_string())
162            .and_then(|raw| PluginManifest::from_json(&raw).map_err(|e| e.to_string()))
163        {
164            Ok(m) => m,
165            Err(e) => {
166                // Hash matches but the file is unreadable = impossible path; still fail-closed
167                // to disabling everything.
168                for tool in &pin.tools {
169                    loaded.disabled.push(DisabledTool {
170                        identity: tool.identity(name),
171                        reason: format!("manifest unreadable: {e}"),
172                    });
173                }
174                return loaded;
175            }
176        };
177
178        let pins: BTreeMap<String, &ToolPin> = pin
179            .tools
180            .iter()
181            .map(|t| (t.identity(name), t))
182            .collect::<BTreeMap<_, _>>();
183        // Per-tool load status (missing → Broken).
184        let mut tool_status: BTreeMap<String, ToolStatus> = BTreeMap::new();
185        for (identity, status) in &loaded.verify.tools {
186            tool_status.insert(identity.clone(), status.clone());
187        }
188
189        for spec in &manifest.tools {
190            let identity = match spec.identity(name) {
191                Ok(key) => key,
192                Err(e) => {
193                    loaded.disabled.push(DisabledTool {
194                        identity: format!("plugin.{name}.{}", spec.name()),
195                        reason: e.to_string(),
196                    });
197                    continue;
198                }
199            };
200            let Some(tool_pin) = pins.get(&identity) else {
201                loaded.disabled.push(DisabledTool {
202                    identity,
203                    reason: "no registry pin for this tool".to_string(),
204                });
205                continue;
206            };
207
208            match (spec, tool_pin) {
209                (PluginToolSpec::Script(spec), ToolPin::Script { run, .. }) => {
210                    match build_script_tool(&identity, spec, run.clone()) {
211                        Ok(tool) => loaded.tools.push(tool),
212                        Err(reason) => loaded.disabled.push(DisabledTool { identity, reason }),
213                    }
214                }
215                (
216                    PluginToolSpec::Wasm(spec),
217                    ToolPin::Wasm {
218                        module,
219                        capabilities,
220                        ..
221                    },
222                ) => {
223                    // Missing file → registry already judged Broken (disable this tool,
224                    // don't skip the whole package).
225                    if let Some(ToolStatus::Broken { detail }) = tool_status.get(&identity) {
226                        loaded.disabled.push(DisabledTool {
227                            identity,
228                            reason: format!("broken: {detail}"),
229                        });
230                        continue;
231                    }
232                    match self.build_wasm_tool(&identity, spec, module, capabilities.clone()) {
233                        Ok(tool) => loaded.tools.push(tool),
234                        Err(reason) => loaded.disabled.push(DisabledTool { identity, reason }),
235                    }
236                }
237                (PluginToolSpec::Mcp(spec), ToolPin::Mcp { .. }) => {
238                    loaded.mcp_servers.push(PluginMcpServer {
239                        label: spec.name.clone(),
240                        command: tool_pin_mcp_command(tool_pin),
241                        env: tool_pin_mcp_env(tool_pin),
242                        url: tool_pin_mcp_url(tool_pin),
243                        headers: tool_pin_mcp_headers(tool_pin),
244                    });
245                }
246                (spec, _) => {
247                    loaded.disabled.push(DisabledTool {
248                        identity,
249                        reason: format!(
250                            "pin/manifest form mismatch: manifest={} pin={}",
251                            spec.form(),
252                            tool_pin.form()
253                        ),
254                    });
255                }
256            }
257        }
258        loaded
259    }
260
261    /// One wasm-form row → tool table entry (or the reason it is disabled).
262    fn build_wasm_tool(
263        &self,
264        identity: &str,
265        spec: &WasmToolSpec,
266        module: &str,
267        capabilities: Vec<super::manifest::ResolvedCapability>,
268    ) -> Result<Arc<dyn Tool>, String> {
269        #[cfg(feature = "wasm")]
270        {
271            let Some(runtime) = self.wasm.as_ref() else {
272                return Err("wasm runtime not configured".to_string());
273            };
274            let component = runtime
275                .compile(Path::new(module))
276                .map_err(|e| e.to_string())?;
277            Ok(Arc::new(super::wasm::WasmTool::new(
278                identity,
279                &spec.description,
280                &spec.parameters,
281                Arc::clone(runtime),
282                component,
283                &spec.name,
284                capabilities,
285                std::time::Duration::from_secs(
286                    spec.timeout_secs.unwrap_or(WASM_DEFAULT_TIMEOUT_SECS),
287                ),
288            )))
289        }
290        #[cfg(not(feature = "wasm"))]
291        {
292            let _ = (
293                identity,
294                spec,
295                module,
296                capabilities,
297                WASM_DEFAULT_TIMEOUT_SECS,
298            );
299            Err("this build has no plugin wasm support (feature `wasm`)".to_string())
300        }
301    }
302}
303
304fn tool_pin_mcp_command(pin: &ToolPin) -> Option<Vec<String>> {
305    match pin {
306        ToolPin::Mcp { command, .. } => command.clone(),
307        _ => None,
308    }
309}
310
311fn tool_pin_mcp_env(pin: &ToolPin) -> BTreeMap<String, String> {
312    match pin {
313        ToolPin::Mcp { env, .. } => env.clone(),
314        _ => BTreeMap::new(),
315    }
316}
317
318fn tool_pin_mcp_url(pin: &ToolPin) -> Option<String> {
319    match pin {
320        ToolPin::Mcp { url, .. } => url.clone(),
321        _ => None,
322    }
323}
324
325fn tool_pin_mcp_headers(pin: &ToolPin) -> BTreeMap<String, String> {
326    match pin {
327        ToolPin::Mcp { headers, .. } => headers.clone(),
328        _ => BTreeMap::new(),
329    }
330}
331
332/// One script-form row → tool table entry (argv uses the pinned registry values, not the manifest's).
333fn build_script_tool(
334    identity: &str,
335    spec: &ScriptToolSpec,
336    run: Vec<String>,
337) -> Result<Arc<dyn Tool>, String> {
338    let entry = ScriptToolEntry {
339        name: spec.name.clone(),
340        description: spec.description.clone(),
341        parameters: spec.parameters.clone(),
342        run,
343        timeout_ms: spec.timeout_secs.map(|s| s.saturating_mul(1_000)),
344        env: BTreeMap::new(),
345        cwd: None,
346        exposure: spec.exposure,
347    };
348    entry.check_laws().map_err(|e| e.to_string())?;
349    Ok(Arc::new(ScriptTool::with_key(identity, entry)))
350}
351
352/// MCP server tool name list → `plugin.{plugin}.{segment}` key assignment.
353///
354/// - normalization goes through [`normalize_tool_segment`] (lowercase, illegal chars → `-`,
355///   truncate to 32);
356/// - names that collide after normalization get `-2` / `-3`… (the suffix counts toward the
357///   32 cap: truncate the base first, then append the suffix);
358/// - names that normalize to an empty string go into `rejected` (fail-closed to "not given",
359///   never given wrong).
360///
361/// Returned keys follow the input order; `(server original tool name, identity key)`.
362pub fn assign_mcp_tool_keys(plugin: &str, raw_tool_names: &[String]) -> McpKeyAssignment {
363    let mut taken: BTreeSet<String> = BTreeSet::new();
364    let mut keys = Vec::new();
365    let mut rejected = Vec::new();
366
367    for raw in raw_tool_names {
368        let base = normalize_tool_segment(raw);
369        if base.is_empty() {
370            rejected.push(raw.clone());
371            continue;
372        }
373        let mut segment = base.clone();
374        let mut n = 2;
375        while taken.contains(&segment) {
376            segment = suffixed_segment(&base, n);
377            n += 1;
378        }
379        taken.insert(segment.clone());
380        keys.push((raw.clone(), format!("plugin.{plugin}.{segment}")));
381    }
382    McpKeyAssignment { keys, rejected }
383}
384
385/// Collision suffix (`base-2`…): the suffix counts toward [`NAME_SEGMENT_MAX`];
386/// if too long, truncate the base first.
387fn suffixed_segment(base: &str, n: usize) -> String {
388    let suffix = format!("-{n}");
389    let keep = NAME_SEGMENT_MAX
390        .saturating_sub(suffix.len())
391        .min(base.len());
392    format!("{}{suffix}", &base[..keep])
393}
394
395/// Result of [`assign_mcp_tool_keys`].
396#[derive(Debug, Clone, PartialEq, Eq)]
397pub struct McpKeyAssignment {
398    /// `(server original tool name, identity key)`, in input order.
399    pub keys: Vec<(String, String)>,
400    /// original names unusable as identity segments after normalization (rejected at load
401    /// time, they don't take up a key).
402    pub rejected: Vec<String>,
403}
404
405#[cfg(test)]
406mod tests {
407    use super::super::install::{PluginSource, commit_install, plan_install, remove_plugin};
408    use super::super::registry::PluginRegistry;
409    use super::*;
410    use crate::approval_ledger::{ApprovalLedger, ApprovalTier};
411    use agent_base::ToolRegistry;
412    use serde_json::Value;
413
414    /// A stub registered manually into the tool table (stand-in for a tool registered
415    /// after an mcp form connects).
416    struct StubTool(&'static str);
417
418    #[async_trait::async_trait]
419    impl Tool for StubTool {
420        fn name(&self) -> &'static str {
421            self.0
422        }
423        fn description(&self) -> &'static str {
424            "stub"
425        }
426        fn schema(&self) -> Value {
427            serde_json::json!({"type": "object", "properties": {}})
428        }
429        async fn call(
430            &self,
431            _args: &Value,
432            _ctx: &agent_base::ToolContext,
433        ) -> agent_base::AgentResult<Vec<agent_base::Content>> {
434            Ok(vec![])
435        }
436    }
437
438    fn dispatcher_wasm() -> std::path::PathBuf {
439        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/dispatcher.wasm")
440    }
441
442    /// Write a script and mark it executable (unix) — the install law requires a directly
443    /// executed `run[0]` to be executable.
444    fn write_script(path: &std::path::Path, contents: &str) {
445        std::fs::write(path, contents).unwrap();
446        #[cfg(unix)]
447        {
448            use std::os::unix::fs::PermissionsExt;
449            let mut perm = std::fs::metadata(path).unwrap().permissions();
450            perm.set_mode(0o755);
451            std::fs::set_permissions(path, perm).unwrap();
452        }
453    }
454
455    /// Install a basic script + mcp plugin (same shape as the install.rs tests).
456    async fn install_basic(plugins_root: &Path, source_dir: &Path) -> PluginRegistry {
457        std::fs::create_dir_all(source_dir.join("scripts")).unwrap();
458        std::fs::create_dir_all(source_dir.join("server")).unwrap();
459        std::fs::write(
460            source_dir.join("plugin.json"),
461            serde_json::json!({
462                "schemaVersion": 1,
463                "name": "my-tools",
464                "version": "0.1.0",
465                "tools": [
466                    {
467                        "name": "deploy", "form": "script",
468                        "description": "deploy it",
469                        "run": ["scripts/deploy.sh", "--env", "${env}"],
470                        "parameters": {"env": {"type": "string"}}
471                    },
472                    {
473                        "name": "wiki", "form": "mcp",
474                        "server": {
475                            "command": ["python", "server/main.py"],
476                            "env": {"WIKI_TOKEN": "${ENV:WIKI_TOKEN}"}
477                        }
478                    }
479                ]
480            })
481            .to_string(),
482        )
483        .unwrap();
484        write_script(
485            &source_dir.join("scripts/deploy.sh"),
486            "#!/bin/sh\necho deployed\n",
487        );
488        std::fs::write(source_dir.join("server/main.py"), "print('wiki')\n").unwrap();
489
490        let mut registry = PluginRegistry::new();
491        let plan = plan_install(&PluginSource::Path(source_dir.to_path_buf()), plugins_root)
492            .await
493            .expect("plan");
494        commit_install(&plan, &mut registry).expect("commit");
495        registry
496    }
497
498    #[tokio::test]
499    async fn tampered_package_disables_all_tools() {
500        let tmp = tempfile::tempdir().unwrap();
501        let plugins_root = tmp.path().join("plugins");
502        let registry = install_basic(&plugins_root, &tmp.path().join("src")).await;
503
504        // Post-install tampering: change the manifest content (hash no longer matches).
505        let manifest_path = plugins_root.join("my-tools/plugin.json");
506        let raw = std::fs::read_to_string(&manifest_path).unwrap();
507        std::fs::write(&manifest_path, raw.replace("deploy it", "tampered!")).unwrap();
508
509        let loader = PluginLoader::new();
510        let loaded = loader.load("my-tools", &registry, &plugins_root);
511        assert!(loaded.verify.tampered());
512        assert!(loaded.tools.is_empty(), "tampering ⇒ everything disabled");
513        assert_eq!(loaded.disabled.len(), 2);
514        for tool in &loaded.disabled {
515            assert!(
516                tool.reason.contains("run `plugin add` again"),
517                "reason must point to re-review: {}",
518                tool.reason
519            );
520        }
521        let mut keys: Vec<String> = loaded.disabled.iter().map(|d| d.identity.clone()).collect();
522        keys.sort();
523        assert_eq!(keys, ["plugin.my-tools.deploy", "plugin.my-tools.wiki"]);
524    }
525
526    #[tokio::test]
527    async fn missing_wasm_disables_that_tool_only() {
528        // .wasm deleted after install → that tool is disabled as Broken, the script in the
529        // same package works as usual (the whole package is not skipped).
530        let tmp = tempfile::tempdir().unwrap();
531        let plugins_root = tmp.path().join("plugins");
532        let source_dir = tmp.path().join("src");
533        std::fs::create_dir_all(source_dir.join("scripts")).unwrap();
534        std::fs::create_dir_all(source_dir.join("wasm")).unwrap();
535        std::fs::write(
536            source_dir.join("plugin.json"),
537            serde_json::json!({
538                "schemaVersion": 1, "name": "mix-pack", "version": "0.1.0",
539                "tools": [
540                    {"name": "cap", "form": "wasm", "description": "capture",
541                     "module": "wasm/cap.wasm"},
542                    {"name": "ship", "form": "script", "description": "ship it",
543                     "run": ["scripts/ship.sh"]}
544                ]
545            })
546            .to_string(),
547        )
548        .unwrap();
549        std::fs::copy(dispatcher_wasm(), source_dir.join("wasm/cap.wasm")).unwrap();
550        write_script(
551            &source_dir.join("scripts/ship.sh"),
552            "#!/bin/sh\necho shipped\n",
553        );
554
555        let mut registry = PluginRegistry::new();
556        let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
557            .await
558            .expect("plan");
559        commit_install(&plan, &mut registry).expect("commit");
560
561        // Delete the .wasm after install (manifest untouched = not tampering, just missing pieces).
562        std::fs::remove_file(plugins_root.join("mix-pack/wasm/cap.wasm")).unwrap();
563
564        let loader = PluginLoader::new();
565        let loaded = loader.load("mix-pack", &registry, &plugins_root);
566        assert!(
567            !loaded.verify.tampered(),
568            "missing pieces are not tampering"
569        );
570        assert_eq!(loaded.tools.len(), 1, "script as usual");
571        assert_eq!(loaded.tools[0].name(), "plugin.mix-pack.ship");
572        assert_eq!(loaded.disabled.len(), 1);
573        assert_eq!(loaded.disabled[0].identity, "plugin.mix-pack.cap");
574        assert!(
575            loaded.disabled[0].reason.contains("broken"),
576            "reason must say the piece is missing: {}",
577            loaded.disabled[0].reason
578        );
579    }
580
581    #[cfg(feature = "wasm")]
582    #[tokio::test]
583    async fn corrupt_wasm_disables_that_tool_only() {
584        // A bad .wasm installs fine (the hash is only a content pin), but fails to compile
585        // at load time ⇒ only it gets disabled.
586        let tmp = tempfile::tempdir().unwrap();
587        let plugins_root = tmp.path().join("plugins");
588        let source_dir = tmp.path().join("src");
589        std::fs::create_dir_all(source_dir.join("wasm")).unwrap();
590        std::fs::write(
591            source_dir.join("plugin.json"),
592            serde_json::json!({
593                "schemaVersion": 1, "name": "wasm-pack", "version": "0.1.0",
594                "tools": [
595                    {"name": "echo", "form": "wasm", "description": "roundtrip",
596                     "module": "wasm/good.wasm"},
597                    {"name": "cursed", "form": "wasm", "description": "broken bits",
598                     "module": "wasm/bad.wasm"}
599                ]
600            })
601            .to_string(),
602        )
603        .unwrap();
604        std::fs::copy(dispatcher_wasm(), source_dir.join("wasm/good.wasm")).unwrap();
605        std::fs::write(source_dir.join("wasm/bad.wasm"), b"not a wasm component").unwrap();
606
607        let mut registry = PluginRegistry::new();
608        let plan = plan_install(&PluginSource::Path(source_dir), &plugins_root)
609            .await
610            .expect("plan");
611        commit_install(&plan, &mut registry).expect("commit");
612
613        let runtime = Arc::new(super::super::wasm::WasmRuntime::new().expect("runtime"));
614        let loader = PluginLoader::with_wasm(Arc::clone(&runtime));
615        let loaded = loader.load("wasm-pack", &registry, &plugins_root);
616        assert!(!loaded.verify.tampered());
617        assert_eq!(
618            loaded.tools.len(),
619            1,
620            "the good half of the package works as usual"
621        );
622        assert_eq!(loaded.tools[0].name(), "plugin.wasm-pack.echo");
623        assert_eq!(loaded.disabled.len(), 1);
624        assert_eq!(loaded.disabled[0].identity, "plugin.wasm-pack.cursed");
625        assert!(
626            loaded.disabled[0].reason.contains("compile"),
627            "reason must say the compile failed: {}",
628            loaded.disabled[0].reason
629        );
630
631        // The good tool really runs (the load surface didn't break the runtime).
632        let out = loaded.tools[0]
633            .call(
634                &serde_json::json!({"hello": "wasm"}),
635                &agent_base::ToolContext::for_test(),
636            )
637            .await
638            .expect("call");
639        assert_eq!(out.len(), 1);
640    }
641
642    #[tokio::test]
643    async fn unload_clears_tool_table_ledger_registry() {
644        // Three places cleaned: tool table / ledger / registry.
645        let tmp = tempfile::tempdir().unwrap();
646        let plugins_root = tmp.path().join("plugins");
647        let registry = install_basic(&plugins_root, &tmp.path().join("src")).await;
648
649        let loader = PluginLoader::new();
650        let loaded = loader.load("my-tools", &registry, &plugins_root);
651
652        // Into the tool table + ledger (the user's everyday state). mcp-form tools are
653        // registered after the product layer connects; here a stub stands in for that row,
654        // likewise in the table.
655        let mut table = ToolRegistry::default();
656        for tool in &loaded.tools {
657            table.register_arc(Arc::clone(tool));
658        }
659        table.register_arc(Arc::new(StubTool("plugin.my-tools.wiki")));
660        let mut ledger = ApprovalLedger::new();
661        ledger.set_tier("plugin.my-tools.deploy", ApprovalTier::AlwaysAllow);
662        ledger.set_tier("plugin.my-tools.wiki", ApprovalTier::Deny);
663        ledger.set_tier("unrelated.keep", ApprovalTier::AlwaysAllow);
664
665        // Unload: registry + directory + ledger prefix + tool table.
666        let mut registry = registry;
667        let report = remove_plugin(&plugins_root, &mut registry, "my-tools").expect("remove");
668        let swept = report.sweep_ledger(&mut ledger);
669        assert_eq!(swept, 2, "all plugin.my-tools.* swept");
670        for key in &report.identity_keys {
671            table.remove(key);
672        }
673
674        // Each of the three places is clean on its own.
675        for key in &report.identity_keys {
676            assert!(table.get(key).is_none(), "tool table has leftovers {key}");
677        }
678        assert_eq!(ledger.tier_of("plugin.my-tools.deploy"), ApprovalTier::Ask);
679        assert_eq!(ledger.tier_of("plugin.my-tools.wiki"), ApprovalTier::Ask);
680        assert_eq!(
681            ledger.tier_of("unrelated.keep"),
682            ApprovalTier::AlwaysAllow,
683            "other plugins' ledgers must not be touched"
684        );
685        assert!(registry.get("my-tools").is_none());
686        assert!(!plugins_root.join("my-tools").exists());
687    }
688
689    #[test]
690    fn assign_mcp_tool_keys_normalizes_and_disambiguates() {
691        let names: Vec<String> = ["Search", "search", "get file", "Other", ""]
692            .iter()
693            .map(|s| s.to_string())
694            .collect();
695        let out = assign_mcp_tool_keys("my-tools", &names);
696        assert_eq!(
697            out.keys,
698            vec![
699                ("Search".to_string(), "plugin.my-tools.search".to_string()),
700                ("search".to_string(), "plugin.my-tools.search-2".to_string()),
701                (
702                    "get file".to_string(),
703                    "plugin.my-tools.get-file".to_string()
704                ),
705                ("Other".to_string(), "plugin.my-tools.other".to_string()),
706            ]
707        );
708        assert_eq!(
709            out.rejected,
710            vec!["".to_string()],
711            "empty name fail-closed reject"
712        );
713    }
714
715    #[test]
716    fn assign_mcp_tool_keys_suffix_respects_32_char_cap() {
717        let base = "a".repeat(NAME_SEGMENT_MAX);
718        let names: Vec<String> = vec![base.clone(), base.clone(), base.clone()];
719        let out = assign_mcp_tool_keys("p", &names);
720        assert_eq!(out.keys[0].1, format!("plugin.p.{base}"));
721        assert_eq!(
722            out.keys[1].1,
723            format!("plugin.p.{}-2", "a".repeat(NAME_SEGMENT_MAX - 2))
724        );
725        assert_eq!(
726            out.keys[2].1,
727            format!("plugin.p.{}-3", "a".repeat(NAME_SEGMENT_MAX - 2))
728        );
729        // Suffix counts toward the 32 cap + all three keys distinct.
730        let segments: Vec<&str> = out
731            .keys
732            .iter()
733            .map(|(_, k)| k.strip_prefix("plugin.p.").unwrap())
734            .collect();
735        for segment in &segments {
736            assert!(segment.len() <= NAME_SEGMENT_MAX, "{segment}");
737        }
738        let mut dedup = segments.clone();
739        dedup.sort_unstable();
740        dedup.dedup();
741        assert_eq!(dedup.len(), 3);
742    }
743}