Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

53.0 KB
Raw Blame
use std::fmt;
use std::io::{self, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};

use super::projection::{self, ParseError};
use crate::api::schema::{
    InstalledPluginInfo, Method, PluginLinkParams, PluginListParams, PluginPlatform,
    PluginSourceInfo, PluginSourceKind, PluginUnlinkParams, Request, ResponseResult,
    SuccessResponse,
};

pub(crate) mod bindings;

pub(crate) fn command() -> clap::Command {
    bindings::command()
}

const PLUGIN_BUILD_OUTPUT_MAX_BYTES: usize = 64 * 1024;
const PLUGIN_INSTALL_USAGE: &str =
    "usage: herdr plugin install [--ref REF] [--yes|-y] <owner>/<repo>[/subdir...]";

pub(super) fn run_plugin_command(args: &[String]) -> std::io::Result<i32> {
    match args.first().map(String::as_str) {
        Some("install") => return plugin_install(&args[1..]),
        Some("update") => return plugin_update(&args[1..]),
        Some("uninstall") => return plugin_uninstall(&args[1..]),
        Some("config-dir") => return plugin_config_dir_command(&args[1..]),
        _ => {}
    }
    let (method, json) = match projection::parse(
        command().bin_name("herdr plugin"),
        args,
        bindings::from_matches,
    ) {
        Ok(parsed) => parsed,
        Err(ParseError::Io(error)) => return Err(error),
        Err(ParseError::Usage(message)) => {
            eprintln!("{message}");
            return Ok(2);
        }
        Err(ParseError::Clap(error)) => return super::print_clap_error(&error),
    };
    match method {
        Method::PluginLink(params) => plugin_link(params),
        Method::PluginList(params) => plugin_list(params, json),
        method => print_plugin_response(method),
    }
}

fn plugin_link(params: PluginLinkParams) -> std::io::Result<i32> {
    let response = match super::send_request(&Request {
        id: "cli:plugin".into(),
        method: Method::PluginLink(params.clone()),
    }) {
        Ok(response) => response,
        Err(err) if is_connection_error(&err) => offline_plugin_link_response(&params)?,
        Err(err) => return Err(err),
    };
    super::print_response(&response)
}

fn plugin_config_dir_command(args: &[String]) -> std::io::Result<i32> {
    let Some(plugin_id) = args.first() else {
        eprintln!("usage: herdr plugin config-dir <plugin_id>");
        return Ok(2);
    };
    if args.len() != 1 {
        eprintln!("usage: herdr plugin config-dir <plugin_id>");
        return Ok(2);
    }
    let path = crate::plugin_paths::plugin_config_dir(plugin_id);
    crate::plugin_paths::ensure_plugin_user_dirs(plugin_id)?;
    println!("{}", path.display());
    Ok(0)
}

fn plugin_list(params: PluginListParams, json: bool) -> std::io::Result<i32> {
    let response = match super::send_request(&Request {
        id: "cli:plugin".into(),
        method: Method::PluginList(params.clone()),
    }) {
        Ok(response) => response,
        Err(err) if is_connection_error(&err) => offline_plugin_list_response(&params)?,
        Err(err) => return Err(err),
    };
    if json {
        return super::print_response(&response);
    }
    print_plugin_list_human(&response)
}

#[derive(Debug)]
struct PluginInstallArgs {
    source: GithubPluginSource,
    requested_ref: Option<String>,
    yes: bool,
}

fn parse_plugin_install_args(args: &[String]) -> Result<PluginInstallArgs, String> {
    let mut source_arg = None;
    let mut requested_ref = None;
    let mut yes = false;
    let mut index = 0;
    while index < args.len() {
        match args[index].as_str() {
            "--ref" => {
                let value = args.get(index + 1).ok_or("missing value for --ref")?;
                requested_ref = Some(value.clone());
                index += 2;
            }
            "--yes" | "-y" => {
                yes = true;
                index += 1;
            }
            other if other.starts_with('-') || source_arg.is_some() => {
                return Err(format!("unknown option: {other}"));
            }
            other => {
                source_arg = Some(other);
                index += 1;
            }
        }
    }
    let source = GithubPluginSource::parse(source_arg.ok_or(PLUGIN_INSTALL_USAGE)?)?;
    Ok(PluginInstallArgs {
        source,
        requested_ref,
        yes,
    })
}

fn plugin_install(args: &[String]) -> std::io::Result<i32> {
    let PluginInstallArgs {
        source,
        requested_ref,
        yes,
    } = match parse_plugin_install_args(args) {
        Ok(args) => args,
        Err(err) => {
            eprintln!("{err}");
            return Ok(2);
        }
    };

    if !yes && !io::stdin().is_terminal() {
        eprintln!("remote plugin install requires --yes when stdin is not interactive");
        return Ok(2);
    }

    match install_github_plugin(source, requested_ref, yes, true, None) {
        Ok(code) => Ok(code),
        Err(err) => {
            eprintln!("{err}");
            Ok(1)
        }
    }
}

fn plugin_update(args: &[String]) -> std::io::Result<i32> {
    let mut targets = Vec::new();
    let mut yes = false;
    for arg in args {
        match arg.as_str() {
            "--yes" | "-y" => yes = true,
            other if other.starts_with('-') => {
                eprintln!("unknown option: {other}");
                return Ok(2);
            }
            _ => targets.push(arg.as_str()),
        }
    }

    let installed = match live_installed_plugins() {
        Ok(plugins) => plugins,
        Err(err) if is_connection_error(&err) => crate::persist::plugin_registry::try_load()?,
        Err(err) => return Err(err),
    };
    let plugins = if targets.is_empty() {
        installed
            .into_iter()
            .filter(|plugin| plugin.source.kind == PluginSourceKind::Github)
            .collect::<Vec<_>>()
    } else {
        let mut plugins: Vec<InstalledPluginInfo> = Vec::new();
        for target in targets {
            let plugin = if target.contains('/') {
                let source = match GithubPluginSource::parse(target) {
                    Ok(source) => source,
                    Err(err) => {
                        eprintln!("{err}");
                        return Ok(2);
                    }
                };
                installed
                    .iter()
                    .find(|plugin| plugin_matches_github_source(plugin, &source))
            } else {
                installed.iter().find(|plugin| plugin.plugin_id == target)
            };
            let Some(plugin) = plugin else {
                eprintln!("plugin not installed: {target}");
                return Ok(1);
            };
            if plugin.source.kind != PluginSourceKind::Github {
                eprintln!("plugin is locally linked and cannot be updated: {target}");
                return Ok(1);
            }
            if !plugins
                .iter()
                .any(|selected| selected.plugin_id == plugin.plugin_id)
            {
                plugins.push(plugin.clone());
            }
        }
        plugins
    };

    if plugins.is_empty() {
        println!("No GitHub-managed plugins installed.");
        return Ok(0);
    }
    if !yes && !io::stdin().is_terminal() {
        eprintln!("plugin update requires --yes when stdin is not interactive");
        return Ok(2);
    }

    let mut exit_code = 0;
    for plugin in plugins {
        let plugin_id = plugin.plugin_id.clone();
        let source = match GithubPluginSource::from_installed(&plugin) {
            Ok(source) => source,
            Err(err) => {
                eprintln!("error updating {plugin_id}: {err}");
                exit_code = 1;
                continue;
            }
        };
        match install_github_plugin(
            source,
            plugin.source.requested_ref.clone(),
            yes,
            plugin.enabled,
            Some(&plugin),
        ) {
            Ok(code) => exit_code = exit_code.max(code),
            Err(err) => {
                eprintln!("error updating {plugin_id}: {err}");
                exit_code = 1;
            }
        }
    }
    Ok(exit_code)
}

