collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
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
//! Marketplace registry — register remote plugin marketplaces and resolve plugin sources.
//!
//! A marketplace is a GitHub repo containing a marketplace index that lists
//! available plugins. The index is checked at:
//! 1. `.collet-plugin/marketplace.json` (collet native)
//! 2. `.claude-plugin/marketplace.json` (Claude Code compatible)
//!
//! The registry maps short marketplace names to `owner/repo` references
//! and is persisted at `~/.collet/marketplaces.json`.
//!
//! # Workflow
//!
//! 1. `/plugin marketplace add epicsagas/plugins`
//!    → stored as `{ "plugins": "epicsagas/plugins" }`
//!
//! 2. `/plugin install epic@plugins`
//!    → look up `plugins` → fetch marketplace.json → resolve `owner/repo`
//!    → clone plugin repo

use std::collections::BTreeMap;
use std::path::PathBuf;

use anyhow::{Context, Result};

/// Path to the persistent marketplace registry file.
pub fn registry_path() -> PathBuf {
    crate::config::config_dir().join("marketplaces.json")
}

/// Persistent registry mapping marketplace short-names to `owner/repo`.
#[derive(Debug, Clone)]
pub struct MarketplaceRegistry {
    /// Sorted map for stable serialization: `name` → `owner/repo`.
    entries: BTreeMap<String, String>,
}

impl MarketplaceRegistry {
    /// Load the registry from disk. Returns an empty registry if the file does not exist.
    pub fn load() -> Result<Self> {
        let path = registry_path();
        if !path.exists() {
            return Ok(Self {
                entries: BTreeMap::new(),
            });
        }
        let content = std::fs::read_to_string(&path)
            .with_context(|| format!("Failed to read {}", path.display()))?;
        let entries: BTreeMap<String, String> = serde_json::from_str(&content)
            .with_context(|| format!("Failed to parse {}", path.display()))?;
        Ok(Self { entries })
    }

    /// Persist the registry to disk.
    pub fn save(&self) -> Result<()> {
        let path = registry_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let content = serde_json::to_string_pretty(&self.entries)?;
        std::fs::write(&path, content)
            .with_context(|| format!("Failed to write {}", path.display()))?;
        Ok(())
    }

    /// Register a marketplace. Validates `name` and `owner_repo` format.
    ///
    /// Returns `true` if this is a new entry, `false` if it was updated.
    pub fn add(&mut self, name: &str, owner_repo: &str) -> Result<bool> {
        validate_marketplace_name(name)?;
        validate_owner_repo(owner_repo)?;
        let is_new = !self.entries.contains_key(name);
        // Preserve previous value so we can roll back if save() fails.
        let previous = self
            .entries
            .insert(name.to_string(), owner_repo.to_string());
        if let Err(e) = self.save() {
            match previous {
                Some(prev) => {
                    self.entries.insert(name.to_string(), prev);
                }
                None => {
                    self.entries.remove(name);
                }
            }
            return Err(e);
        }
        Ok(is_new)
    }

    /// Remove a marketplace by name. Returns `true` if it existed.
    pub fn remove(&mut self, name: &str) -> Result<bool> {
        let existed = self.entries.remove(name).is_some();
        if existed {
            self.save()?;
        }
        Ok(existed)
    }

    /// Return a sorted list of `(name, owner_repo)` pairs.
    pub fn list(&self) -> Vec<(&str, &str)> {
        self.entries
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect()
    }

    /// Look up the `owner/repo` for a given marketplace name.
    pub fn get(&self, name: &str) -> Option<&str> {
        self.entries.get(name).map(|s| s.as_str())
    }

    /// Number of registered marketplaces.
    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// A plugin entry resolved from a marketplace index.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct ResolvedPlugin {
    /// Plugin name as listed in marketplace.json.
    pub name: String,
    /// The `owner/repo` to clone (resolved from `source` field).
    pub owner_repo: String,
    /// Description from marketplace.json.
    pub description: String,
}

