Skip to main content

bamboo_plugin/
registry.rs

1//! Provenance registry: `~/.bamboo/plugins/installed.json`.
2//!
3//! Records, for each installed plugin, EXACTLY what it registered (which
4//! `mcpServers` ids, which skill dir names, which prompt preset ids, which
5//! workflow filenames) so uninstall/upgrade can precisely undo only what a
6//! given plugin added — never touching a user's own hand-added entries that
7//! happen to share a config file with plugin-registered ones.
8//!
9//! This module only defines the schema + load/save/add/remove helpers. Wiring
10//! *when* to call `add`/`remove` relative to actually registering/
11//! deregistering capabilities (MCP servers, prompt presets, workflow files)
12//! is the installer's job (see [`crate::installer`] and `PLUGIN_PLAN.md`).
13
14use std::collections::HashSet;
15use std::path::{Path, PathBuf};
16
17use chrono::{DateTime, Utc};
18use serde::{Deserialize, Serialize};
19use tokio::fs;
20
21use crate::error::{PluginError, PluginResult};
22
23/// Where a plugin's installed bundle came from. Recorded verbatim so
24/// `update`/reinstall can re-fetch from the same place.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(tag = "type", rename_all = "snake_case")]
27pub enum PluginSource {
28    /// Installed from a local directory (copied or referenced in place — the
29    /// installer decides which; either way this records the ORIGINAL path the
30    /// user pointed at, not necessarily `plugin_dir`).
31    LocalDir { path: PathBuf },
32    /// Installed by unpacking a local `.tar.gz` archive.
33    LocalArchive { path: PathBuf },
34    /// Installed by fetching a URL. Three trust layers, all enforced by
35    /// `bamboo-server`'s `plugin_source.rs` before this record is written:
36    ///
37    /// 1. **Host allowlist** (source authorization) — was the URL's host
38    ///    fetched from an operator-trusted host (`allow_untrusted_host` opts
39    ///    out).
40    /// 2. **Signature** (publisher authenticity) — did the bundle's `.sig`
41    ///    verify against a trusted ed25519 key (`signed_by`; `allow_unsigned`
42    ///    opts out of requiring one).
43    /// 3. **Checksum** (integrity) — `sha256` is the user-verified hash of
44    ///    the downloaded BUNDLE (the `plugin.json`, or the archive containing
45    ///    it) — `Some` in the normal case, confirmed against a
46    ///    caller-supplied expected hash BEFORE anything was
47    ///    extracted/trusted.
48    ///
49    /// `sha256` is `None` either when the install explicitly opted out of
50    /// checksum verification (`allow_unverified: true`, no hash supplied), OR
51    /// when a verified signature (`signed_by: Some(_)`) already established
52    /// integrity+authenticity more strongly than a pasted checksum could —
53    /// see `plugin_source.rs`'s module docs for why a valid signature
54    /// supersedes the checksum requirement. An install refuses outright
55    /// rather than silently trusting an unpinned/unsigned download from an
56    /// untrusted host, so every `None`/`false` combination here always means
57    /// a deliberate, recorded risk acceptance, never an oversight.
58    ///
59    /// `insecure` is the convenience AGGREGATE over the three per-layer
60    /// opt-outs above: `true` when this install waived all three at once,
61    /// either via a per-install `--insecure` flag / `"insecure": true` on the
62    /// request, or because `plugin_trust.enforcement` was `off` at install
63    /// time (see `bamboo-server`'s `plugin_source.rs` module docs). Recorded
64    /// separately from the three individual `allow_*` fields so `plugin
65    /// list`/audit can tell "an operator deliberately accepted ALL risk for
66    /// this source" apart from "these three flags happened to all be set
67    /// individually" — functionally identical, but a meaningfully different
68    /// signal for review. `#[serde(default)]` so a pre-existing
69    /// `installed.json` row (written before this field existed) loads as
70    /// `false` rather than failing to deserialize.
71    Url {
72        url: String,
73        #[serde(default, skip_serializing_if = "Option::is_none")]
74        sha256: Option<String>,
75        /// Recorded for audit: true when this install ran with
76        /// `allow_unverified` and no `sha256`. `#[serde(default)]` so a
77        /// pre-existing `installed.json` row (written before this field
78        /// existed, back when only the per-platform binary artifact was
79        /// pinned) loads as `false` rather than failing to deserialize.
80        #[serde(default, skip_serializing_if = "is_false")]
81        allow_unverified: bool,
82        /// Recorded for audit: true when this install ran with
83        /// `allow_untrusted_host` against a host outside
84        /// `plugin_trust.trusted_hosts`. `#[serde(default)]` for backward
85        /// compat with rows written before this field existed.
86        #[serde(default, skip_serializing_if = "is_false")]
87        allow_untrusted_host: bool,
88        /// Recorded for audit: true when this install ran with
89        /// `allow_unsigned` (no valid signature from a trusted key).
90        /// `#[serde(default)]` for backward compat.
91        #[serde(default, skip_serializing_if = "is_false")]
92        allow_unsigned: bool,
93        /// The label of the `plugin_trust.trusted_keys` entry the bundle's
94        /// `.sig` verified against, or `None` if the install proceeded
95        /// unsigned (`allow_unsigned: true`). `#[serde(default)]` for
96        /// backward compat with rows written before signing existed.
97        #[serde(default, skip_serializing_if = "Option::is_none")]
98        signed_by: Option<String>,
99        /// True when this install ran with ALL THREE trust layers waived at
100        /// once via the `--insecure` / `"insecure": true` aggregate opt-out,
101        /// or because `plugin_trust.enforcement` was `off` — see this
102        /// variant's doc comment above. `#[serde(default)]` for backward
103        /// compat with rows written before this field existed.
104        #[serde(default, skip_serializing_if = "is_false")]
105        insecure: bool,
106    },
107}
108
109/// `skip_serializing_if` helper for a `bool` field that should be omitted
110/// from the JSON when `false` (serde has no built-in equivalent of
111/// `std::ops::Not::not` that takes a reference).
112fn is_false(value: &bool) -> bool {
113    !*value
114}
115
116/// Exactly what an installed plugin registered into Bamboo's shared capability
117/// stores. Every id/name here MUST have actually been written by the
118/// installer for THIS plugin — never a superset (that would risk clobbering
119/// or removing a user's own entries on uninstall) and never a subset
120/// (uninstall would leak orphaned registrations).
121#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
122pub struct RegisteredCapabilities {
123    /// Ids registered into `config.json`'s `mcpServers` map.
124    #[serde(default, skip_serializing_if = "Vec::is_empty")]
125    pub mcp_server_ids: Vec<String>,
126    /// Directory names under `<plugin_dir>/skills/` that are valid skill
127    /// dirs (contain `SKILL.md`) and are therefore discoverable in place.
128    #[serde(default, skip_serializing_if = "Vec::is_empty")]
129    pub skill_dirs: Vec<String>,
130    /// Ids appended into `prompt-presets.json`.
131    #[serde(default, skip_serializing_if = "Vec::is_empty")]
132    pub preset_ids: Vec<String>,
133    /// Filenames copied into `bamboo_config::paths::workflows_dir()`.
134    #[serde(default, skip_serializing_if = "Vec::is_empty")]
135    pub workflow_filenames: Vec<String>,
136}
137
138impl RegisteredCapabilities {
139    pub fn is_empty(&self) -> bool {
140        self.mcp_server_ids.is_empty()
141            && self.skill_dirs.is_empty()
142            && self.preset_ids.is_empty()
143            && self.workflow_filenames.is_empty()
144    }
145
146    /// The capabilities present in `old` (a prior install's registered set)
147    /// but ABSENT from `self` (the set the new/upgraded install will register).
148    ///
149    /// These are exactly the entries an in-place upgrade must DE-register:
150    /// their ids/filenames vanish from provenance across the upgrade, so if
151    /// they are not actively removed here they leak — orphaned forever,
152    /// un-removable because no future uninstall knows they were ours. See the
153    /// upgrade sequence in [`crate::installer`] / `PLUGIN_PLAN.md`.
154    ///
155    /// Order-preserving relative to `old` (stable output for diffing/logging).
156    pub fn removed_since(&self, old: &RegisteredCapabilities) -> RegisteredCapabilities {
157        RegisteredCapabilities {
158            mcp_server_ids: subtract(&old.mcp_server_ids, &self.mcp_server_ids),
159            skill_dirs: subtract(&old.skill_dirs, &self.skill_dirs),
160            preset_ids: subtract(&old.preset_ids, &self.preset_ids),
161            workflow_filenames: subtract(&old.workflow_filenames, &self.workflow_filenames),
162        }
163    }
164}
165
166/// Elements of `from` not present in `remove`, preserving `from`'s order.
167fn subtract(from: &[String], remove: &[String]) -> Vec<String> {
168    let drop: HashSet<&str> = remove.iter().map(String::as_str).collect();
169    from.iter()
170        .filter(|value| !drop.contains(value.as_str()))
171        .cloned()
172        .collect()
173}
174
175/// Ownership classification of one declared capability id/filename against a
176/// shared store, for the REFUSE-on-conflict capability kinds (MCP servers,
177/// workflow files). Prompt presets do NOT use this — they rename on collision
178/// via bamboo-server's `ensure_unique_preset_id` instead.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum Ownership {
181    /// Not present in the shared store — safe to create AND record as
182    /// plugin-owned/removable.
183    New,
184    /// Present, and registered by THIS plugin's prior install — an upgrade
185    /// re-registering its own entry. Safe; stays recorded as plugin-owned.
186    OwnedReinstall,
187    /// Present and NOT owned by this plugin (a user's own entry, or another
188    /// plugin's). Must block the install — never recorded as removable.
189    ForeignConflict,
190}
191
192/// Classify one id against the shared store's current `existing` ids and the
193/// `owned_previously` ids that THIS plugin's prior install registered.
194pub fn classify_ownership(
195    id: &str,
196    existing: &HashSet<&str>,
197    owned_previously: &HashSet<&str>,
198) -> Ownership {
199    if !existing.contains(id) {
200        Ownership::New
201    } else if owned_previously.contains(id) {
202        Ownership::OwnedReinstall
203    } else {
204        Ownership::ForeignConflict
205    }
206}
207
208/// Result of reconciling a plugin's declared ids/filenames against a shared
209/// store for a REFUSE-on-conflict capability (MCP servers, workflow files).
210#[derive(Debug, Clone, Default, PartialEq, Eq)]
211pub struct ExclusiveReconciliation {
212    /// Genuinely-new plus this-plugin's-own-from-a-prior-install: register
213    /// these and record them as plugin-owned/removable in provenance.
214    pub to_register: Vec<String>,
215    /// Foreign collisions (exist, not owned by this plugin). If this is
216    /// non-empty the caller MUST refuse the install (return
217    /// [`PluginError::Conflict`]) — do not register or record any of these.
218    pub foreign_conflicts: Vec<String>,
219}
220
221/// Reconcile `declared` ids against the shared store for a REFUSE-on-conflict
222/// capability. `existing` = every id currently in the shared store;
223/// `owned_previously` = the ids THIS plugin's prior install recorded (empty
224/// for a fresh install). Pure — the caller supplies the store state (which,
225/// for MCP/workflows, only the app layer can read).
226///
227/// This is the pre-check that closes BLOCKER 1: a pre-existing collision with
228/// a non-plugin entry lands in `foreign_conflicts`, so it is NEVER registered
229/// and NEVER recorded as removable — uninstall can therefore only ever delete
230/// entries this plugin genuinely created.
231pub fn reconcile_exclusive(
232    declared: &[String],
233    existing: &[String],
234    owned_previously: &[String],
235) -> ExclusiveReconciliation {
236    let existing_set: HashSet<&str> = existing.iter().map(String::as_str).collect();
237    let owned_set: HashSet<&str> = owned_previously.iter().map(String::as_str).collect();
238
239    let mut result = ExclusiveReconciliation::default();
240    for id in declared {
241        match classify_ownership(id, &existing_set, &owned_set) {
242            Ownership::New | Ownership::OwnedReinstall => result.to_register.push(id.clone()),
243            Ownership::ForeignConflict => result.foreign_conflicts.push(id.clone()),
244        }
245    }
246    result
247}
248
249/// Lifecycle status of a provenance row — the crash-safety journal marker.
250///
251/// The installer writes a row as [`Self::Installing`] BEFORE it begins
252/// registering capabilities (MCP into `config.json`, prompts, workflow files),
253/// and flips it to [`Self::Installed`] only after the whole sequence succeeds.
254/// A row left [`Self::Installing`] therefore marks an install that was
255/// interrupted (a hard process kill mid-install): its `registered` set names
256/// what the install INTENDED to own, so on the next install/upgrade of that id
257/// the installer can (a) treat the leftover as this-plugin-owned — so the
258/// ownership pre-check doesn't false-`Conflict` on the plugin's own
259/// half-written entries — and (b) clean it up as an upgrade-over-incomplete.
260/// `uninstall` works on an `Installing` row too, so a user is never stranded
261/// having to hand-edit `config.json`.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
263#[serde(rename_all = "snake_case")]
264pub enum PluginInstallStatus {
265    /// A crash-safety journal marker: capability registration has begun but
266    /// not yet completed. `registered` records the INTENDED ownership set.
267    Installing,
268    /// The steady state: registration completed and provenance is authoritative.
269    /// The [`Default`] so a pre-journal `installed.json` (no `status` field)
270    /// deserializes as a completed install (backward compat).
271    #[default]
272    Installed,
273}
274
275/// A single installed plugin's provenance record.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277pub struct InstalledPlugin {
278    pub id: String,
279    /// The manifest `version` at the time of this install/upgrade.
280    pub version: String,
281    pub source: PluginSource,
282    /// `~/.bamboo/plugins/<id>` — where the plugin's own files live.
283    pub plugin_dir: PathBuf,
284    /// Caller-supplied timestamp (NOT computed internally — see module docs
285    /// on why: keeps this crate free of a hidden `Utc::now()` call so tests
286    /// and callers stay in full control of "when").
287    pub installed_at: DateTime<Utc>,
288    /// Crash-safety journal marker (see [`PluginInstallStatus`]). Defaults to
289    /// [`PluginInstallStatus::Installed`] so an `installed.json` written before
290    /// this field existed loads as a completed install.
291    #[serde(default)]
292    pub status: PluginInstallStatus,
293    #[serde(default)]
294    pub registered: RegisteredCapabilities,
295}
296
297/// The full `installed.json` document: `{ "plugins": [ ... ] }`.
298#[derive(Debug, Clone, Default, Serialize, Deserialize)]
299pub struct InstalledPlugins {
300    #[serde(default)]
301    pub plugins: Vec<InstalledPlugin>,
302}
303
304impl InstalledPlugins {
305    /// Load from `path`. A missing file is treated as an empty registry (this
306    /// is the state before any plugin has ever been installed) rather than an
307    /// error.
308    pub async fn load(path: &Path) -> PluginResult<Self> {
309        match fs::try_exists(path).await {
310            Ok(true) => {}
311            Ok(false) => return Ok(Self::default()),
312            Err(error) => return Err(PluginError::Io(error)),
313        }
314
315        let raw = fs::read_to_string(path).await?;
316        if raw.trim().is_empty() {
317            return Ok(Self::default());
318        }
319        let store: Self = serde_json::from_str(&raw)?;
320        Ok(store)
321    }
322
323    /// Persist to `path`, creating parent directories as needed.
324    ///
325    /// Writes to a sibling `<path>.tmp` first, then `rename`s it over `path`
326    /// — `rename` is atomic on the same filesystem (and `<path>.tmp` sits
327    /// right next to `path`, guaranteeing that), so a hard kill mid-write can
328    /// only ever leave a stray, harmless `.tmp` file behind, never a
329    /// truncated/corrupt `installed.json` a later `load` would choke on.
330    pub async fn save(&self, path: &Path) -> PluginResult<()> {
331        if let Some(parent) = path.parent() {
332            fs::create_dir_all(parent).await?;
333        }
334        let serialized = serde_json::to_string_pretty(self)?;
335        let tmp_path = tmp_path_for(path);
336        fs::write(&tmp_path, serialized).await?;
337        fs::rename(&tmp_path, path).await?;
338        Ok(())
339    }
340
341    /// Look up a plugin by id.
342    pub fn get(&self, id: &str) -> Option<&InstalledPlugin> {
343        self.plugins.iter().find(|plugin| plugin.id == id)
344    }
345
346    /// Insert or replace (by id) — an upgrade re-adds the same id with a new
347    /// version/registered set, so this is an upsert rather than an append.
348    pub fn add(&mut self, plugin: InstalledPlugin) {
349        self.remove(&plugin.id);
350        self.plugins.push(plugin);
351    }
352
353    /// Remove and return the entry for `id`, if any.
354    pub fn remove(&mut self, id: &str) -> Option<InstalledPlugin> {
355        let index = self.plugins.iter().position(|plugin| plugin.id == id)?;
356        Some(self.plugins.remove(index))
357    }
358
359    /// All installed plugins, in insertion order.
360    pub fn list(&self) -> &[InstalledPlugin] {
361        &self.plugins
362    }
363}
364
365/// `<path>` with `.tmp` appended to its file name (e.g. `installed.json` ->
366/// `installed.json.tmp`) — a sibling in the SAME directory as `path`, so the
367/// `rename` in [`InstalledPlugins::save`] is guaranteed same-filesystem and
368/// therefore atomic.
369fn tmp_path_for(path: &Path) -> PathBuf {
370    let mut tmp_name = path.file_name().unwrap_or_default().to_os_string();
371    tmp_name.push(".tmp");
372    path.with_file_name(tmp_name)
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    fn sample_plugin(id: &str) -> InstalledPlugin {
380        InstalledPlugin {
381            id: id.to_string(),
382            version: "0.1.0".to_string(),
383            source: PluginSource::LocalDir {
384                path: PathBuf::from("/tmp/source"),
385            },
386            plugin_dir: PathBuf::from(format!("/home/user/.bamboo/plugins/{id}")),
387            installed_at: DateTime::parse_from_rfc3339("2026-07-12T00:00:00Z")
388                .unwrap()
389                .with_timezone(&Utc),
390            status: PluginInstallStatus::Installed,
391            registered: RegisteredCapabilities {
392                mcp_server_ids: vec![],
393                skill_dirs: vec!["hello-world".to_string()],
394                preset_ids: vec!["hello_preset".to_string()],
395                workflow_filenames: vec![],
396            },
397        }
398    }
399
400    #[tokio::test]
401    async fn load_missing_file_returns_empty_registry() {
402        let dir = tempfile::tempdir().expect("tempdir");
403        let path = dir.path().join("plugins").join("installed.json");
404        let loaded = InstalledPlugins::load(&path).await.expect("load");
405        assert!(loaded.plugins.is_empty());
406    }
407
408    #[tokio::test]
409    async fn save_is_atomic_via_tmp_file_rename() {
410        let dir = tempfile::tempdir().expect("tempdir");
411        let path = dir.path().join("installed.json");
412        let tmp_path = tmp_path_for(&path);
413
414        let mut store = InstalledPlugins::default();
415        store.add(sample_plugin("hello-plugin"));
416        store.save(&path).await.expect("save");
417
418        assert!(path.exists(), "installed.json should exist after save");
419        assert!(
420            !tmp_path.exists(),
421            "the .tmp staging file must be renamed over the target, never left behind"
422        );
423
424        // A second save (e.g. an upgrade re-persisting the store) must go
425        // through the same write-tmp-then-rename path and leave no trace
426        // either.
427        let mut reloaded = InstalledPlugins::load(&path).await.expect("load");
428        reloaded.add(sample_plugin("other-plugin"));
429        reloaded.save(&path).await.expect("save again");
430        assert!(!tmp_path.exists());
431
432        let loaded = InstalledPlugins::load(&path).await.expect("load");
433        assert_eq!(loaded.plugins.len(), 2);
434    }
435
436    #[tokio::test]
437    async fn save_then_load_round_trips() {
438        let dir = tempfile::tempdir().expect("tempdir");
439        let path = dir.path().join("plugins").join("installed.json");
440
441        let mut store = InstalledPlugins::default();
442        store.add(sample_plugin("hello-plugin"));
443        store.add(sample_plugin("other-plugin"));
444        store.save(&path).await.expect("save");
445
446        let loaded = InstalledPlugins::load(&path).await.expect("load");
447        assert_eq!(loaded.plugins.len(), 2);
448        let hello = loaded.get("hello-plugin").expect("hello-plugin present");
449        assert_eq!(hello.version, "0.1.0");
450        assert_eq!(hello.registered.skill_dirs, vec!["hello-world".to_string()]);
451        assert_eq!(
452            hello.registered.preset_ids,
453            vec!["hello_preset".to_string()]
454        );
455        assert_eq!(
456            hello.source,
457            PluginSource::LocalDir {
458                path: PathBuf::from("/tmp/source")
459            }
460        );
461    }
462
463    #[tokio::test]
464    async fn add_upserts_by_id() {
465        let dir = tempfile::tempdir().expect("tempdir");
466        let path = dir.path().join("installed.json");
467
468        let mut store = InstalledPlugins::default();
469        store.add(sample_plugin("hello-plugin"));
470
471        let mut upgraded = sample_plugin("hello-plugin");
472        upgraded.version = "0.2.0".to_string();
473        store.add(upgraded);
474
475        assert_eq!(store.plugins.len(), 1);
476        assert_eq!(store.get("hello-plugin").unwrap().version, "0.2.0");
477
478        store.save(&path).await.expect("save");
479        let loaded = InstalledPlugins::load(&path).await.expect("load");
480        assert_eq!(loaded.plugins.len(), 1);
481        assert_eq!(loaded.get("hello-plugin").unwrap().version, "0.2.0");
482    }
483
484    #[tokio::test]
485    async fn remove_deletes_and_returns_entry() {
486        let mut store = InstalledPlugins::default();
487        store.add(sample_plugin("hello-plugin"));
488
489        let removed = store.remove("hello-plugin").expect("present before remove");
490        assert_eq!(removed.id, "hello-plugin");
491        assert!(store.get("hello-plugin").is_none());
492        assert!(store.remove("hello-plugin").is_none());
493    }
494
495    #[test]
496    fn reconcile_exclusive_fresh_install_splits_new_from_foreign() {
497        // Fresh install (no prior ownership): "a" is new, "b" collides with a
498        // user's own entry.
499        let declared = vec!["a".to_string(), "b".to_string()];
500        let existing = vec!["b".to_string(), "user-thing".to_string()];
501        let owned_previously: Vec<String> = vec![];
502
503        let reconciliation = reconcile_exclusive(&declared, &existing, &owned_previously);
504        assert_eq!(reconciliation.to_register, vec!["a".to_string()]);
505        assert_eq!(reconciliation.foreign_conflicts, vec!["b".to_string()]);
506    }
507
508    #[test]
509    fn reconcile_exclusive_upgrade_reregisters_own_but_refuses_new_foreign() {
510        // Upgrade: "a" was ours last time (owned reinstall, fine); "c" is new;
511        // "d" newly collides with a user entry that appeared since → foreign.
512        let declared = vec!["a".to_string(), "c".to_string(), "d".to_string()];
513        let existing = vec!["a".to_string(), "d".to_string()];
514        let owned_previously = vec!["a".to_string()];
515
516        let reconciliation = reconcile_exclusive(&declared, &existing, &owned_previously);
517        assert_eq!(
518            reconciliation.to_register,
519            vec!["a".to_string(), "c".to_string()]
520        );
521        assert_eq!(reconciliation.foreign_conflicts, vec!["d".to_string()]);
522    }
523
524    #[test]
525    fn classify_ownership_three_way() {
526        let existing: HashSet<&str> = ["x", "y"].into_iter().collect();
527        let owned: HashSet<&str> = ["y"].into_iter().collect();
528        assert_eq!(classify_ownership("z", &existing, &owned), Ownership::New);
529        assert_eq!(
530            classify_ownership("y", &existing, &owned),
531            Ownership::OwnedReinstall
532        );
533        assert_eq!(
534            classify_ownership("x", &existing, &owned),
535            Ownership::ForeignConflict
536        );
537    }
538
539    #[test]
540    fn removed_since_computes_dropped_capabilities_per_kind() {
541        let old = RegisteredCapabilities {
542            mcp_server_ids: vec!["srv-a".to_string(), "srv-b".to_string()],
543            skill_dirs: vec!["skill-a".to_string()],
544            preset_ids: vec!["preset-a".to_string(), "preset-b".to_string()],
545            workflow_filenames: vec!["wf-a.md".to_string()],
546        };
547        // New version drops srv-b and preset-a, keeps the rest, adds srv-c.
548        let new = RegisteredCapabilities {
549            mcp_server_ids: vec!["srv-a".to_string(), "srv-c".to_string()],
550            skill_dirs: vec!["skill-a".to_string()],
551            preset_ids: vec!["preset-b".to_string()],
552            workflow_filenames: vec!["wf-a.md".to_string()],
553        };
554
555        let removed = new.removed_since(&old);
556        assert_eq!(removed.mcp_server_ids, vec!["srv-b".to_string()]);
557        assert!(removed.skill_dirs.is_empty());
558        assert_eq!(removed.preset_ids, vec!["preset-a".to_string()]);
559        assert!(removed.workflow_filenames.is_empty());
560    }
561
562    #[tokio::test]
563    async fn load_empty_file_returns_empty_registry() {
564        let dir = tempfile::tempdir().expect("tempdir");
565        let path = dir.path().join("installed.json");
566        tokio::fs::create_dir_all(path.parent().unwrap())
567            .await
568            .unwrap();
569        tokio::fs::write(&path, "").await.unwrap();
570
571        let loaded = InstalledPlugins::load(&path).await.expect("load");
572        assert!(loaded.plugins.is_empty());
573    }
574}