fn install_github_plugin(
    source: GithubPluginSource,
    requested_ref: Option<String>,
    yes: bool,
    enabled: bool,
    updating_plugin: Option<&InstalledPluginInfo>,
) -> std::io::Result<i32> {
    let updating = updating_plugin.is_some();
    let temp_root = create_plugin_temp_dir(if updating { "update" } else { "install" })?;
    let checkout = temp_root.join("checkout");
    let install_result = (|| {
        git_checkout(&source, requested_ref.as_deref(), &checkout)?;
        let resolved_commit = git_output(&checkout, ["rev-parse", "HEAD"])?;
        let manifest_root = source.manifest_root(&checkout);
        let preview_plugin = load_cli_plugin_manifest(&manifest_root, enabled)?;
        if let Some(plugin) = updating_plugin {
            if preview_plugin.plugin_id != plugin.plugin_id {
                return Err(io::Error::other(format!(
                    "update source now contains plugin {}, expected {}",
                    preview_plugin.plugin_id, plugin.plugin_id
                )));
            }
        }
        let _checkout_lock = lock_managed_checkout(&preview_plugin.plugin_id)?;
        let existing = installed_plugin_info(&preview_plugin.plugin_id)?;
        if let Some(expected) = updating_plugin {
            ensure_update_target_unchanged(expected, existing.as_ref())?;
        }
        ensure_replacement_allowed(&preview_plugin, existing.as_ref())?;
        if updating
            && existing
                .as_ref()
                .and_then(|plugin| plugin.source.resolved_commit.as_deref())
                == Some(resolved_commit.as_str())
        {
            println!("{} is already up to date.", preview_plugin.plugin_id);
            return Ok(true);
        }

        let mut source_info =
            source.to_source_info(requested_ref, resolved_commit, None, current_unix_ms());
        print_install_preview(&preview_plugin, &source_info, existing.as_ref(), updating);
        let prompt = if updating {
            "Update this plugin?"
        } else {
            "Install this plugin?"
        };
        if !yes && !confirm(prompt)? {
            eprintln!(
                "plugin {} cancelled",
                if updating { "update" } else { "install" }
            );
            return Ok(false);
        }
        let installation =
            crate::plugin_paths::create_managed_installation(&preview_plugin.plugin_id)?;
        let installation_lease = crate::plugin_installations::create_lease(&installation)?;
        let final_checkout = installation.join("checkout");
        let mut activation_attempted = false;
        let install_attempt = (|| {
            std::fs::rename(&checkout, &final_checkout)?;
            let final_manifest_root = source.manifest_root(&final_checkout);
            let mut preview_plugin = preview_plugin.clone();
            let relocated_plugin = load_cli_plugin_manifest(&final_manifest_root, enabled)?;
            preview_plugin.manifest_path = relocated_plugin.manifest_path;
            preview_plugin.plugin_root = relocated_plugin.plugin_root;
            run_plugin_build_commands(&preview_plugin, &final_manifest_root).map_err(|err| {
                io::Error::other(format!(
                    "{err}\n\nPlugin was not {}.",
                    if updating { "updated" } else { "installed" }
                ))
            })?;
            let mut plugin = load_cli_plugin_manifest(&final_manifest_root, enabled)?;
            ensure_manifest_unchanged_after_build(&preview_plugin, &plugin)?;
            source_info.managed_path = Some(final_checkout.display().to_string());
            plugin.source = source_info;
            activation_attempted = true;
            if let Some(expected) = updating_plugin {
                persist_updated_plugin(&plugin, expected)?;
            } else {
                persist_plugin_offline(&plugin, true)?;
            }
            Ok::<InstalledPluginInfo, io::Error>(plugin)
        })();
        let plugin = match install_attempt {
            Ok(plugin) => plugin,
            Err(err) => {
                drop(installation_lease);
                // A failed activation may have published the path. Never delete files
                // that a server or a plugin process could already be using.
                if activation_attempted {
                    return Err(io::Error::other(format!(
                        "{err}; plugin files retained at {}",
                        final_checkout.display()
                    )));
                }
                if let Err(cleanup_err) =
                    crate::persist::plugin_registry::with_registry_lock(|| {
                        std::fs::remove_dir_all(&installation)
                    })
                {
                    return Err(io::Error::other(format!(
                        "{err}; could not remove failed installation at {}: {cleanup_err}",
                        installation.display()
                    )));
                }
                return Err(err);
            }
        };
        println!(
            "{} {} from {}.",
            if updating { "Updated" } else { "Installed" },
            plugin.plugin_id,
            source.display()
        );
        println!(
            "Config: {}",
            crate::plugin_paths::plugin_config_dir(&plugin.plugin_id).display()
        );
        Ok(true)
    })();
    let _ = std::fs::remove_dir_all(&temp_root);
    install_result.map(|cleanup| {
        if cleanup {
            if let Err(err) = crate::plugin_installations::cleanup() {
                eprintln!("Plugin cleanup deferred: {err}");
            }
        }
        0
    })
}