/// Fetch a marketplace's plugin index from GitHub.
///
/// Tries `main` branch first, then `master`. Returns the list of available plugins.
///
/// Checks both `.collet-plugin/marketplace.json` and `.claude-plugin/marketplace.json`.
pub fn fetch_marketplace_index(marketplace_owner_repo: &str) -> Result<Vec<ResolvedPlugin>> {
    let branches = ["main", "master"];
    let manifest_paths = [
        ".collet-plugin/marketplace.json",
        ".claude-plugin/marketplace.json",
    ];
    let mut last_err = String::new();

    for branch in &branches {
        for manifest_path in &manifest_paths {
            let url = format!(
                "https://raw.githubusercontent.com/{marketplace_owner_repo}/{branch}/{manifest_path}"
            );
            match fetch_url(&url) {
                Ok(body) => {
                    return parse_index(marketplace_owner_repo, &body);
                }
                Err(e) => {
                    last_err = format!("{e}");
                    tracing::debug!(url = %url, error = %e, "Failed to fetch marketplace index");
                }
            }
        }
    }

    anyhow::bail!(
        "Could not fetch marketplace index for `{marketplace_owner_repo}`. \
         Make sure the repo contains `.collet-plugin/marketplace.json` or `.claude-plugin/marketplace.json`. \
         Last error: {last_err}"
    )
}

/// Resolve `name@marketplace` into a `ResolvedPlugin`.
///
/// Parses the `@` syntax, looks up the marketplace in the registry, fetches its index,
/// and returns the matching plugin entry.
pub fn resolve(spec: &str) -> Result<ResolvedPlugin> {
    let (plugin_name, marketplace_name) = parse_at_spec(spec)?;

    let registry = MarketplaceRegistry::load()?;
    let marketplace_owner_repo = registry.get(marketplace_name).ok_or_else(|| {
        let known: Vec<&str> = registry.list().iter().map(|(n, _)| *n).collect();
        if known.is_empty() {
            anyhow::anyhow!(
                "Marketplace '{marketplace_name}' is not registered.\n\
                 Register it first: `/plugin marketplace add <owner/repo>`"
            )
        } else {
            anyhow::anyhow!(
                "Marketplace '{marketplace_name}' is not registered.\n\
                 Known marketplaces: {}\n\
                 Register with: `/plugin marketplace add <owner/repo>`",
                known.join(", ")
            )
        }
    })?;

    let plugins = fetch_marketplace_index(marketplace_owner_repo)?;

    plugins
        .into_iter()
        .find(|p| p.name == plugin_name)
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Plugin '{plugin_name}' not found in marketplace '{marketplace_name}'.\n\
                 Run `/plugin marketplace list` to see registered marketplaces."
            )
        })
}

/// Derive a short marketplace name from an `owner/repo` string.
///
/// Strips common suffixes (`-marketplace`, `-plugins`, `-registry`, `-plugin`) from the repo name.
/// Example: `obra/superpowers-marketplace` → `"superpowers"`
pub fn derive_marketplace_name(owner_repo: &str) -> &str {
    let repo = owner_repo.split('/').next_back().unwrap_or(owner_repo);
    for suffix in &["-marketplace", "-plugins", "-registry", "-plugin"] {
        if let Some(stripped) = repo.strip_suffix(suffix)
            && !stripped.is_empty()
        {
            return stripped;
        }
    }
    repo
}

// ── Helpers ────────────────────────────────────────────────────────────────────

/// Parse `"name@marketplace"` into `(name, marketplace)`.
pub fn parse_at_spec(spec: &str) -> Result<(&str, &str)> {
    let at = spec.rfind('@').ok_or_else(|| {
        anyhow::anyhow!("Expected `<plugin>@<marketplace>` or `<owner/repo>` format, got `{spec}`")
    })?;
    let name = &spec[..at];
    let marketplace = &spec[at + 1..];
    if name.is_empty() || marketplace.is_empty() {
        anyhow::bail!("Plugin name and marketplace name must not be empty in `{spec}`");
    }
    Ok((name, marketplace))
}

