ironclaw 0.22.0

Secure personal AI assistant that protects your data and expands its capabilities on the fly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Registry catalog: loads manifests from disk, provides list/search/resolve operations.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::registry::embedded;
use crate::registry::manifest::{BundleDefinition, BundlesFile, ExtensionManifest, ManifestKind};

/// Error type for registry operations.
#[derive(Debug, thiserror::Error)]
pub enum RegistryError {
    #[error("Registry directory not found: {0}")]
    DirectoryNotFound(PathBuf),

    #[error("Failed to read manifest {path}: {reason}")]
    ManifestRead { path: PathBuf, reason: String },

    #[error("Failed to parse manifest {path}: {reason}")]
    ManifestParse { path: PathBuf, reason: String },

    #[error("Extension not found: {0}")]
    ExtensionNotFound(String),

    #[error("'{name}' already installed at {path}. Use --force to overwrite.")]
    AlreadyInstalled {
        name: String,
        path: std::path::PathBuf,
    },

    // `url` is stored for programmatic access (logs, retries) but intentionally
    // omitted from the Display message to avoid leaking internal artifact URLs
    // to end users.
    #[error("Artifact download failed: {reason}")]
    DownloadFailed { url: String, reason: String },

    #[error("Invalid extension manifest for '{name}' field '{field}': {reason}")]
    InvalidManifest {
        name: String,
        field: &'static str,
        reason: String,
    },

    #[error("Checksum verification failed: expected {expected_sha256}, got {actual_sha256}")]
    ChecksumMismatch {
        url: String,
        expected_sha256: String,
        actual_sha256: String,
    },

    #[error("Missing SHA256 checksum for '{name}' artifact. Use --build to build from source.")]
    MissingChecksum { name: String },

    #[error(
        "Source fallback unavailable for '{name}' after artifact install failed. Retry artifact download or run from a repository checkout."
    )]
    SourceFallbackUnavailable {
        name: String,
        source_dir: PathBuf,
        artifact_error: Box<RegistryError>,
    },

    #[error("Artifact install and source fallback both failed for '{name}'.")]
    InstallFallbackFailed {
        name: String,
        artifact_error: Box<RegistryError>,
        source_error: Box<RegistryError>,
    },

    #[error(
        "Ambiguous name '{name}': exists as both {kind_a} and {kind_b}. Use '{prefix_a}/{name}' or '{prefix_b}/{name}'."
    )]
    AmbiguousName {
        name: String,
        kind_a: &'static str,
        prefix_a: &'static str,
        kind_b: &'static str,
        prefix_b: &'static str,
    },

    #[error("Bundle not found: {0}")]
    BundleNotFound(String),

    #[error("Failed to read bundles file: {0}")]
    BundlesRead(String),

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

/// Central catalog loaded from the `registry/` directory.
#[derive(Debug, Clone)]
pub struct RegistryCatalog {
    /// All loaded manifests, keyed by "<kind>/<name>" (e.g. "tools/github").
    manifests: HashMap<String, ExtensionManifest>,

    /// Bundle definitions from `_bundles.json`.
    bundles: HashMap<String, BundleDefinition>,

    /// Root directory of the registry.
    root: PathBuf,
}

impl RegistryCatalog {
    /// Find the `registry/` directory by searching relative to cwd, the executable,
    /// and `CARGO_MANIFEST_DIR`. Returns `None` if the directory cannot be found
    /// (non-fatal at startup).
    pub fn find_dir() -> Option<PathBuf> {
        // Try relative to current directory (for dev usage)
        if let Ok(cwd) = std::env::current_dir() {
            let candidate = cwd.join("registry");
            if candidate.is_dir() {
                return Some(candidate);
            }
        }

        // Try relative to executable (covers installed binary, target/debug/, target/release/)
        if let Ok(exe) = std::env::current_exe()
            && let Some(parent) = exe.parent()
        {
            // Walk up to 3 levels: exe dir, parent (target/release -> target), grandparent (-> repo root)
            let mut dir = Some(parent);
            for _ in 0..3 {
                if let Some(d) = dir {
                    let candidate = d.join("registry");
                    if candidate.is_dir() {
                        return Some(candidate);
                    }
                    dir = d.parent();
                }
            }
        }

        // Try CARGO_MANIFEST_DIR (compile-time, works in dev builds)
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let candidate = manifest_dir.join("registry");
        if candidate.is_dir() {
            return Some(candidate);
        }

        None
    }

