troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
//! Self-contained, embedded host marketplaces.

use std::{fs, io, path::Path};

use serde::Serialize;

use crate::{error::CliError, output, platform};

const CLAUDE: &[(&str, &str)] = &[
    (
        ".claude-plugin/marketplace.json",
        include_str!("../../embedded/.claude-plugin/marketplace.json"),
    ),
    (
        "integrations/claude-code/.claude-plugin/plugin.json",
        include_str!("../../embedded/integrations/claude-code/.claude-plugin/plugin.json"),
    ),
    (
        "integrations/claude-code/.mcp.json",
        include_str!("../../embedded/integrations/claude-code/.mcp.json"),
    ),
    (
        "integrations/claude-code/skills/troll/SKILL.md",
        include_str!("../../embedded/integrations/claude-code/skills/troll/SKILL.md"),
    ),
    (
        "integrations/claude-code/README.md",
        include_str!("../../embedded/integrations/claude-code/README.md"),
    ),
];
const CODEX: &[(&str, &str)] = &[
    (
        ".agents/plugins/marketplace.json",
        include_str!("../../embedded/.agents/plugins/marketplace.json"),
    ),
    (
        "integrations/codex/.codex-plugin/plugin.json",
        include_str!("../../embedded/integrations/codex/.codex-plugin/plugin.json"),
    ),
    (
        "integrations/codex/.mcp.json",
        include_str!("../../embedded/integrations/codex/.mcp.json"),
    ),
    (
        "integrations/codex/skills/troll/SKILL.md",
        include_str!("../../embedded/integrations/codex/skills/troll/SKILL.md"),
    ),
    (
        "integrations/codex/README.md",
        include_str!("../../embedded/integrations/codex/README.md"),
    ),
];

#[derive(Serialize)]
struct FileResult {
    path: String,
    status: &'static str,
}
#[derive(Serialize)]
struct ResultOutput {
    schema: u32,
    directory: String,
    files: Vec<FileResult>,
    next_commands: Vec<String>,
}

pub(crate) fn run(host: &'static str, force: bool, json: bool) -> Result<(), CliError> {
    let files = if host == "claude" { CLAUDE } else { CODEX };
    let dir = platform::data_home()?.join("plugins").join(host);
    let quoted = shell_quote(&dir)?;
    let _lock = platform::lock_setup_dir(&dir)
        .map_err(|e| CliError::SetupIo("lock the marketplace", dir.clone(), e))?;
    // Check the entire package before writing, so a conflict cannot cause a partial update.
    let mut changes = Vec::new();
    for &(relative, contents) in files {
        let path = dir.join(relative);
        let unchanged = match fs::read(&path) {
            Ok(existing) => existing == contents.as_bytes(),
            Err(e) if e.kind() == io::ErrorKind::NotFound => false,
            Err(e) => return Err(CliError::SetupIo("read the plugin file", path, e)),
        };
        let exists = match fs::symlink_metadata(&path) {
            Ok(_) => true,
            Err(e) if e.kind() == io::ErrorKind::NotFound => false,
            Err(e) => return Err(CliError::SetupIo("inspect the plugin file", path, e)),
        };
        if exists && !unchanged && !force {
            return Err(CliError::PluginExists(path, host));
        }
        changes.push((path, contents, unchanged, exists));
    }
    let mut results = Vec::new();
    for (path, contents, unchanged, exists) in changes {
        if !unchanged {
            let parent = path.parent().expect("plugin file has a parent");
            fs::create_dir_all(parent).map_err(|e| {
                CliError::SetupIo("create the plugin directory", parent.to_owned(), e)
            })?;
            let name = path
                .file_name()
                .expect("plugin file has a name")
                .to_str()
                .expect("embedded names are UTF-8");
            platform::write_setup_file(parent, name, contents.as_bytes(), exists).map_err(|e| {
                if e.kind() == io::ErrorKind::AlreadyExists && !exists {
                    CliError::PluginExists(path.clone(), host)
                } else {
                    CliError::SetupIo("write the plugin file", path.clone(), e)
                }
            })?;
        }
        results.push(FileResult {
            path: path.to_string_lossy().into_owned(),
            status: if unchanged { "unchanged" } else { "written" },
        });
    }
    let install = if host == "claude" {
        "claude plugin install troll@troll-local --scope user"
    } else {
        "codex plugin add troll@troll-local"
    };
    let result = ResultOutput {
        schema: output::SCHEMA,
        directory: dir.to_string_lossy().into_owned(),
        files: results,
        next_commands: vec![
            format!("{host} plugin marketplace add {quoted}"),
            install.into(),
        ],
    };
    output::write(json, &result, |out| {
        writeln!(out, "Marketplace: {}", result.directory)?;
        for file in &result.files {
            writeln!(out, "{}: {}", file.status, file.path)?;
        }
        writeln!(out, "Next commands:")?;
        for command in &result.next_commands {
            writeln!(out, "  {command}")?;
        }
        Ok(())
    })
}