fn plugin_uninstall(args: &[String]) -> std::io::Result<i32> {
    let Some(target) = args.first() else {
        eprintln!("usage: herdr plugin uninstall <plugin_id|owner/repo[/subdir...]>");
        return Ok(2);
    };
    if args.len() != 1 {
        eprintln!("usage: herdr plugin uninstall <plugin_id|owner/repo[/subdir...]>");
        return Ok(2);
    }

    let (plugin_id, existing) = match GithubPluginSource::parse(target) {
        Ok(source) => {
            let existing = installed_plugin_by_github_source(&source)?;
            let Some(existing) = existing else {
                eprintln!("plugin not installed: {}", source.display());
                return Ok(1);
            };
            (existing.plugin_id.clone(), Some(existing))
        }
        Err(_) => {
            let existing = match live_installed_plugin_info(target) {
                Ok(plugin) => plugin,
                Err(err) if is_connection_error(&err) => registry_plugin_info(target),
                Err(err) => return Err(err),
            };
            (target.clone(), existing)
        }
    };
    let _checkout_lock = existing
        .as_ref()
        .filter(|plugin| plugin.source.kind == PluginSourceKind::Github)
        .map(|_| lock_managed_checkout(&plugin_id))
        .transpose()?;

    match super::send_request(&Request {
        id: "cli:plugin".into(),
        method: Method::PluginUnlink(PluginUnlinkParams {
            plugin_id: plugin_id.clone(),
        }),
    }) {
        Ok(response) => {
            if response.get("error").is_some() {
                return super::print_response(&response);
            }
            if response["result"]["removed"].as_bool() == Some(false) {
                eprintln!("plugin not installed: {target}");
                return Ok(1);
            }
        }
        Err(err) if is_connection_error(&err) => {
            let (removed, _) = crate::persist::plugin_registry::update(|plugins| {
                let before = plugins.len();
                plugins.retain(|plugin| plugin.plugin_id != plugin_id);
                before != plugins.len()
            })?;
            if !removed {
                eprintln!("plugin not installed: {target}");
                return Ok(1);
            }
        }
        Err(err) => return Err(err),
    }

    println!("Uninstalled {plugin_id}.");
    Ok(0)
}

fn normalize_plugin_path_arg(value: &str) -> std::io::Result<String> {
    if super::target::is_remote() {
        if super::target::remote_path_is_absolute(value) {
            return Ok(value.to_owned());
        }
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "remote plugin paths must be absolute",
        ));
    }
    let path = crate::worktree::expand_tilde_path(value);
    let absolute = if path.is_absolute() {
        path
    } else {
        std::env::current_dir()?.join(path)
    };
    Ok(absolute.display().to_string())
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct GithubPluginSource {
    owner: String,
    repo: String,
    subdir: Option<String>,
}

impl GithubPluginSource {
    fn parse(value: &str) -> Result<Self, String> {
        if value.starts_with("http://")
            || value.starts_with("https://")
            || value.starts_with("git@")
            || value.contains(':')
        {
            return Err("plugin install v1 accepts only owner/repo[/subdir] shorthand".into());
        }
        let parts = value.split('/').collect::<Vec<_>>();
        if parts.len() < 2 {
            return Err(PLUGIN_INSTALL_USAGE.into());
        }
        let owner = parts[0];
        let repo = parts[1];
        validate_github_segment("owner", owner)?;
        validate_github_segment("repo", repo)?;
        let subdir_parts = &parts[2..];
        for part in subdir_parts {
            validate_subdir_segment(part)?;
        }
        let subdir = if subdir_parts.is_empty() {
            None
        } else {
            Some(subdir_parts.join("/"))
        };
        Ok(Self {
            owner: owner.to_string(),
            repo: repo.to_string(),
            subdir,
        })
    }

    fn remote_url(&self) -> String {
        format!("https://github.com/{}/{}.git", self.owner, self.repo)
    }

    fn from_installed(plugin: &InstalledPluginInfo) -> std::io::Result<Self> {
        let owner = plugin
            .source
            .owner
            .clone()
            .ok_or_else(|| io::Error::other("installed GitHub plugin has no source owner"))?;
        let repo =
            plugin.source.repo.clone().ok_or_else(|| {
                io::Error::other("installed GitHub plugin has no source repository")
            })?;
        Ok(Self {
            owner,
            repo,
            subdir: plugin.source.subdir.clone(),
        })
    }

    fn display(&self) -> String {
        match &self.subdir {
            Some(subdir) => format!("{}/{}/{}", self.owner, self.repo, subdir),
            None => format!("{}/{}", self.owner, self.repo),
        }
    }

    fn manifest_root(&self, checkout: &Path) -> PathBuf {
        match &self.subdir {
            Some(subdir) => checkout.join(subdir),
            None => checkout.to_path_buf(),
        }
    }

    fn to_source_info(
        &self,
        requested_ref: Option<String>,
        resolved_commit: String,
        managed_path: Option<String>,
        installed_unix_ms: u64,
    ) -> PluginSourceInfo {
        PluginSourceInfo {
            kind: PluginSourceKind::Github,
            owner: Some(self.owner.clone()),
            repo: Some(self.repo.clone()),
            subdir: self.subdir.clone(),
            requested_ref,
            resolved_commit: Some(resolved_commit),
            managed_path,
            installed_unix_ms: Some(installed_unix_ms),
        }
    }
}

fn ensure_replacement_allowed(
    plugin: &InstalledPluginInfo,
    existing: Option<&InstalledPluginInfo>,
) -> std::io::Result<()> {
    let Some(existing) = existing else {
        return Ok(());
    };
    if existing.source.kind != PluginSourceKind::Github {
        return Err(std::io::Error::other(format!(
            "plugin {} is already linked from a local path; uninstall/unlink it before installing from GitHub",
            plugin.plugin_id
        )));
    }
    Ok(())
}

fn ensure_update_target_unchanged(
    expected: &InstalledPluginInfo,
    current: Option<&InstalledPluginInfo>,
) -> std::io::Result<()> {
    if current.is_some_and(|current| same_update_target(expected, current)) {
        return Ok(());
    }
    Err(io::Error::other(format!(
        "plugin {} changed while its update was in progress; retry the update",
        expected.plugin_id
    )))
}

fn same_update_target(expected: &InstalledPluginInfo, current: &InstalledPluginInfo) -> bool {
    current.manifest_path == expected.manifest_path && current.source == expected.source
}

fn validate_github_segment(label: &str, value: &str) -> Result<(), String> {
    if value.is_empty() {
        return Err(format!("GitHub {label} must not be empty"));
    }
    if value == "." || value == ".." {
        return Err(format!("GitHub {label} is invalid: {value}"));
    }
    if !value
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
    {
        return Err(format!(
            "GitHub {label} contains invalid characters: {value}"
        ));
    }
    Ok(())
}