/// Returns `true` if `spec` uses the `name@marketplace` syntax.
pub fn is_at_spec(spec: &str) -> bool {
    spec.contains('@') && !spec.starts_with('@')
}

/// Returns `true` if `spec` looks like a direct `owner/repo` GitHub reference.
pub fn is_owner_repo(spec: &str) -> bool {
    let parts: Vec<&str> = spec.splitn(2, '/').collect();
    parts.len() == 2 && !parts[0].is_empty() && !parts[1].is_empty() && !spec.contains('@')
}

fn validate_marketplace_name(name: &str) -> Result<()> {
    if name.is_empty() {
        anyhow::bail!("Marketplace name cannot be empty");
    }
    if name.contains('\0') || name.contains('/') || name.contains('\\') {
        anyhow::bail!("Invalid marketplace name: {:?}", name);
    }
    let valid = name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.');
    if !valid {
        anyhow::bail!(
            "Invalid marketplace name {:?}: only ASCII alphanumeric, '-', '_', '.' allowed",
            name
        );
    }
    Ok(())
}

fn validate_owner_repo(owner_repo: &str) -> Result<()> {
    let parts: Vec<&str> = owner_repo.splitn(2, '/').collect();
    if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
        anyhow::bail!(
            "Expected `owner/repo` format, got `{owner_repo}`\n\
             Example: `obra/superpowers-marketplace`"
        );
    }
    if parts[1].contains('/') {
        anyhow::bail!("repo name must not contain slashes");
    }
    // Strict allowlist: GitHub usernames and repo names permit only alphanumeric, '-', '_', '.'
    let valid_component = |s: &str| {
        s.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
    };
    if !valid_component(parts[0]) || !valid_component(parts[1]) {
        anyhow::bail!(
            "Invalid `owner/repo` `{owner_repo}`: only ASCII alphanumeric, '-', '_', '.' allowed"
        );
    }
    Ok(())
}

/// Parse a marketplace.json body and resolve sources against `marketplace_owner_repo`.
fn parse_index(marketplace_owner_repo: &str, body: &str) -> Result<Vec<ResolvedPlugin>> {
    let raw: serde_json::Value =
        serde_json::from_str(body).context("Failed to parse marketplace.json")?;

    let plugins = raw
        .get("plugins")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("marketplace.json missing `plugins` array"))?;

    let mut result = Vec::new();
    for p in plugins {
        let name = match p.get("name").and_then(|v| v.as_str()) {
            Some(n) if !n.is_empty() => n.to_string(),
            _ => continue,
        };
        // Validate name with the same allowlist used for registry entries.
        if validate_marketplace_name(&name).is_err() {
            tracing::debug!(
                name,
                "Skipping plugin with invalid name in marketplace.json"
            );
            continue;
        }

        let source = p
            .get("source")
            .and_then(|v| v.as_str())
            .unwrap_or("./")
            .to_string();
        // Strip terminal ANSI escape sequences from description to prevent injection
        // when the text is displayed in a terminal.
        let raw_desc = p
            .get("description")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        // Remove ESC-led sequences (\x1b[...m) and lone ESC characters.
        let description = {
            let mut out = String::with_capacity(raw_desc.len());
            let mut chars = raw_desc.chars().peekable();
            while let Some(ch) = chars.next() {
                if ch == '\x1b' {
                    // Skip the entire escape sequence
                    if chars.peek() == Some(&'[') {
                        chars.next();
                        for c in chars.by_ref() {
                            if c.is_ascii_alphabetic() {
                                break;
                            }
                        }
                    }
                } else {
                    out.push(ch);
                }
            }
            out
        };

        // Resolve source to an owner/repo:
        // - "owner/repo"   → use directly (validated against allowlist)
        // - "./"           → use the marketplace repo itself
        // - "./subdir"     → unsupported for now; treat as marketplace repo
        let owner_repo = if is_owner_repo(&source) {
            // Validate before use: a malicious marketplace.json could inject crafted
            // source values that reach `git clone` in install_from_github.
            validate_owner_repo(&source).with_context(|| {
                format!("Invalid source `{source}` in marketplace.json for plugin `{name}`")
            })?;
            source
        } else {
            // Relative path or bare "./" → use the marketplace repo
            marketplace_owner_repo.to_string()
        };

        result.push(ResolvedPlugin {
            name,
            owner_repo,
            description,
        });
    }

    Ok(result)
}