fn shell_quote(path: &Path) -> Result<String, CliError> {
    let value = path.to_str().ok_or_else(|| {
        CliError::SetupIo(
            "render the marketplace path",
            path.to_owned(),
            io::Error::new(io::ErrorKind::InvalidInput, "path is not UTF-8"),
        )
    })?;
    Ok(format!("'{}'", value.replace('\'', "'\\''")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use std::path::PathBuf;

    #[test]
    fn marketplace_command_quotes_shell_metacharacters() {
        assert_eq!(
            shell_quote(Path::new("/tmp/a b'c$(x)")).unwrap(),
            "'/tmp/a b'\\''c$(x)'"
        );
    }

    #[test]
    fn embedded_packages_match_disk_and_validate() {
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
        for (host, files) in [("claude-code", CLAUDE), ("codex", CODEX)] {
            for &(path, embedded) in files {
                assert_eq!(
                    fs::read_to_string(root.join(path)).unwrap(),
                    embedded,
                    "{path}"
                );
            }
            let base = root.join("integrations").join(host);
            let manifest_path = if host == "codex" {
                ".codex-plugin/plugin.json"
            } else {
                ".claude-plugin/plugin.json"
            };
            let manifest: Value =
                serde_json::from_str(&fs::read_to_string(base.join(manifest_path)).unwrap())
                    .unwrap();
            assert_eq!(manifest["name"], "troll");
            assert_eq!(manifest["version"], env!("CARGO_PKG_VERSION"));
            assert_eq!(manifest["author"]["name"], "Michel Abboud");
            assert_eq!(
                manifest["repository"],
                "https://github.com/michelabboud/troll"
            );
            if host == "codex" {
                for key in ["skills", "mcpServers"] {
                    assert!(base.join(manifest[key].as_str().unwrap()).exists());
                }
                for key in [
                    "displayName",
                    "shortDescription",
                    "longDescription",
                    "developerName",
                    "category",
                ] {
                    assert!(
                        manifest["interface"][key]
                            .as_str()
                            .is_some_and(|s| !s.is_empty())
                    );
                }
                assert_eq!(manifest["interface"]["category"], "Developer Tools");
            }
            let mcp: Value =
                serde_json::from_str(&fs::read_to_string(base.join(".mcp.json")).unwrap()).unwrap();
            assert_eq!(mcp["mcpServers"]["troll"]["command"], "troll");
            assert_eq!(
                mcp["mcpServers"]["troll"]["args"],
                serde_json::json!(["mcp"])
            );
            let skill = fs::read_to_string(base.join("skills/troll/SKILL.md"))
                .unwrap()
                .replace("\r\n", "\n");
            let front = skill
                .strip_prefix("---\n")
                .unwrap()
                .split_once("\n---\n")
                .unwrap()
                .0;
            assert!(front.lines().any(|line| line == "name: troll"));
            assert!(
                front
                    .lines()
                    .any(|line| line.starts_with("description: ") && line.len() > 13)
            );
            for word in [
                "port 0",
                "troll_check",
                "troll_list",
                "troll_lease",
                "troll_renew",
                "troll_release",
                "troll_claim",
            ] {
                assert!(skill.contains(word), "missing {word}");
            }
            let marketplace = if host == "codex" {
                ".agents/plugins/marketplace.json"
            } else {
                ".claude-plugin/marketplace.json"
            };
            let catalog: Value =
                serde_json::from_str(&fs::read_to_string(root.join(marketplace)).unwrap()).unwrap();
            assert_eq!(catalog["name"], "troll-local");
            assert_eq!(catalog["plugins"].as_array().unwrap().len(), 1);
            assert_eq!(catalog["plugins"][0]["name"], "troll");
            let source = if host == "codex" {
                catalog["plugins"][0]["source"]["path"].as_str().unwrap()
            } else {
                assert_eq!(catalog["plugins"][0]["version"], env!("CARGO_PKG_VERSION"));
                catalog["plugins"][0]["source"].as_str().unwrap()
            };
            assert_eq!(
                root.join(source),
                root.join(format!("./integrations/{host}"))
            );
            assert!(root.join(source).is_dir());
        }
        assert_eq!(
            fs::read_to_string(root.join("integrations/claude-code/skills/troll/SKILL.md"))
                .unwrap(),
            fs::read_to_string(root.join("integrations/codex/skills/troll/SKILL.md")).unwrap()
        );
    }
}