fn validate_subdir_segment(value: &str) -> Result<(), String> {
    if value.is_empty() || value == "." || value == ".." {
        return Err(format!("invalid plugin subdir segment: {value}"));
    }
    if value.contains('\\') || value.contains('\0') {
        return Err(format!("invalid plugin subdir segment: {value}"));
    }
    Ok(())
}

fn git_checkout(
    source: &GithubPluginSource,
    requested_ref: Option<&str>,
    checkout: &Path,
) -> std::io::Result<()> {
    std::fs::create_dir_all(checkout)?;
    run_git(Some(checkout), ["init"])?;
    run_git(
        Some(checkout),
        ["remote", "add", "origin", &source.remote_url()],
    )?;
    match requested_ref {
        Some(reference) => {
            run_git(
                Some(checkout),
                ["fetch", "--depth", "1", "origin", reference],
            )?;
        }
        None => {
            run_git(Some(checkout), ["fetch", "--depth", "1", "origin", "HEAD"])?;
        }
    }
    run_git(Some(checkout), ["checkout", "--detach", "FETCH_HEAD"])?;
    Ok(())
}

fn run_git<const N: usize>(cwd: Option<&Path>, args: [&str; N]) -> std::io::Result<()> {
    let mut command = crate::noninteractive_process::command("git");
    command.args(args);
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    command.stdin(Stdio::null());
    let output = command.output()?;
    if output.status.success() {
        return Ok(());
    }
    Err(std::io::Error::other(command_failure_message(
        "git", &output,
    )))
}

fn git_output<const N: usize>(cwd: &Path, args: [&str; N]) -> std::io::Result<String> {
    let output = crate::noninteractive_process::command("git")
        .args(args)
        .current_dir(cwd)
        .stdin(Stdio::null())
        .output()?;
    if output.status.success() {
        return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string());
    }
    Err(std::io::Error::other(command_failure_message(
        "git", &output,
    )))
}

fn command_failure_message(program: &str, output: &std::process::Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
    if stderr.is_empty() {
        format!("{program} failed with status {}", output.status)
    } else {
        format!("{program} failed with status {}: {stderr}", output.status)
    }
}

fn load_cli_plugin_manifest(path: &Path, enabled: bool) -> std::io::Result<InstalledPluginInfo> {
    crate::app::load_plugin_manifest(&path.display().to_string(), enabled)
        .map_err(|(_, message)| std::io::Error::other(message))
}

fn persist_plugin_offline(
    plugin: &InstalledPluginInfo,
    preserve_enabled: bool,
) -> std::io::Result<()> {
    crate::plugin_paths::ensure_plugin_user_dirs(&plugin.plugin_id)?;
    crate::persist::plugin_registry::update(|plugins| {
        let mut plugin = plugin.clone();
        if preserve_enabled {
            if let Some(existing) = plugins
                .iter()
                .find(|entry| entry.plugin_id == plugin.plugin_id)
            {
                plugin.enabled = existing.enabled;
            }
        }
        plugins.retain(|entry| entry.plugin_id != plugin.plugin_id);
        plugins.push(plugin);
    })?;
    Ok(())
}

fn persist_updated_plugin(
    plugin: &InstalledPluginInfo,
    expected: &InstalledPluginInfo,
) -> std::io::Result<()> {
    let (updated, _) = crate::persist::plugin_registry::update(|plugins| {
        let Some(current) = plugins
            .iter_mut()
            .find(|entry| entry.plugin_id == expected.plugin_id)
        else {
            return false;
        };
        if !same_update_target(expected, current) {
            return false;
        }
        let enabled = current.enabled;
        *current = plugin.clone();
        current.enabled = enabled;
        true
    })?;
    if updated {
        Ok(())
    } else {
        Err(io::Error::other(format!(
            "plugin {} changed while its update was in progress; retry the update",
            expected.plugin_id
        )))
    }
}

fn installed_plugin_info(plugin_id: &str) -> std::io::Result<Option<InstalledPluginInfo>> {
    match live_installed_plugin_info(plugin_id) {
        Ok(plugin) => Ok(plugin),
        Err(err) if is_connection_error(&err) => Ok(registry_plugin_info(plugin_id)),
        Err(err) => Err(err),
    }
}

fn live_installed_plugin_info(plugin_id: &str) -> std::io::Result<Option<InstalledPluginInfo>> {
    let response = super::send_request(&Request {
        id: "cli:plugin".into(),
        method: Method::PluginList(PluginListParams {
            plugin_id: Some(plugin_id.to_string()),
        }),
    })?;
    if response.get("error").is_some() {
        return Err(std::io::Error::other(
            serde_json::to_string(&response).unwrap(),
        ));
    }
    plugin_info_from_list_response(response)
}

fn installed_plugin_by_github_source(
    source: &GithubPluginSource,
) -> std::io::Result<Option<InstalledPluginInfo>> {
    let plugins = match live_installed_plugins() {
        Ok(plugins) => plugins,
        Err(err) if is_connection_error(&err) => registry_plugins(),
        Err(err) => return Err(err),
    };
    Ok(plugin_by_github_source(plugins, source))
}

fn live_installed_plugins() -> std::io::Result<Vec<InstalledPluginInfo>> {
    let response = super::send_request(&Request {
        id: "cli:plugin".into(),
        method: Method::PluginList(PluginListParams { plugin_id: None }),
    })?;
    if response.get("error").is_some() {
        return Err(std::io::Error::other(
            serde_json::to_string(&response).unwrap(),
        ));
    }
    plugin_list_from_response(response)
}

fn registry_plugin_info(plugin_id: &str) -> Option<InstalledPluginInfo> {
    registry_plugins()
        .into_iter()
        .find(|plugin| plugin.plugin_id == plugin_id)
}

fn registry_plugins() -> Vec<InstalledPluginInfo> {
    crate::persist::plugin_registry::load()
}

fn plugin_info_from_list_response(
    response: serde_json::Value,
) -> std::io::Result<Option<InstalledPluginInfo>> {
    let mut plugins = plugin_list_from_response(response)?;
    Ok(plugins.pop())
}