    /// Try to load from disk; if `registry/` cannot be found, fall back to
    /// manifests embedded into the binary at compile time.
    pub fn load_or_embedded() -> Result<Self, RegistryError> {
        if let Some(dir) = Self::find_dir() {
            return Self::load(&dir);
        }

        // Fall back to embedded catalog
        let manifests = embedded::load_embedded();
        let bundles = embedded::load_embedded_bundles();

        tracing::info!(
            "Loaded embedded registry catalog ({} extensions, {} bundles)",
            manifests.len(),
            bundles.len()
        );

        Ok(Self {
            manifests,
            bundles,
            root: PathBuf::new(),
        })
    }

    /// Load the catalog from a registry directory.
    ///
    /// Expects the structure:
    /// ```text
    /// registry/
    /// ├── tools/*.json
    /// ├── channels/*.json
    /// └── _bundles.json
    /// ```
    pub fn load(registry_dir: &Path) -> Result<Self, RegistryError> {
        if !registry_dir.exists() {
            return Err(RegistryError::DirectoryNotFound(registry_dir.to_path_buf()));
        }

        let mut manifests = HashMap::new();

        // Load tools
        let tools_dir = registry_dir.join("tools");
        if tools_dir.is_dir() {
            Self::load_manifests_from_dir(&tools_dir, "tools", &mut manifests)?;
        }

        // Load channels
        let channels_dir = registry_dir.join("channels");
        if channels_dir.is_dir() {
            Self::load_manifests_from_dir(&channels_dir, "channels", &mut manifests)?;
        }

        // Load MCP servers
        let mcp_servers_dir = registry_dir.join("mcp-servers");
        if mcp_servers_dir.is_dir() {
            Self::load_manifests_from_dir(&mcp_servers_dir, "mcp-servers", &mut manifests)?;
        }

        // Load bundles
        let bundles_path = registry_dir.join("_bundles.json");
        let bundles = if bundles_path.is_file() {
            let content = std::fs::read_to_string(&bundles_path).map_err(|e| {
                RegistryError::BundlesRead(format!("{}: {}", bundles_path.display(), e))
            })?;
            let bundles_file: BundlesFile = serde_json::from_str(&content).map_err(|e| {
                RegistryError::BundlesRead(format!("{}: {}", bundles_path.display(), e))
            })?;
            bundles_file.bundles
        } else {
            HashMap::new()
        };

        Ok(Self {
            manifests,
            bundles,
            root: registry_dir.to_path_buf(),
        })
    }

    fn load_manifests_from_dir(
        dir: &Path,
        kind_prefix: &str,
        manifests: &mut HashMap<String, ExtensionManifest>,
    ) -> Result<(), RegistryError> {
        let entries = std::fs::read_dir(dir).map_err(|e| RegistryError::ManifestRead {
            path: dir.to_path_buf(),
            reason: e.to_string(),
        })?;

        for entry in entries {
            let entry = entry.map_err(|e| RegistryError::ManifestRead {
                path: dir.to_path_buf(),
                reason: e.to_string(),
            })?;

            let path = entry.path();
            if !path.is_file() || path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }

            let content =
                std::fs::read_to_string(&path).map_err(|e| RegistryError::ManifestRead {
                    path: path.clone(),
                    reason: e.to_string(),
                })?;

            let manifest: ExtensionManifest =
                serde_json::from_str(&content).map_err(|e| RegistryError::ManifestParse {
                    path: path.clone(),
                    reason: e.to_string(),
                })?;

            let key = format!("{}/{}", kind_prefix, manifest.name);
            manifests.insert(key, manifest);
        }

