Skip to main content

bamboo_plugin/
installer.rs

1//! The `PluginInstaller` trait — the method surface later agents implement.
2//!
3//! This crate lives at the `infra` layer and has no access to `AppState`
4//! (`bamboo-server`, an `app`-layer crate). Actually registering capabilities
5//! — merging into `config.json`, calling `mcp_manager.start_server`, appending
6//! to `prompt-presets.json`, writing workflow files — all need `AppState` (or
7//! equivalent handles), so a REAL implementation of this trait has to live in
8//! `bamboo-server` (or a sibling crate that depends on it), implemented by a
9//! later agent (see `PLUGIN_PLAN.md` § Installer-core agent). Because the
10//! trait is foreign there and the implementing type is local, that's a
11//! perfectly ordinary downstream `impl` — no orphan-rule issue.
12//!
13//! [`LocalPluginInstaller`] below is a reference skeleton that implements
14//! everything this crate CAN implement without `AppState` (manifest
15//! validation, platform gating, MCP-entry token resolution, the
16//! disposition/upgrade decision, the `provides.skills`-authoritative check,
17//! provenance listing) and returns [`PluginError::NotImplemented`] at the
18//! exact points that need capability-registration wiring, with a comment
19//! enumerating what goes there and citing the exact files. It is a
20//! reference/example, not a requirement to reuse verbatim — Wave-2's
21//! installer-core agent may replace it entirely with a type that holds an
22//! `AppState` handle.
23//!
24//! # Ownership + upgrade contract (why uninstall is provably safe)
25//!
26//! Two invariants make uninstall/upgrade never touch a user's own entries:
27//!
28//! 1. **Only plugin-created entries are ever recorded as removable.** For the
29//!    REFUSE-on-conflict capabilities (MCP servers, workflow files) the
30//!    installer MUST run [`crate::registry::reconcile_exclusive`] against the
31//!    live shared store before touching anything: a declared id/filename that
32//!    already exists and is not owned by this plugin lands in
33//!    `foreign_conflicts` and the install is REFUSED
34//!    ([`PluginError::Conflict`]) — it is never registered and never written
35//!    into [`crate::registry::RegisteredCapabilities`]. So the `registered`
36//!    set an [`InstalledPlugin`] carries contains ONLY entries this plugin
37//!    genuinely created; `uninstall` iterating that set can only ever delete
38//!    the plugin's own entries. (Prompt presets are the one exception: they
39//!    rename on collision via bamboo-server's `ensure_unique_preset_id`
40//!    instead of refusing, and the RENAMED id is what gets recorded.)
41//! 2. **Upgrade de-registers what the new version dropped.** `install` with
42//!    [`InstallDisposition::Upgrade`] loads the prior [`InstalledPlugin`],
43//!    computes [`crate::registry::RegisteredCapabilities::removed_since`] (old
44//!    minus new), de-registers those dropped capabilities, THEN registers the
45//!    new set and upserts provenance — so a capability the old version had and
46//!    the new one dropped can't leak as an orphan.
47
48use std::path::{Path, PathBuf};
49
50use async_trait::async_trait;
51use chrono::{DateTime, Utc};
52
53use crate::error::{PluginError, PluginResult};
54use crate::manifest::{Platform, PluginManifest};
55use crate::registry::{InstalledPlugin, InstalledPlugins, PluginSource};
56
57/// How [`PluginInstaller::install`] must treat a plugin id that is ALREADY
58/// installed. Maps directly to the CLI verbs: `bamboo plugin install` uses
59/// [`Self::FailIfInstalled`], `bamboo plugin update` (or `install --force`)
60/// uses [`Self::Upgrade`].
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum InstallDisposition {
63    /// Refuse a re-install of an already-installed id with
64    /// [`PluginError::AlreadyInstalled`]. A first-time `install` should not
65    /// silently replace an existing plugin.
66    FailIfInstalled,
67    /// Upgrade in place: de-register the capabilities the new version dropped
68    /// (via [`crate::registry::RegisteredCapabilities::removed_since`]),
69    /// register the new set, then upsert provenance.
70    Upgrade,
71}
72
73/// The installer method surface. `install`/`uninstall`/`list` are the verbs
74/// the CLI (`bamboo plugin install/list/remove/update`) and the HTTP routes
75/// (`/api/v1/plugins`) both call through.
76#[async_trait]
77pub trait PluginInstaller {
78    /// Install (or, with [`InstallDisposition::Upgrade`], upgrade) a plugin
79    /// already unpacked at `plugin_dir` (source handling — copying a local
80    /// dir, unpacking a `.tar.gz`, fetching+verifying a URL + selecting the
81    /// per-platform artifact — happens BEFORE this is called; by the time
82    /// `install` runs, `plugin_dir` already contains `plugin.json` plus the
83    /// `skills/`/`prompts/`/`workflows/`/`bin/` layout the manifest declares).
84    ///
85    /// Contract (see the module docs for the full rationale):
86    /// - `disposition` decides already-installed handling (fail vs upgrade).
87    /// - MCP-server and workflow collisions with NON-plugin entries MUST be
88    ///   refused ([`PluginError::Conflict`]) via
89    ///   [`crate::registry::reconcile_exclusive`] — never clobbered.
90    /// - On upgrade, capabilities the new version dropped MUST be
91    ///   de-registered ([`crate::registry::RegisteredCapabilities::removed_since`]).
92    /// - The returned [`InstalledPlugin`] must have already been persisted
93    ///   into `installed.json`, and its `registered` set must contain ONLY
94    ///   entries this plugin genuinely created (so uninstall is safe).
95    async fn install(
96        &self,
97        manifest: &PluginManifest,
98        plugin_dir: &Path,
99        source: PluginSource,
100        disposition: InstallDisposition,
101        installed_at: DateTime<Utc>,
102    ) -> PluginResult<InstalledPlugin>;
103
104    /// Reverse everything `install` registered for `id` (stop + remove MCP
105    /// servers, remove prompt presets, remove workflow files), then remove
106    /// the provenance entry and delete `plugin_dir` from disk. Safe by
107    /// construction: the provenance `registered` set only ever names
108    /// plugin-created entries (invariant 1 in the module docs).
109    async fn uninstall(&self, id: &str) -> PluginResult<()>;
110
111    /// All currently-installed plugins (a thin read of `installed.json`).
112    async fn list(&self) -> PluginResult<Vec<InstalledPlugin>>;
113}
114
115/// Directory names directly under `<plugin_dir>/skills/` that contain a
116/// `SKILL.md` (i.e. what discovery would actually pick up in place). Used
117/// by [`preflight_install`] to enforce that `provides.skills` is
118/// authoritative (MAJOR 4).
119pub async fn on_disk_skill_dirs(plugin_dir: &Path) -> Vec<String> {
120    let skills_root = plugin_dir.join("skills");
121    let mut found = Vec::new();
122    let Ok(mut entries) = tokio::fs::read_dir(&skills_root).await else {
123        return found;
124    };
125    while let Ok(Some(entry)) = entries.next_entry().await {
126        let is_dir = entry
127            .file_type()
128            .await
129            .map(|file_type| file_type.is_dir())
130            .unwrap_or(false);
131        if !is_dir {
132            continue;
133        }
134        let has_skill_md = tokio::fs::try_exists(entry.path().join("SKILL.md"))
135            .await
136            .unwrap_or(false);
137        if !has_skill_md {
138            continue;
139        }
140        if let Some(name) = entry.file_name().to_str() {
141            found.push(name.to_string());
142        }
143    }
144    found
145}
146
147/// Everything an `install` can validate/resolve WITHOUT touching `AppState`:
148/// manifest validation, platform gating, per-entry MCP resolution (so a
149/// malformed entry — e.g. an empty stdio command — fails fast before any
150/// registration happens), and the `provides.skills` / `provides.workflows`
151/// on-disk existence + authoritative checks (MAJOR 4).
152///
153/// Shared by [`LocalPluginInstaller`] and any real `AppState`-backed
154/// installer (see `PLUGIN_PLAN.md` § Installer-core agent) so the two can
155/// never drift apart. Returns the resolved MCP server configs (the caller
156/// needs them anyway to register step 1) so a real installer doesn't have to
157/// re-resolve them a second time.
158pub async fn preflight_install(
159    manifest: &PluginManifest,
160    plugin_dir: &Path,
161) -> PluginResult<Vec<bamboo_domain::mcp_config::McpServerConfig>> {
162    manifest.validate()?;
163
164    let current_platform = Platform::current();
165    if let Some(platforms) = &manifest.platforms {
166        // An unrecognized host OS (`current_platform == None`) fails closed
167        // rather than guessing.
168        let supported = current_platform.is_some_and(|platform| platforms.contains(&platform));
169        if !supported {
170            return Err(PluginError::UnsupportedPlatform {
171                plugin_id: manifest.id.clone(),
172                platform: current_platform
173                    .map(|platform| platform.as_str().to_string())
174                    .unwrap_or_else(|| std::env::consts::OS.to_string()),
175            });
176        }
177    }
178
179    // Resolve what each declared MCP server WOULD look like once registered.
180    // Pure — fails early on an unresolvable entry (e.g. empty stdio command)
181    // and hands the caller the resolved configs to register in step 1.
182    let platform = current_platform.unwrap_or(Platform::Linux);
183    let resolved_mcp_servers = manifest
184        .provides
185        .mcp_servers
186        .iter()
187        .map(|entry| entry.resolve(plugin_dir, &manifest.id, platform))
188        .collect::<PluginResult<Vec<_>>>()?;
189
190    // Sanity-check declared skill dirs exist on disk. Skills need no further
191    // action here — they're discovered in place by bamboo-skills' plugin
192    // discovery-dir extension, not copied.
193    for skill_dir in &manifest.provides.skills {
194        let skill_md = plugin_dir.join("skills").join(skill_dir).join("SKILL.md");
195        if !tokio::fs::try_exists(&skill_md).await.unwrap_or(false) {
196            return Err(PluginError::InvalidManifest(format!(
197                "declared skill '{skill_dir}' has no SKILL.md at {}",
198                skill_md.display()
199            )));
200        }
201    }
202    // `provides.skills` is AUTHORITATIVE: reject any on-disk skill dir the
203    // manifest does not declare. Discovery is a dumb globber that picks up
204    // every `<plugin_dir>/skills/*` with a SKILL.md, so without this a
205    // bundle could smuggle an undeclared skill live past its own manifest.
206    {
207        use std::collections::HashSet;
208        let declared: HashSet<&str> = manifest
209            .provides
210            .skills
211            .iter()
212            .map(String::as_str)
213            .collect();
214        for on_disk in on_disk_skill_dirs(plugin_dir).await {
215            if !declared.contains(on_disk.as_str()) {
216                return Err(PluginError::InvalidManifest(format!(
217                    "skill directory '{on_disk}' exists under skills/ but is not declared in \
218                     provides.skills (a plugin must declare every skill it ships)"
219                )));
220            }
221        }
222    }
223    for workflow_file in &manifest.provides.workflows {
224        let workflow_path = plugin_dir.join("workflows").join(workflow_file);
225        if !tokio::fs::try_exists(&workflow_path).await.unwrap_or(false) {
226            return Err(PluginError::InvalidManifest(format!(
227                "declared workflow '{workflow_file}' not found at {}",
228                workflow_path.display()
229            )));
230        }
231    }
232
233    Ok(resolved_mcp_servers)
234}
235
236/// Loads prior provenance for `plugin_id` from `installed_json_path` and
237/// applies the [`InstallDisposition`] gate: [`InstallDisposition::FailIfInstalled`]
238/// errors [`PluginError::AlreadyInstalled`] when a COMPLETED entry already
239/// exists; [`InstallDisposition::Upgrade`] passes through either way. Returns
240/// the previous entry (`None` for a fresh install), which the caller needs for
241/// the upgrade drop-diff (BLOCKER 2) and for crash recovery.
242///
243/// Crash-recovery exception: a previous row with
244/// [`crate::registry::PluginInstallStatus::Installing`] is a leftover from an
245/// interrupted install (a hard kill mid-registration), NOT a completed
246/// install — so it does NOT trip `AlreadyInstalled` even under
247/// `FailIfInstalled`. It is returned like any other `previous` so the caller
248/// treats its (intended) `registered` set as this-plugin-owned and cleans it
249/// up as an upgrade-over-incomplete, instead of the leftover's half-written
250/// entries reading as a foreign conflict on retry.
251pub async fn load_previous_for_disposition(
252    installed_json_path: &Path,
253    plugin_id: &str,
254    disposition: InstallDisposition,
255) -> PluginResult<Option<InstalledPlugin>> {
256    use crate::registry::PluginInstallStatus;
257
258    let existing = InstalledPlugins::load(installed_json_path).await?;
259    let previous = existing.get(plugin_id).cloned();
260    let is_completed = previous
261        .as_ref()
262        .is_some_and(|plugin| plugin.status == PluginInstallStatus::Installed);
263    if is_completed && disposition == InstallDisposition::FailIfInstalled {
264        return Err(PluginError::AlreadyInstalled(plugin_id.to_string()));
265    }
266    Ok(previous)
267}
268
269/// Reference skeleton — see module docs. Holds only a `bamboo_dir` so tests
270/// can point it at a tempdir instead of the real `~/.bamboo`.
271pub struct LocalPluginInstaller {
272    bamboo_dir: PathBuf,
273}
274
275impl LocalPluginInstaller {
276    pub fn new(bamboo_dir: PathBuf) -> Self {
277        Self { bamboo_dir }
278    }
279
280    fn plugins_dir(&self) -> PathBuf {
281        self.bamboo_dir.join("plugins")
282    }
283
284    fn installed_json_path(&self) -> PathBuf {
285        self.plugins_dir().join("installed.json")
286    }
287}
288
289impl Default for LocalPluginInstaller {
290    fn default() -> Self {
291        Self::new(bamboo_config::paths::bamboo_dir())
292    }
293}
294
295#[async_trait]
296impl PluginInstaller for LocalPluginInstaller {
297    async fn install(
298        &self,
299        manifest: &PluginManifest,
300        plugin_dir: &Path,
301        _source: PluginSource,
302        disposition: InstallDisposition,
303        _installed_at: DateTime<Utc>,
304    ) -> PluginResult<InstalledPlugin> {
305        // --- Disposition / upgrade decision (fully implemented here) ---
306        //
307        // Load prior provenance FIRST so we can (a) reject a first-time
308        // install of an already-installed id, and (b) on upgrade, capture the
309        // old registered set for the drop-diff below.
310        let previous =
311            load_previous_for_disposition(&self.installed_json_path(), &manifest.id, disposition)
312                .await?;
313        // On upgrade this is the set the installer-core agent must
314        // `removed_since`-diff against the new registered set and de-register.
315        let _previous_registered = previous.as_ref().map(|plugin| plugin.registered.clone());
316
317        // --- Validation + pure path resolution (fully implemented here,
318        // shared with any real AppState-backed installer via
319        // `preflight_install`) ---
320        let _resolved_mcp_servers = preflight_install(manifest, plugin_dir).await?;
321
322        // --- Capability-registration wiring (TODO: installer-core agent) ---
323        //
324        // None of this can be implemented in this infra-layer crate — it all
325        // needs `AppState` (bamboo-server, an app-layer crate this crate must
326        // not depend on). See PLUGIN_PLAN.md § Installer-core agent for the
327        // full breakdown. In order:
328        //
329        //   0. UPGRADE DROP-DIFF (only when `previous` is Some): compute
330        //      `new_registered.removed_since(&_previous_registered.unwrap())`
331        //      and DE-register those dropped mcp ids / preset ids / workflow
332        //      files (same removal ops as `uninstall`) BEFORE registering the
333        //      new set, so a capability the old version had and the new one
334        //      dropped never leaks (BLOCKER 2).
335        //   1. MCP: run `registry::reconcile_exclusive(declared_mcp_ids,
336        //      existing_mcp_ids_in_config, previously_owned_mcp_ids)`. If
337        //      `foreign_conflicts` is non-empty → return `PluginError::Conflict`
338        //      (BLOCKER 1 — do NOT clobber). Otherwise merge only `to_register`
339        //      into `Config.mcp.servers` via `AppState::update_config`
340        //      (crates/app/bamboo-server/src/app_state/config_runtime.rs),
341        //      reusing the merge-by-id logic in
342        //      crates/app/bamboo-server/src/handlers/agent/mcp/server_handlers/import.rs
343        //      (`import_servers`), then `state.mcp_manager.start_server(..)`
344        //      for each enabled one. Record exactly `to_register` as owned.
345        //   2. Prompts: append `manifest.provides.prompts` into
346        //      `prompt-presets.json`
347        //      (crates/app/bamboo-server/src/handlers/agent/prompt_presets/storage.rs),
348        //      reusing `validate_preset_id` / `ensure_unique_preset_id` — on an
349        //      id collision RENAME (don't refuse), and record the RENAMED id as
350        //      owned (not the manifest's nominal one).
351        //   3. Workflows: run `reconcile_exclusive` on the workflow filenames
352        //      the same way as MCP (refuse foreign collisions), then copy
353        //      `<plugin_dir>/workflows/<name>.md` into
354        //      `bamboo_config::paths::workflows_dir()/<name>.md` (validate each
355        //      name with `bamboo_config::paths::is_safe_workflow_name`).
356        //   4. Skills: nothing to register (discovered in place). Record the
357        //      declared+validated dir names as owned.
358        //   5. Only once 0-4 succeed: build the `RegisteredCapabilities`
359        //      reflecting exactly what got registered (renamed preset ids, the
360        //      `to_register` mcp/workflow subsets — NOT a blind copy of
361        //      `manifest.provides`), then upsert provenance via
362        //      `InstalledPlugins::load` + `.add(..)` + `.save(..)` at
363        //      `self.installed_json_path()`.
364        let _ = self.installed_json_path(); // reserved for step 5 above.
365        Err(PluginError::NotImplemented(
366            "capability registration wiring — see PLUGIN_PLAN.md \
367             \u{a7} Installer-core agent"
368                .to_string(),
369        ))
370    }
371
372    async fn uninstall(&self, id: &str) -> PluginResult<()> {
373        let installed = InstalledPlugins::load(&self.installed_json_path()).await?;
374        if installed.get(id).is_none() {
375            return Err(PluginError::NotFound(id.to_string()));
376        }
377
378        // TODO(installer-core agent): using the found entry's `registered`
379        // capabilities (which, by construction, name ONLY plugin-created
380        // entries — see module docs), stop + remove each `mcp_server_ids`
381        // entry from `config.json` (`AppState::update_config` +
382        // `mcp_manager.stop_server`), remove each `preset_ids` entry from
383        // `prompt-presets.json`, delete each `workflow_filenames` file from
384        // `bamboo_config::paths::workflows_dir()`. THEN remove the provenance
385        // entry (`InstalledPlugins::remove` + `.save(..)`) and finally
386        // `tokio::fs::remove_dir_all(entry.plugin_dir)`.
387        Err(PluginError::NotImplemented(
388            "capability de-registration wiring — see PLUGIN_PLAN.md \
389             \u{a7} Installer-core agent"
390                .to_string(),
391        ))
392    }
393
394    async fn list(&self) -> PluginResult<Vec<InstalledPlugin>> {
395        let installed = InstalledPlugins::load(&self.installed_json_path()).await?;
396        Ok(installed.plugins)
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403    use crate::manifest::PluginManifest;
404    use crate::registry::RegisteredCapabilities;
405
406    fn manifest_with(skills: Vec<&str>, workflows: Vec<&str>) -> PluginManifest {
407        let json = serde_json::json!({
408            "id": "hello-plugin",
409            "name": "Hello Plugin",
410            "version": "0.1.0",
411            "provides": {
412                "skills": skills,
413                "workflows": workflows,
414            }
415        });
416        PluginManifest::parse_str(&json.to_string()).expect("parse manifest")
417    }
418
419    /// Create `<plugin_dir>/skills/<id>/SKILL.md` for each id.
420    async fn write_skill_dirs(plugin_dir: &Path, ids: &[&str]) {
421        for id in ids {
422            let skill_dir = plugin_dir.join("skills").join(id);
423            tokio::fs::create_dir_all(&skill_dir).await.unwrap();
424            tokio::fs::write(
425                skill_dir.join("SKILL.md"),
426                format!("---\nname: {id}\ndescription: demo\n---\nHi\n"),
427            )
428            .await
429            .unwrap();
430        }
431    }
432
433    #[tokio::test]
434    async fn list_on_fresh_bamboo_dir_is_empty() {
435        let dir = tempfile::tempdir().expect("tempdir");
436        let installer = LocalPluginInstaller::new(dir.path().to_path_buf());
437        let plugins = installer.list().await.expect("list");
438        assert!(plugins.is_empty());
439    }
440
441    #[tokio::test]
442    async fn uninstall_unknown_plugin_is_not_found() {
443        let dir = tempfile::tempdir().expect("tempdir");
444        let installer = LocalPluginInstaller::new(dir.path().to_path_buf());
445        let error = installer
446            .uninstall("does-not-exist")
447            .await
448            .expect_err("should be not-found");
449        assert!(matches!(error, PluginError::NotFound(_)));
450    }
451
452    #[tokio::test]
453    async fn install_validates_declared_skill_exists_on_disk() {
454        let dir = tempfile::tempdir().expect("tempdir");
455        let installer = LocalPluginInstaller::new(dir.path().join("bamboo-home"));
456
457        let plugin_dir = dir.path().join("plugin-src");
458        tokio::fs::create_dir_all(&plugin_dir).await.unwrap();
459        // Note: no `skills/hello-world/SKILL.md` created — install should
460        // reject the manifest for a missing declared skill before it ever
461        // reaches the (currently NotImplemented) registration step.
462        let manifest = manifest_with(vec!["hello-world"], vec![]);
463
464        let error = installer
465            .install(
466                &manifest,
467                &plugin_dir,
468                PluginSource::LocalDir {
469                    path: plugin_dir.clone(),
470                },
471                InstallDisposition::FailIfInstalled,
472                Utc::now(),
473            )
474            .await
475            .expect_err("missing SKILL.md should fail validation");
476        assert!(matches!(error, PluginError::InvalidManifest(_)));
477    }
478
479    #[tokio::test]
480    async fn install_rejects_undeclared_on_disk_skill_dir() {
481        let dir = tempfile::tempdir().expect("tempdir");
482        let installer = LocalPluginInstaller::new(dir.path().join("bamboo-home"));
483
484        let plugin_dir = dir.path().join("plugin-src");
485        // Bundle ships TWO skills on disk but declares only one.
486        write_skill_dirs(&plugin_dir, &["hello-world", "sneaky-extra"]).await;
487        let manifest = manifest_with(vec!["hello-world"], vec![]);
488
489        let error = installer
490            .install(
491                &manifest,
492                &plugin_dir,
493                PluginSource::LocalDir {
494                    path: plugin_dir.clone(),
495                },
496                InstallDisposition::FailIfInstalled,
497                Utc::now(),
498            )
499            .await
500            .expect_err("undeclared skill dir should be rejected");
501        assert!(matches!(error, PluginError::InvalidManifest(_)));
502        assert!(error.to_string().contains("sneaky-extra"));
503    }
504
505    #[tokio::test]
506    async fn install_reaches_not_implemented_once_declared_files_exist() {
507        let dir = tempfile::tempdir().expect("tempdir");
508        let installer = LocalPluginInstaller::new(dir.path().join("bamboo-home"));
509
510        let plugin_dir = dir.path().join("plugin-src");
511        write_skill_dirs(&plugin_dir, &["hello-world"]).await;
512        let manifest = manifest_with(vec!["hello-world"], vec![]);
513
514        let error = installer
515            .install(
516                &manifest,
517                &plugin_dir,
518                PluginSource::LocalDir {
519                    path: plugin_dir.clone(),
520                },
521                InstallDisposition::FailIfInstalled,
522                Utc::now(),
523            )
524            .await
525            .expect_err("registration wiring is a later-agent TODO");
526        assert!(matches!(error, PluginError::NotImplemented(_)));
527
528        // And it must not have been committed to provenance either, since
529        // registration never completed.
530        let plugins = installer.list().await.expect("list");
531        assert!(plugins.is_empty());
532    }
533
534    #[tokio::test]
535    async fn install_fails_if_already_installed_under_fail_disposition() {
536        let dir = tempfile::tempdir().expect("tempdir");
537        let bamboo_home = dir.path().join("bamboo-home");
538        let installer = LocalPluginInstaller::new(bamboo_home.clone());
539
540        // Seed provenance with an existing install of the same id.
541        let mut store = InstalledPlugins::default();
542        store.add(InstalledPlugin {
543            id: "hello-plugin".to_string(),
544            version: "0.0.1".to_string(),
545            source: PluginSource::LocalDir {
546                path: dir.path().to_path_buf(),
547            },
548            plugin_dir: bamboo_home.join("plugins").join("hello-plugin"),
549            installed_at: Utc::now(),
550            status: crate::registry::PluginInstallStatus::Installed,
551            registered: RegisteredCapabilities::default(),
552        });
553        store
554            .save(&bamboo_home.join("plugins").join("installed.json"))
555            .await
556            .unwrap();
557
558        let plugin_dir = dir.path().join("plugin-src");
559        write_skill_dirs(&plugin_dir, &["hello-world"]).await;
560        let manifest = manifest_with(vec!["hello-world"], vec![]);
561
562        let error = installer
563            .install(
564                &manifest,
565                &plugin_dir,
566                PluginSource::LocalDir {
567                    path: plugin_dir.clone(),
568                },
569                InstallDisposition::FailIfInstalled,
570                Utc::now(),
571            )
572            .await
573            .expect_err("already-installed under FailIfInstalled should error");
574        assert!(matches!(error, PluginError::AlreadyInstalled(_)));
575    }
576
577    #[tokio::test]
578    async fn upgrade_disposition_proceeds_past_the_already_installed_gate() {
579        let dir = tempfile::tempdir().expect("tempdir");
580        let bamboo_home = dir.path().join("bamboo-home");
581        let installer = LocalPluginInstaller::new(bamboo_home.clone());
582
583        // Same seed as the FailIfInstalled test.
584        let mut store = InstalledPlugins::default();
585        store.add(InstalledPlugin {
586            id: "hello-plugin".to_string(),
587            version: "0.0.1".to_string(),
588            source: PluginSource::LocalDir {
589                path: dir.path().to_path_buf(),
590            },
591            plugin_dir: bamboo_home.join("plugins").join("hello-plugin"),
592            installed_at: Utc::now(),
593            status: crate::registry::PluginInstallStatus::Installed,
594            registered: RegisteredCapabilities::default(),
595        });
596        store
597            .save(&bamboo_home.join("plugins").join("installed.json"))
598            .await
599            .unwrap();
600
601        let plugin_dir = dir.path().join("plugin-src");
602        write_skill_dirs(&plugin_dir, &["hello-world"]).await;
603        let manifest = manifest_with(vec!["hello-world"], vec![]);
604
605        // Upgrade must NOT hit AlreadyInstalled; it proceeds to the (still
606        // later-agent) registration TODO.
607        let error = installer
608            .install(
609                &manifest,
610                &plugin_dir,
611                PluginSource::LocalDir {
612                    path: plugin_dir.clone(),
613                },
614                InstallDisposition::Upgrade,
615                Utc::now(),
616            )
617            .await
618            .expect_err("registration wiring is a later-agent TODO");
619        assert!(matches!(error, PluginError::NotImplemented(_)));
620    }
621}