fn plugin_list_from_response(
    response: serde_json::Value,
) -> std::io::Result<Vec<InstalledPluginInfo>> {
    let parsed: SuccessResponse =
        serde_json::from_value(response).map_err(std::io::Error::other)?;
    let ResponseResult::PluginList { mut plugins } = parsed.result else {
        return Err(std::io::Error::other("expected plugin_list response"));
    };
    plugins.sort_by(|a, b| a.plugin_id.cmp(&b.plugin_id));
    Ok(plugins)
}

fn plugin_by_github_source(
    plugins: impl IntoIterator<Item = InstalledPluginInfo>,
    source: &GithubPluginSource,
) -> Option<InstalledPluginInfo> {
    plugins
        .into_iter()
        .find(|plugin| plugin_matches_github_source(plugin, source))
}

fn plugin_matches_github_source(plugin: &InstalledPluginInfo, source: &GithubPluginSource) -> bool {
    plugin.source.kind == PluginSourceKind::Github
        && plugin
            .source
            .owner
            .as_deref()
            .is_some_and(|owner| owner.eq_ignore_ascii_case(&source.owner))
        && plugin
            .source
            .repo
            .as_deref()
            .is_some_and(|repo| repo.eq_ignore_ascii_case(&source.repo))
        && plugin.source.subdir.as_deref() == source.subdir.as_deref()
}

fn offline_plugin_link_response(params: &PluginLinkParams) -> std::io::Result<serde_json::Value> {
    let plugin = load_cli_plugin_manifest(Path::new(&params.path), params.enabled)?;
    persist_plugin_offline(&plugin, false)?;
    serde_json::to_value(SuccessResponse {
        id: "cli:plugin".into(),
        result: ResponseResult::PluginLinked { plugin },
    })
    .map_err(std::io::Error::other)
}

fn offline_plugin_list_response(params: &PluginListParams) -> std::io::Result<serde_json::Value> {
    let entries = crate::persist::plugin_registry::load();
    let mut plugins =
        crate::persist::plugin_registry::reload_manifests(entries, |path, enabled| {
            crate::app::load_plugin_manifest(path, enabled).map_err(|(_, msg)| msg)
        })
        .into_iter()
        .filter(|plugin| {
            params
                .plugin_id
                .as_deref()
                .is_none_or(|plugin_id| plugin.plugin_id == plugin_id)
        })
        .collect::<Vec<_>>();
    plugins.sort_by(|a, b| a.plugin_id.cmp(&b.plugin_id));
    serde_json::to_value(SuccessResponse {
        id: "cli:plugin".into(),
        result: ResponseResult::PluginList { plugins },
    })
    .map_err(std::io::Error::other)
}

fn print_plugin_list_human(response: &serde_json::Value) -> std::io::Result<i32> {
    if response.get("error").is_some() {
        return super::print_response(response);
    }
    let parsed: SuccessResponse =
        serde_json::from_value(response.clone()).map_err(std::io::Error::other)?;
    let ResponseResult::PluginList { plugins } = parsed.result else {
        return super::print_response(response);
    };
    if plugins.is_empty() {
        println!("No plugins installed.");
        return Ok(0);
    }
    println!(
        "{} plugin{} installed:",
        plugins.len(),
        if plugins.len() == 1 { "" } else { "s" }
    );
    for plugin in plugins {
        let enabled = if plugin.enabled {
            "enabled"
        } else {
            "disabled"
        };
        let warning = if plugin.warnings.is_empty() {
            String::new()
        } else {
            format!("; {} warning(s)", plugin.warnings.len())
        };
        println!(
            "- {} ({}) {} [{}{}]",
            plugin.plugin_id,
            plugin.name,
            enabled,
            source_display(&plugin),
            warning
        );
        println!(
            "  config: {}",
            crate::plugin_paths::plugin_config_dir(&plugin.plugin_id).display()
        );
        for warning in plugin.warnings {
            println!("  warning: {warning}");
        }
    }
    Ok(0)
}

fn source_display(plugin: &InstalledPluginInfo) -> String {
    match plugin.source.kind {
        PluginSourceKind::Github => {
            let owner = plugin.source.owner.as_deref().unwrap_or("unknown");
            let repo = plugin.source.repo.as_deref().unwrap_or("unknown");
            let subdir = plugin
                .source
                .subdir
                .as_deref()
                .map(|subdir| format!("/{subdir}"))
                .unwrap_or_default();
            let reference = plugin
                .source
                .requested_ref
                .as_deref()
                .or(plugin.source.resolved_commit.as_deref())
                .unwrap_or("unknown");
            format!("github:{owner}/{repo}{subdir}@{reference}")
        }
        PluginSourceKind::Local => format!("local:{}", plugin.plugin_root),
    }
}

fn print_install_preview(
    plugin: &InstalledPluginInfo,
    source: &PluginSourceInfo,
    existing: Option<&InstalledPluginInfo>,
    updating: bool,
) {
    eprintln!(
        "Plugin {} preview:",
        if updating { "update" } else { "install" }
    );
    eprintln!("  id: {}", plugin.plugin_id);
    eprintln!("  name: {}", plugin.name);
    eprintln!("  version: {}", plugin.version);
    if let (Some(owner), Some(repo)) = (&source.owner, &source.repo) {
        let subdir = source
            .subdir
            .as_deref()
            .map(|subdir| format!("/{subdir}"))
            .unwrap_or_default();
        eprintln!("  source: {owner}/{repo}{subdir}");
    }
    if let Some(reference) = &source.requested_ref {
        eprintln!("  ref: {reference}");
    }
    if let Some(commit) = &source.resolved_commit {
        eprintln!("  commit: {commit}");
    }
    eprintln!("  actions: {}", plugin.actions.len());
    eprintln!("  startup commands: {}", plugin.startup.len());
    eprintln!("  events: {}", plugin.events.len());
    eprintln!("  panes: {}", plugin.panes.len());
    eprintln!("  link handlers: {}", plugin.link_handlers.len());
    eprintln!("  build commands: {}", plugin.build.len());
    for build in &plugin.build {
        let support = if build_platform_supported(&build.platforms, &plugin.platforms) {
            String::new()
        } else {
            format!(
                " (skipped on {})",
                plugin_platform_name(current_plugin_platform())
            )
        };
        eprintln!("    build{}: {}", support, build.command.join(" "));
    }
    for startup in &plugin.startup {
        eprintln!("    startup: {}", startup.command.join(" "));
    }
    for action in &plugin.actions {
        eprintln!("    action {}: {}", action.id, action.command.join(" "));
    }
    for event in &plugin.events {
        eprintln!("    event {}: {}", event.on, event.command.join(" "));
    }
    for pane in &plugin.panes {
        eprintln!("    pane {}: {}", pane.id, pane.command.join(" "));
    }
    for warning in &plugin.warnings {
        eprintln!("  warning: {warning}");
    }
    if let Some(existing) = existing {
        eprintln!(
            "  replaces: {} from {}",
            existing.plugin_id,
            source_display(existing)
        );
    }
}