/// Minimal synchronous HTTP GET using `curl` (avoids adding a heavy HTTP dep).
fn fetch_url(url: &str) -> Result<String> {
    // Whitelist: only allow GitHub raw content URLs.
    // This prevents a compromised registry file from pointing curl at arbitrary hosts.
    if !url.starts_with("https://raw.githubusercontent.com/") {
        anyhow::bail!(
            "URL not allowed (must start with https://raw.githubusercontent.com/): {url}"
        );
    }

    let output = std::process::Command::new("curl")
        .args([
            "--silent",
            "--fail",
            "--location",
            "--max-time",
            "15",
            "--max-filesize",
            "1048576",
            "--proto",
            "=https",
            "--tlsv1.2",
            "--",
            url,
        ])
        .output()
        .context("Failed to run curl")?;

    if !output.status.success() {
        anyhow::bail!(
            "curl failed with status {}: {}",
            output.status,
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }

    String::from_utf8(output.stdout).context("Response is not valid UTF-8")
}

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

    #[test]
    fn test_parse_at_spec_valid() {
        let (name, mkt) = parse_at_spec("superpowers@superpowers-marketplace").unwrap();
        assert_eq!(name, "superpowers");
        assert_eq!(mkt, "superpowers-marketplace");
    }

    #[test]
    fn test_parse_at_spec_no_at() {
        assert!(parse_at_spec("owner/repo").is_err());
    }

    #[test]
    fn test_parse_at_spec_empty_name() {
        assert!(parse_at_spec("@marketplace").is_err());
    }

    #[test]
    fn test_parse_at_spec_empty_marketplace() {
        assert!(parse_at_spec("plugin@").is_err());
    }

    #[test]
    fn test_is_at_spec() {
        assert!(is_at_spec("plugin@marketplace"));
        assert!(!is_at_spec("owner/repo"));
        assert!(!is_at_spec("@marketplace")); // starts_with @
    }

    #[test]
    fn test_is_owner_repo() {
        assert!(is_owner_repo("owner/repo"));
        assert!(!is_owner_repo("owner/repo@mkt"));
        assert!(!is_owner_repo("noslash"));
        assert!(!is_owner_repo("/repo"));
        assert!(!is_owner_repo("owner/"));
    }

    #[test]
    fn test_registry_add_remove() {
        let dir = tempfile::tempdir().unwrap();
        // Override registry path via a temp file
        let path = dir.path().join("marketplaces.json");
        std::fs::write(&path, "{}").unwrap();

        // Manually construct registry and test logic
        let mut registry = MarketplaceRegistry {
            entries: BTreeMap::new(),
        };
        assert!(registry.is_empty());

        registry
            .entries
            .insert("test-mkt".to_string(), "owner/repo".to_string());
        assert_eq!(registry.get("test-mkt"), Some("owner/repo"));
        assert_eq!(registry.len(), 1);

        let existed = registry.entries.remove("test-mkt").is_some();
        assert!(existed);
        assert!(registry.is_empty());
    }

    #[test]
    fn test_validate_marketplace_name_valid() {
        assert!(validate_marketplace_name("superpowers-marketplace").is_ok());
        assert!(validate_marketplace_name("my.marketplace_1").is_ok());
    }

    #[test]
    fn test_validate_marketplace_name_invalid() {
        assert!(validate_marketplace_name("").is_err());
        assert!(validate_marketplace_name("has/slash").is_err());
        assert!(validate_marketplace_name("has space").is_err());
    }

    #[test]
    fn test_parse_index_owner_repo_source() {
        let body = serde_json::json!({
            "plugins": [
                { "name": "superpowers", "source": "obra/superpowers", "description": "Cool" }
            ]
        })
        .to_string();
        let plugins = parse_index("obra/superpowers-marketplace", &body).unwrap();
        assert_eq!(plugins.len(), 1);
        assert_eq!(plugins[0].name, "superpowers");
        assert_eq!(plugins[0].owner_repo, "obra/superpowers");
    }

    #[test]
    fn test_parse_index_relative_source() {
        let body = serde_json::json!({
            "plugins": [
                { "name": "epic", "source": "./", "description": "Self-hosted" }
            ]
        })
        .to_string();
        let plugins = parse_index("epicsagas/epic-harness", &body).unwrap();
        assert_eq!(plugins[0].owner_repo, "epicsagas/epic-harness");
    }

    #[test]
    fn test_parse_index_missing_plugins() {
        let body = serde_json::json!({ "name": "bad" }).to_string();
        assert!(parse_index("owner/repo", &body).is_err());
    }

    #[test]
    fn test_parse_index_rejects_malicious_source() {
        // A crafted source with characters outside the GitHub allowlist must be rejected.
        // Space-containing owner passes the slash/@ check in is_owner_repo but fails the allowlist.
        let body = serde_json::json!({
            "plugins": [
                { "name": "evil", "source": "evil owner/repo", "description": "" }
            ]
        })
        .to_string();
        assert!(
            parse_index("legitimate/marketplace", &body).is_err(),
            "source with spaces should be rejected by validate_owner_repo"
        );

        // A source with query-string injection should also be rejected
        let body2 = serde_json::json!({
            "plugins": [
                { "name": "evil2", "source": "owner/repo?query=1", "description": "" }
            ]
        })
        .to_string();
        assert!(
            parse_index("legitimate/marketplace", &body2).is_err(),
            "source with '?' should be rejected by validate_owner_repo"
        );
    }

    #[test]
    fn test_validate_owner_repo_strict() {
        // Valid
        assert!(validate_owner_repo("owner/repo").is_ok());
        assert!(validate_owner_repo("my-org/my_repo.js").is_ok());
        // Invalid: special chars
        assert!(validate_owner_repo("evil @host/repo").is_err());
        assert!(validate_owner_repo("owner/repo?query").is_err());
        assert!(validate_owner_repo("owner/repo#fragment").is_err());
    }

    #[test]
    fn test_fetch_url_rejects_non_github_raw_urls() {
        assert!(fetch_url("http://raw.githubusercontent.com/owner/repo/main/file").is_err());
        assert!(fetch_url("https://evil.com/owner/repo/main/file").is_err());
        assert!(fetch_url("ftp://raw.githubusercontent.com/owner/repo/main/file").is_err());
        assert!(fetch_url("").is_err());
        // Error message must mention the policy, not a curl error
        let err = fetch_url("https://example.com/file").unwrap_err();
        assert!(err.to_string().contains("URL not allowed"), "got: {err}");
    }

    #[test]
    fn test_fetch_url_accepts_valid_github_raw_prefix() {
        // A valid-prefix URL should pass whitelist and fail only at the network level
        // (curl returns non-zero on a nonexistent path, not a whitelist error).
        let err = fetch_url(
            "https://raw.githubusercontent.com/nonexistent-org/nonexistent-repo/main/file.json",
        )
        .unwrap_err();
        assert!(
            !err.to_string().contains("URL not allowed"),
            "should not be blocked by whitelist: {err}"
        );
    }

    #[test]
    fn test_add_rollback_on_save_failure() {
        // Build a registry whose save() will fail (path points to a dir, not a file).
        let dir = tempfile::tempdir().unwrap();
        // Create a subdirectory where the registry file would be, so write fails.
        let conflict = dir.path().join(".collet");
        std::fs::create_dir_all(conflict.join("marketplaces.json")).unwrap();

        let mut registry = MarketplaceRegistry {
            entries: BTreeMap::new(),
        };
        // save() will fail; entries must remain empty after rollback.
        let result = registry.add("test-mkt", "owner/repo");
        // Either save succeeded (unlikely in test) or it failed and rolled back.
        if result.is_err() {
            assert!(registry.is_empty(), "add() must roll back on save failure");
        }
    }
}