        Ok(())
    }

    /// The root directory this catalog was loaded from.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Get all manifests.
    pub fn all(&self) -> Vec<&ExtensionManifest> {
        let mut items: Vec<_> = self.manifests.values().collect();
        items.sort_by(|a, b| a.name.cmp(&b.name));
        items
    }

    /// List manifests, optionally filtered by kind and/or tag.
    pub fn list(&self, kind: Option<ManifestKind>, tag: Option<&str>) -> Vec<&ExtensionManifest> {
        let mut results: Vec<_> = self
            .manifests
            .values()
            .filter(|m| kind.is_none_or(|k| m.kind == k))
            .filter(|m| tag.is_none_or(|t| m.tags.iter().any(|mt| mt == t)))
            .collect();
        results.sort_by(|a, b| a.name.cmp(&b.name));
        results
    }

    /// Get a manifest by name. Tries exact key match first ("tools/github"),
    /// then searches by bare name ("github").
    ///
    /// If a bare name matches more than one prefix, returns `None`.
    /// Use a qualified key ("tools/github", "channels/telegram", or
    /// "mcp-servers/notion") to disambiguate.
    pub fn get(&self, name: &str) -> Option<&ExtensionManifest> {
        // Try exact key first
        if let Some(m) = self.manifests.get(name) {
            return Some(m);
        }

        // Try with kind prefix, detecting collisions
        let candidates: Vec<_> = ["tools", "channels", "mcp-servers"]
            .iter()
            .filter_map(|prefix| self.manifests.get(&format!("{}/{}", prefix, name)))
            .collect();

        if candidates.len() == 1 {
            Some(candidates[0])
        } else {
            None // ambiguous or not found
        }
    }

    /// Get a manifest by name, returning a `Result` with an explicit error for
    /// ambiguous bare names.
    pub fn get_strict(&self, name: &str) -> Result<&ExtensionManifest, RegistryError> {
        // Try exact key first
        if let Some(m) = self.manifests.get(name) {
            return Ok(m);
        }

        let prefixes: &[(&str, &str)] = &[
            ("tools", "tool"),
            ("channels", "channel"),
            ("mcp-servers", "mcp_server"),
        ];

        let matches: Vec<_> = prefixes
            .iter()
            .filter(|(prefix, _)| self.manifests.contains_key(&format!("{}/{}", prefix, name)))
            .collect();

        match matches.len() {
            0 => Err(RegistryError::ExtensionNotFound(name.to_string())),
            1 => {
                let (prefix, _) = matches[0];
                let key = format!("{}/{}", prefix, name);
                self.manifests
                    .get(&key)
                    .ok_or_else(|| RegistryError::ExtensionNotFound(name.to_string()))
            }
            _ => {
                let (prefix_a, kind_a) = matches[0];
                let (prefix_b, kind_b) = matches[1];
                Err(RegistryError::AmbiguousName {
                    name: name.to_string(),
                    kind_a,
                    prefix_a,
                    kind_b,
                    prefix_b,
                })
            }
        }
    }

    /// Get the full key ("tools/github", "channels/telegram", or
    /// "mcp-servers/notion") for a manifest.
    pub fn key_for(&self, name: &str) -> Option<String> {
        if self.manifests.contains_key(name) {
            return Some(name.to_string());
        }

        let matches: Vec<String> = ["tools", "channels", "mcp-servers"]
            .iter()
            .filter_map(|prefix| {
                let key = format!("{}/{}", prefix, name);
                if self.manifests.contains_key(&key) {
                    Some(key)
                } else {
                    None
                }
            })
            .collect();

        if matches.len() == 1 {
            matches.into_iter().next()
        } else {
            None // ambiguous or not found
        }
    }

    /// Search manifests by query string (matches name, display_name, description, keywords).
    pub fn search(&self, query: &str) -> Vec<&ExtensionManifest> {
        let query_lower = query.to_lowercase();
        let tokens: Vec<&str> = query_lower.split_whitespace().collect();

        let mut scored: Vec<(&ExtensionManifest, usize)> = self
            .manifests
            .values()
            .filter_map(|m| {
                let score = Self::score_manifest(m, &tokens);
                if score > 0 { Some((m, score)) } else { None }
            })
            .collect();

        scored.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.name.cmp(&b.0.name)));
        scored.into_iter().map(|(m, _)| m).collect()
    }

    fn score_manifest(manifest: &ExtensionManifest, tokens: &[&str]) -> usize {
        let mut score = 0;
        let name_lower = manifest.name.to_lowercase();
        let display_lower = manifest.display_name.to_lowercase();
        let desc_lower = manifest.description.to_lowercase();

        for token in tokens {
            if name_lower == *token {
                score += 10;
            } else if name_lower.contains(token) {
                score += 5;
            }

            if display_lower == *token {
                score += 8;
            } else if display_lower.contains(token) {
                score += 4;
            }

            if desc_lower.contains(token) {
                score += 2;
            }

            for kw in &manifest.keywords {
                if kw.to_lowercase() == *token {
                    score += 6;
                } else if kw.to_lowercase().contains(token) {
                    score += 3;
                }
            }

            for tag in &manifest.tags {
                if tag.to_lowercase() == *token {
                    score += 4;
                }
            }
        }

        score
    }

    /// Get a bundle definition by name.
    pub fn get_bundle(&self, name: &str) -> Option<&BundleDefinition> {
        self.bundles.get(name)
    }

    /// List all bundle names.
    pub fn bundle_names(&self) -> Vec<&str> {
        let mut names: Vec<_> = self.bundles.keys().map(|s| s.as_str()).collect();
        names.sort();
        names
    }

    /// Resolve a bundle into its constituent manifests.
    /// Returns the manifests and any extension keys that couldn't be found.
    pub fn resolve_bundle(
        &self,
        bundle_name: &str,
    ) -> Result<(Vec<&ExtensionManifest>, Vec<String>), RegistryError> {
        let bundle = self
            .bundles
            .get(bundle_name)
            .ok_or_else(|| RegistryError::BundleNotFound(bundle_name.to_string()))?;

        let mut found = Vec::new();
        let mut missing = Vec::new();

        for ext_key in &bundle.extensions {
            if let Some(manifest) = self.manifests.get(ext_key) {
                found.push(manifest);
            } else {
                missing.push(ext_key.clone());
            }
        }

        Ok((found, missing))
    }

    /// Check if a name refers to a bundle rather than an individual extension.
    pub fn is_bundle(&self, name: &str) -> bool {
        self.bundles.contains_key(name)
    }

    /// Resolve a name to either a single manifest or the manifests in a bundle.
    /// Returns (manifests, bundle_definition_if_bundle).
    pub fn resolve(
        &self,
        name: &str,
    ) -> Result<(Vec<&ExtensionManifest>, Option<&BundleDefinition>), RegistryError> {
        // Check bundle first
        if let Some(bundle) = self.bundles.get(name) {
            let (manifests, missing) = self.resolve_bundle(name)?;
            if !missing.is_empty() {
                tracing::warn!(
                    "Bundle '{}' references missing extensions: {:?}",
                    name,
                    missing
                );
            }
            return Ok((manifests, Some(bundle)));
        }

        // Single extension (use get_strict to catch ambiguous bare names)
        let manifest = self.get_strict(name)?;
        Ok((vec![manifest], None))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    fn create_test_registry(dir: &Path) {
        let tools_dir = dir.join("tools");
        let channels_dir = dir.join("channels");
        let mcp_dir = dir.join("mcp-servers");
        fs::create_dir_all(&tools_dir).unwrap();
        fs::create_dir_all(&channels_dir).unwrap();
        fs::create_dir_all(&mcp_dir).unwrap();

        fs::write(
            tools_dir.join("slack.json"),
            r#"{
                "name": "slack",
                "display_name": "Slack",
                "kind": "tool",
                "version": "0.1.0",
                "description": "Post messages via Slack API",
                "keywords": ["messaging", "chat"],
                "source": {
                    "dir": "tools-src/slack",
                    "capabilities": "slack-tool.capabilities.json",
                    "crate_name": "slack-tool"
                },
                "auth_summary": {
                    "method": "oauth",
                    "provider": "Slack",
                    "secrets": ["slack_bot_token"]
                },
                "tags": ["default", "messaging"]
            }"#,
        )
        .unwrap();

        fs::write(
            tools_dir.join("github.json"),
            r#"{
                "name": "github",
                "display_name": "GitHub",
                "kind": "tool",
                "version": "0.1.0",
                "description": "GitHub integration for issues and PRs",
                "keywords": ["code", "git"],
                "source": {
                    "dir": "tools-src/github",
                    "capabilities": "github-tool.capabilities.json",
                    "crate_name": "github-tool"
                },
                "tags": ["default", "development"]
            }"#,
        )
        .unwrap();

        fs::write(
            channels_dir.join("telegram.json"),
            r#"{
                "name": "telegram",
                "display_name": "Telegram",
                "kind": "channel",
                "version": "0.1.0",
                "description": "Telegram Bot API channel",
                "source": {
                    "dir": "channels-src/telegram",
                    "capabilities": "telegram.capabilities.json",
                    "crate_name": "telegram-channel"
                },
                "tags": ["messaging"]
            }"#,
        )
        .unwrap();

        fs::write(
            mcp_dir.join("notion.json"),
            r#"{
                "name": "notion",
                "display_name": "Notion",
                "kind": "mcp_server",
                "description": "Connect to Notion for pages and databases",
                "keywords": ["notes", "wiki"],
                "url": "https://mcp.notion.com/mcp",
                "auth": "dcr"
            }"#,
        )
        .unwrap();

        fs::write(
            dir.join("_bundles.json"),
            r#"{
                "bundles": {
                    "default": {
                        "display_name": "Recommended",
                        "extensions": ["tools/slack", "tools/github", "channels/telegram"]
                    },
                    "messaging": {
                        "display_name": "Messaging",
                        "extensions": ["tools/slack", "channels/telegram"],
                        "shared_auth": null
                    }
                }
            }"#,
        )
        .unwrap();
    }

    #[test]
    fn test_load_catalog() {
        let tmp = tempfile::tempdir().unwrap();
        create_test_registry(tmp.path());

        let catalog = RegistryCatalog::load(tmp.path()).unwrap();
        assert_eq!(catalog.all().len(), 4);
    }

    #[test]
    fn test_list_by_kind() {
        let tmp = tempfile::tempdir().unwrap();
        create_test_registry(tmp.path());

        let catalog = RegistryCatalog::load(tmp.path()).unwrap();
        let tools = catalog.list(Some(ManifestKind::Tool), None);
        assert_eq!(tools.len(), 2);

        let channels = catalog.list(Some(ManifestKind::Channel), None);
        assert_eq!(channels.len(), 1);

        let mcp_servers = catalog.list(Some(ManifestKind::McpServer), None);
        assert_eq!(mcp_servers.len(), 1);
    }

    #[test]
    fn test_list_by_tag() {
        let tmp = tempfile::tempdir().unwrap();
        create_test_registry(tmp.path());

        let catalog = RegistryCatalog::load(tmp.path()).unwrap();
        let defaults = catalog.list(None, Some("default"));
        assert_eq!(defaults.len(), 2);

        let messaging = catalog.list(None, Some("messaging"));
        assert_eq!(messaging.len(), 2); // slack (tool) and telegram (channel) both have "messaging" tag
    }

    #[test]
    fn test_get_by_name() {
        let tmp = tempfile::tempdir().unwrap();
        create_test_registry(tmp.path());

        let catalog = RegistryCatalog::load(tmp.path()).unwrap();

        // Full key
        assert!(catalog.get("tools/slack").is_some());
        assert!(catalog.get("mcp-servers/notion").is_some());

        // Bare name
        assert!(catalog.get("slack").is_some());
        assert!(catalog.get("telegram").is_some());
        assert!(catalog.get("notion").is_some());

        // Missing
        assert!(catalog.get("nonexistent").is_none());
    }

    #[test]
    fn test_search() {
        let tmp = tempfile::tempdir().unwrap();
        create_test_registry(tmp.path());

        let catalog = RegistryCatalog::load(tmp.path()).unwrap();

        let results = catalog.search("slack");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "slack");

        let results = catalog.search("messaging");
        assert!(!results.is_empty());

        let results = catalog.search("nonexistent query");
        assert!(results.is_empty());
    }

    #[test]
    fn test_resolve_bundle() {
        let tmp = tempfile::tempdir().unwrap();
        create_test_registry(tmp.path());

        let catalog = RegistryCatalog::load(tmp.path()).unwrap();

        let (manifests, missing) = catalog.resolve_bundle("default").unwrap();
        assert_eq!(manifests.len(), 3);
        assert!(missing.is_empty());

        assert!(catalog.resolve_bundle("nonexistent").is_err());
    }

    #[test]
    fn test_resolve_single_or_bundle() {
        let tmp = tempfile::tempdir().unwrap();
        create_test_registry(tmp.path());

        let catalog = RegistryCatalog::load(tmp.path()).unwrap();

        // Single extension
        let (manifests, bundle) = catalog.resolve("slack").unwrap();
        assert_eq!(manifests.len(), 1);
        assert!(bundle.is_none());

        // Bundle
        let (manifests, bundle) = catalog.resolve("default").unwrap();
        assert_eq!(manifests.len(), 3);
        assert!(bundle.is_some());
    }

    #[test]
    fn test_bundle_names() {
        let tmp = tempfile::tempdir().unwrap();
        create_test_registry(tmp.path());

        let catalog = RegistryCatalog::load(tmp.path()).unwrap();
        let names = catalog.bundle_names();
        assert_eq!(names, vec!["default", "messaging"]);
    }

    #[test]
    fn test_directory_not_found() {
        let result = RegistryCatalog::load(Path::new("/nonexistent/path"));
        assert!(result.is_err());
    }

    #[test]
    fn test_load_or_embedded_succeeds() {
        // Should always succeed: either finds registry/ on disk or falls back to embedded
        let catalog = RegistryCatalog::load_or_embedded().unwrap();
        // At minimum, the embedded catalog from the repo should have entries
        assert!(!catalog.all().is_empty() || !catalog.bundle_names().is_empty());
    }

    #[test]
    fn test_bundle_entries_resolve_against_real_registry() {
        // Load the actual registry/ directory (catches stale bundle refs after renames)
        let catalog = RegistryCatalog::load_or_embedded().unwrap();

        for bundle_name in catalog.bundle_names() {
            let (manifests, missing) = catalog.resolve_bundle(bundle_name).unwrap();
            assert!(
                missing.is_empty(),
                "Bundle '{}' has unresolved entries: {:?}. \
                 Check that _bundles.json entries match manifest name fields.",
                bundle_name,
                missing
            );
            assert!(
                !manifests.is_empty(),
                "Bundle '{}' resolved to zero manifests",
                bundle_name
            );
        }
    }
}