fn run_plugin_build_commands(
    plugin: &InstalledPluginInfo,
    manifest_root: &Path,
) -> Result<(), Box<PluginBuildFailure>> {
    let total = plugin.build.len();
    for (index, build) in plugin.build.iter().enumerate() {
        if !build_platform_supported(&build.platforms, &plugin.platforms) {
            continue;
        }
        run_plugin_build_command(
            &plugin.plugin_id,
            index + 1,
            total,
            manifest_root,
            &build.command,
        )?;
    }
    Ok(())
}

fn ensure_manifest_unchanged_after_build(
    before: &InstalledPluginInfo,
    after: &InstalledPluginInfo,
) -> io::Result<()> {
    if before == after {
        return Ok(());
    }
    Err(io::Error::other(
        "plugin build changed herdr-plugin.toml after install preview; aborting install",
    ))
}

fn run_plugin_build_command(
    plugin_id: &str,
    build_index: usize,
    build_total: usize,
    cwd: &Path,
    command: &[String],
) -> Result<(), Box<PluginBuildFailure>> {
    let context = plugin_build_context(plugin_id, build_index, build_total, cwd, command);
    let Some(program) = command.first() else {
        return Err(Box::new(PluginBuildFailure {
            context,
            kind: PluginBuildFailureKind::Start {
                error: io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "build command must not be empty",
                ),
            },
        }));
    };
    let args = command.iter().skip(1).cloned().collect::<Vec<_>>();
    let mut child = crate::plugin_command::command_for_argv_in_dir(program, &args, cwd);
    child
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    scrub_herdr_runtime_env(&mut child);

    let mut child = match child.spawn() {
        Ok(child) => child,
        Err(err) => {
            return Err(Box::new(PluginBuildFailure {
                context,
                kind: PluginBuildFailureKind::Start { error: err },
            }));
        }
    };
    let stdout = child.stdout.take();
    let stderr = child.stderr.take();
    let stdout_reader = stdout.map(|stdout| {
        std::thread::spawn(move || read_tail_capped_output(stdout, PLUGIN_BUILD_OUTPUT_MAX_BYTES))
    });
    let stderr_reader = stderr.map(|stderr| {
        std::thread::spawn(move || read_tail_capped_output(stderr, PLUGIN_BUILD_OUTPUT_MAX_BYTES))
    });
    let status = child.wait().map_err(|error| {
        Box::new(PluginBuildFailure {
            context: context.clone(),
            kind: PluginBuildFailureKind::Wait { error },
        })
    })?;
    let stdout = stdout_reader
        .and_then(|reader| reader.join().ok())
        .unwrap_or_default();
    let stderr = stderr_reader
        .and_then(|reader| reader.join().ok())
        .unwrap_or_default();
    if status.success() {
        return Ok(());
    }
    Err(Box::new(PluginBuildFailure {
        context,
        kind: PluginBuildFailureKind::Exit {
            status,
            stdout,
            stderr,
        },
    }))
}

fn plugin_build_context(
    plugin_id: &str,
    build_index: usize,
    build_total: usize,
    cwd: &Path,
    command: &[String],
) -> PluginBuildContext {
    PluginBuildContext {
        plugin_id: plugin_id.to_string(),
        build_index,
        build_total,
        cwd: cwd.display().to_string(),
        command: command.to_vec(),
    }
}

#[derive(Debug, Default)]
struct CappedOutput {
    text: String,
    truncated: bool,
}

#[derive(Debug, Clone)]
struct PluginBuildContext {
    plugin_id: String,
    build_index: usize,
    build_total: usize,
    cwd: String,
    command: Vec<String>,
}

#[derive(Debug)]
struct PluginBuildFailure {
    context: PluginBuildContext,
    kind: PluginBuildFailureKind,
}

#[derive(Debug)]
enum PluginBuildFailureKind {
    Start {
        error: io::Error,
    },
    Wait {
        error: io::Error,
    },
    Exit {
        status: ExitStatus,
        stdout: CappedOutput,
        stderr: CappedOutput,
    },
}

impl fmt::Display for PluginBuildFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "error: plugin build failed")?;
        write_build_context(f, &self.context)?;
        match &self.kind {
            PluginBuildFailureKind::Start { error } => {
                writeln!(f, "  error: failed to start: {error}")?;
            }
            PluginBuildFailureKind::Wait { error } => {
                writeln!(f, "  error: failed to wait for command: {error}")?;
            }
            PluginBuildFailureKind::Exit {
                status,
                stdout,
                stderr,
            } => {
                writeln!(f, "  status: {status}")?;
                write_output_section(f, "stderr", stderr)?;
                write_output_section(f, "stdout", stdout)?;
            }
        }
        Ok(())
    }
}

fn write_build_context(f: &mut fmt::Formatter<'_>, context: &PluginBuildContext) -> fmt::Result {
    writeln!(f, "  plugin: {}", context.plugin_id)?;
    writeln!(
        f,
        "  build: {}/{}",
        context.build_index, context.build_total
    )?;
    writeln!(f, "  cwd: {}", context.cwd)?;
    writeln!(f, "  command: {}", context.command.join(" "))
}

fn write_output_section(
    f: &mut fmt::Formatter<'_>,
    label: &str,
    output: &CappedOutput,
) -> fmt::Result {
    let text = output.text.trim_end();
    if text.is_empty() {
        return Ok(());
    }
    writeln!(f)?;
    if output.truncated {
        writeln!(
            f,
            "{label}: showing last {PLUGIN_BUILD_OUTPUT_MAX_BYTES} bytes; earlier output omitted"
        )?;
    } else {
        writeln!(f, "{label}:")?;
    }
    writeln!(f, "{text}")
}

fn read_tail_capped_output(mut reader: impl Read, cap: usize) -> CappedOutput {
    let mut out = Vec::new();
    let mut buf = [0u8; 8192];
    let mut truncated = false;
    loop {
        match reader.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                out.extend_from_slice(&buf[..n]);
                if out.len() > cap {
                    let excess = out.len() - cap;
                    out.drain(0..excess);
                    truncated = true;
                }
            }
            Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
            Err(_) => break,
        }
    }
    CappedOutput {
        text: String::from_utf8_lossy(&out).to_string(),
        truncated,
    }
}

fn scrub_herdr_runtime_env(command: &mut Command) {
    for key in [
        crate::api::SOCKET_PATH_ENV_VAR,
        crate::server::socket_paths::CLIENT_SOCKET_PATH_ENV_VAR,
        crate::session::SESSION_ENV_VAR,
        "HERDR_BIN_PATH",
        "HERDR_ENV",
        "HERDR_WORKSPACE_ID",
        "HERDR_TAB_ID",
        "HERDR_PANE_ID",
    ] {
        command.env_remove(key);
    }
    for (key, _) in std::env::vars_os() {
        if key.to_string_lossy().starts_with("HERDR_PLUGIN_") {
            command.env_remove(key);
        }
    }
}

fn build_platform_supported(
    platforms: &Option<Vec<PluginPlatform>>,
    plugin_platforms: &Option<Vec<PluginPlatform>>,
) -> bool {
    platforms
        .as_ref()
        .or(plugin_platforms.as_ref())
        .is_none_or(|platforms| platforms.contains(&current_plugin_platform()))
}

fn current_plugin_platform() -> PluginPlatform {
    if cfg!(target_os = "linux") {
        PluginPlatform::Linux
    } else if cfg!(target_os = "macos") {
        PluginPlatform::Macos
    } else {
        PluginPlatform::Windows
    }
}

fn plugin_platform_name(platform: PluginPlatform) -> &'static str {
    match platform {
        PluginPlatform::Linux => "linux",
        PluginPlatform::Macos => "macos",
        PluginPlatform::Windows => "windows",
    }
}

fn confirm(prompt: &str) -> std::io::Result<bool> {
    eprint!("{prompt} [y/N] ");
    io::stderr().flush()?;
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    Ok(matches!(line.trim(), "y" | "Y" | "yes" | "YES" | "Yes"))
}

fn create_plugin_temp_dir(label: &str) -> std::io::Result<PathBuf> {
    let path = crate::plugin_paths::managed_plugins_dir().join(format!(
        ".tmp-{label}-{}-{}",
        std::process::id(),
        current_unix_ms()
    ));
    std::fs::create_dir_all(&path)?;
    Ok(path)
}

fn lock_managed_checkout(plugin_id: &str) -> std::io::Result<std::fs::File> {
    let lock_path = crate::plugin_paths::managed_checkout_lock_path(plugin_id);
    if let Some(parent) = lock_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(lock_path)?;
    lock.lock()?;
    Ok(lock)
}

fn current_unix_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_millis() as u64)
        .unwrap_or(0)
}

fn is_connection_error(err: &std::io::Error) -> bool {
    if super::target::is_remote() {
        return false;
    }
    // A `server_not_running` marker is a connect failure for recovery purposes:
    // treating it as a connection error lets plugin commands fall back to the
    // offline registry. The marker carries (but does not print) a friendly
    // response, so recovering here prints nothing.
    super::server_not_running_was_reported(err)
        || matches!(
            err.kind(),
            std::io::ErrorKind::NotFound
                | std::io::ErrorKind::ConnectionRefused
                | std::io::ErrorKind::ConnectionAborted
                | std::io::ErrorKind::ConnectionReset
                | std::io::ErrorKind::BrokenPipe
        )
}

fn print_plugin_response(method: Method) -> std::io::Result<i32> {
    super::print_response(&super::send_request(&Request {
        id: "cli:plugin".into(),
        method,
    })?)
}

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

    #[test]
    fn machine_plugin_connection_errors_never_use_local_offline_state() {
        crate::cli::target::with_test_client(crate::api::client::ApiClient::local(), || {
            assert!(!is_connection_error(&std::io::Error::from(
                std::io::ErrorKind::ConnectionRefused
            )));
        });
    }

    fn unique_plugin_id(label: &str) -> String {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_nanos())
            .unwrap_or(0);
        format!("test.{label}.{}.{nanos}", std::process::id())
    }

    fn github_plugin(
        id: &str,
        owner: &str,
        repo: &str,
        subdir: Option<&str>,
    ) -> InstalledPluginInfo {
        InstalledPluginInfo {
            plugin_id: id.to_string(),
            name: "Test Plugin".to_string(),
            version: "0.1.0".to_string(),
            min_herdr_version: crate::build_info::BASE_VERSION.to_string(),
            description: None,
            manifest_path: format!("/tmp/{id}/herdr-plugin.toml"),
            plugin_root: format!("/tmp/{id}"),
            enabled: true,
            platforms: None,
            build: vec![],
            startup: vec![],
            actions: vec![],
            events: vec![],
            panes: vec![],
            link_handlers: vec![],
            source: PluginSourceInfo {
                kind: PluginSourceKind::Github,
                owner: Some(owner.to_string()),
                repo: Some(repo.to_string()),
                subdir: subdir.map(str::to_string),
                requested_ref: None,
                resolved_commit: Some("abc123".to_string()),
                managed_path: Some(format!("/tmp/herdr/plugins/{id}")),
                installed_unix_ms: Some(42),
            },
            warnings: vec![],
        }
    }

    #[test]
    fn plugin_install_args_accept_options_around_source() {
        for (args, expected_ref, expected_yes) in [
            (vec!["owner/repo"], None, false),
            (vec!["--yes", "owner/repo"], None, true),
            (vec!["-y", "owner/repo"], None, true),
            (
                vec!["owner/repo", "--ref", "main", "-y"],
                Some("main"),
                true,
            ),
            (
                vec!["--ref", "main", "owner/repo", "--yes"],
                Some("main"),
                true,
            ),
            (
                vec![
                    "--yes",
                    "--ref",
                    "old",
                    "owner/repo",
                    "--ref",
                    "main",
                    "--yes",
                ],
                Some("main"),
                true,
            ),
            // Preserve ref-value consumption: a value named --yes is not consent.
            (vec!["owner/repo", "--ref", "--yes"], Some("--yes"), false),
        ] {
            let args = args.into_iter().map(String::from).collect::<Vec<_>>();
            let parsed = parse_plugin_install_args(&args).unwrap();
            assert_eq!(parsed.source.display(), "owner/repo", "{args:?}");
            assert_eq!(parsed.requested_ref.as_deref(), expected_ref, "{args:?}");
            assert_eq!(parsed.yes, expected_yes, "{args:?}");
        }
    }

    #[test]
    fn plugin_install_args_reject_invalid_syntax() {
        for (args, expected_error) in [
            (vec![], PLUGIN_INSTALL_USAGE),
            (vec!["--yes"], PLUGIN_INSTALL_USAGE),
            (vec!["owner/repo", "--ref"], "missing value for --ref"),
            (vec!["--unknown", "owner/repo"], "unknown option: --unknown"),
            (
                vec!["owner/repo", "extra/repo"],
                "unknown option: extra/repo",
            ),
            (vec!["owner"], PLUGIN_INSTALL_USAGE),
        ] {
            let args = args.into_iter().map(String::from).collect::<Vec<_>>();
            assert_eq!(
                parse_plugin_install_args(&args).unwrap_err(),
                expected_error,
                "{args:?}"
            );
        }
    }

    #[test]
    fn github_plugin_source_parses_root_repo() {
        let source = GithubPluginSource::parse("ogulcancelik/herdr-plugin-examples").unwrap();
        assert_eq!(source.owner, "ogulcancelik");
        assert_eq!(source.repo, "herdr-plugin-examples");
        assert_eq!(source.subdir, None);
        assert_eq!(
            source.remote_url(),
            "https://github.com/ogulcancelik/herdr-plugin-examples.git"
        );
    }

    #[test]
    fn github_plugin_source_parses_subdir() {
        let source =
            GithubPluginSource::parse("ogulcancelik/herdr-plugin-examples/worktree-bootstrap")
                .unwrap();
        assert_eq!(source.owner, "ogulcancelik");
        assert_eq!(source.repo, "herdr-plugin-examples");
        assert_eq!(source.subdir.as_deref(), Some("worktree-bootstrap"));
    }

    #[test]
    fn github_plugin_source_rejects_non_shorthand_sources() {
        for source in [
            "https://github.com/ogulcancelik/herdr-plugin-examples",
            "[email protected]:ogulcancelik/herdr-plugin-examples.git",
            "ogulcancelik",
            "ogulcancelik/herdr-plugin-examples/../bad",
            "ogulcancelik/herdr-plugin-examples//bad",
        ] {
            assert!(
                GithubPluginSource::parse(source).is_err(),
                "{source} should be rejected"
            );
        }
    }

    #[test]
    fn github_source_lookup_matches_installed_plugin_source() {
        let source =
            GithubPluginSource::parse("ogulcancelik/herdr-plugin-examples/agent-telegram-notify")
                .unwrap();
        let plugins = vec![
            github_plugin(
                "examples.github-link-preview",
                "ogulcancelik",
                "herdr-plugin-examples",
                Some("github-link-preview"),
            ),
            github_plugin(
                "examples.agent-telegram-notify",
                "ogulcancelik",
                "herdr-plugin-examples",
                Some("agent-telegram-notify"),
            ),
        ];

        let plugin = plugin_by_github_source(plugins, &source).unwrap();
        assert_eq!(plugin.plugin_id, "examples.agent-telegram-notify");
    }

    #[test]
    fn github_source_lookup_requires_exact_subdir() {
        let source = GithubPluginSource::parse("ogulcancelik/herdr-plugin-examples").unwrap();
        let plugins = vec![github_plugin(
            "examples.agent-telegram-notify",
            "ogulcancelik",
            "herdr-plugin-examples",
            Some("agent-telegram-notify"),
        )];

        assert!(plugin_by_github_source(plugins, &source).is_none());
    }

    #[test]
    fn github_source_lookup_ignores_owner_and_repo_case() {
        let source = GithubPluginSource::parse("OGULCANCELIK/HERDR-PLUGIN-EXAMPLES").unwrap();
        let plugins = vec![github_plugin(
            "examples.root",
            "ogulcancelik",
            "herdr-plugin-examples",
            None,
        )];

        assert_eq!(
            plugin_by_github_source(plugins, &source).unwrap().plugin_id,
            "examples.root"
        );
    }

    #[test]
    fn github_source_lookup_ignores_local_plugins() {
        let source = GithubPluginSource::parse("ogulcancelik/herdr-plugin-examples").unwrap();
        let mut plugin = github_plugin(
            "examples.local",
            "ogulcancelik",
            "herdr-plugin-examples",
            None,
        );
        plugin.source = PluginSourceInfo::default();

        assert!(plugin_by_github_source([plugin], &source).is_none());
    }

    #[test]
    fn update_target_revalidation_allows_state_changes_but_rejects_install_changes() {
        let expected = github_plugin("examples.root", "owner", "repo", None);
        let mut current = expected.clone();
        current.enabled = false;
        assert!(ensure_update_target_unchanged(&expected, Some(&current)).is_ok());

        current.source.resolved_commit = Some("newer".to_string());
        assert!(ensure_update_target_unchanged(&expected, Some(&current)).is_err());
        current = expected.clone();
        current.source = PluginSourceInfo::default();
        assert!(ensure_update_target_unchanged(&expected, Some(&current)).is_err());
        current = expected.clone();
        current.manifest_path.push_str(".reinstalled");
        assert!(ensure_update_target_unchanged(&expected, Some(&current)).is_err());
        assert!(ensure_update_target_unchanged(&expected, None).is_err());
    }

    #[test]
    fn cli_user_dir_creation_seeds_legacy_config_before_printing_config_dir() {
        let plugin_id = unique_plugin_id("legacy-config");
        let config_dir = crate::plugin_paths::plugin_config_dir(&plugin_id);
        let state_dir = crate::plugin_paths::plugin_state_dir(&plugin_id);
        let legacy_dir = crate::config::config_dir().join("plugins").join(&plugin_id);
        let _ = std::fs::remove_dir_all(&config_dir);
        let _ = std::fs::remove_dir_all(&state_dir);
        let _ = std::fs::remove_dir_all(&legacy_dir);
        std::fs::create_dir_all(&legacy_dir).unwrap();
        std::fs::write(legacy_dir.join(".env"), "TOKEN=legacy\n").unwrap();

        assert_eq!(
            plugin_config_dir_command(std::slice::from_ref(&plugin_id)).unwrap(),
            0
        );

        assert_eq!(
            std::fs::read_to_string(config_dir.join(".env")).unwrap(),
            "TOKEN=legacy\n"
        );

        let _ = std::fs::remove_dir_all(config_dir);
        let _ = std::fs::remove_dir_all(state_dir);
        let _ = std::fs::remove_dir_all(legacy_dir);
    }
}