eclipse-cli 0.13.4

Command-line interface for eclipse
//! `eclipse skills list | view | validate`: what skills exist, where each one came from, and
//! which are broken.
//!
//! These print what [`eclipse_core::skills::discover`] finds from the same roots the prompt
//! index and the skill tools use, so the listing cannot describe a skill the agent does not
//! see. `validate` exists for scripts: it exits non-zero when anything is broken, and names each.

use crate::ui::Style;
use anyhow::{bail, Result};
use eclipse_core::config::{process_env, Config};
use eclipse_core::plugins::{self, Plugins};
use eclipse_core::skills::{self, Found, Report, Root};
use serde_json::json;

/// Discover skills the way the agent does: every root, plugins included.
pub fn discover(cfg: &Config, loaded: &Plugins) -> (Vec<Root>, Report) {
    let workspace = cfg.workspace_root(&process_env);
    let roots = skills::roots_for(cfg, &process_env, loaded, &workspace);
    let report = skills::discover(&roots);
    (roots, report)
}

fn discover_for(cfg: &Config) -> (Vec<Root>, Report) {
    let loaded = plugins::load(&cfg.plugins_dirs(&process_env), &cfg.plugins.enabled);
    discover(cfg, &loaded)
}

fn describe(found: &Found) -> serde_json::Value {
    let shadows: Vec<_> = found
        .shadows
        .iter()
        .map(|s| json!({"source": s.source.label(), "path": s.path}))
        .collect();
    let mut entry = json!({
        "name": found.name,
        "source": found.source.label(),
        "path": found.path,
        "broken": found.state.is_err(),
        "error": found.broken_reason(),
        "shadows": shadows,
    });
    if let Some(skill) = found.skill() {
        entry["description"] = json!(skill.meta.description);
        entry["version"] = json!(skill.meta.version);
        entry["tags"] = json!(skill.meta.tags);
        entry["requires"] = json!(skill.meta.requires);
    }
    entry
}

/// `eclipse skills list`.
pub fn list(cfg: &Config, style: &Style, as_json: bool) -> Result<()> {
    let (roots, report) = discover_for(cfg);
    for problem in &report.problems {
        eprintln!("{} {problem}", style.yellow("warning:"));
    }
    if as_json {
        let all: Vec<_> = report.found.iter().map(describe).collect();
        println!("{}", serde_json::to_string_pretty(&all)?);
        return Ok(());
    }
    println!(
        "{} {}",
        style.dim("profile:"),
        style.cyan(cfg.profile_name())
    );
    let broken = report.broken().count();
    println!(
        "{} {} found, {} broken",
        style.dim("skills:"),
        report.found.len(),
        broken
    );
    if report.found.is_empty() {
        println!();
        println!("no skills. Looked in:");
        for root in &roots {
            println!("  {:<18} {}", root.source.label(), root.dir.display());
        }
        return Ok(());
    }
    println!();
    let name_width = report
        .found
        .iter()
        .map(|f| f.name.chars().count())
        .chain(std::iter::once(4))
        .max()
        .unwrap_or(4);
    let source_width = report
        .found
        .iter()
        .map(|f| f.source.label().chars().count())
        .chain(std::iter::once(6))
        .max()
        .unwrap_or(6);
    println!(
        "{}",
        style.dim(&format!(
            "{:<name_width$}  {:<source_width$}  PATH",
            "NAME", "SOURCE"
        ))
    );
    for found in &report.found {
        let name = format!("{:<name_width$}", found.name);
        let name = if found.state.is_err() {
            style.red(&name)
        } else {
            name
        };
        println!(
            "{name}  {:<source_width$}  {}",
            found.source.label(),
            found.path.display()
        );
        if let Some(reason) = found.broken_reason() {
            println!("  {} {reason}", style.red("BROKEN:"));
        }
        for shadowed in &found.shadows {
            println!(
                "  {} {} ({})",
                style.dim("shadows:"),
                shadowed.path.display(),
                shadowed.source.label()
            );
        }
    }
    Ok(())
}

/// `eclipse skills view <name>`: the frontmatter, the body and the files the skill ships.
pub fn view(cfg: &Config, style: &Style, name: &str) -> Result<()> {
    let (_, report) = discover_for(cfg);
    let Some(found) = report.get(name) else {
        let mut names: Vec<&str> = report.active().map(|(f, _)| f.name.as_str()).collect();
        names.sort_unstable();
        bail!(
            "no skill named {name:?}. Available: {}",
            if names.is_empty() {
                "none".to_string()
            } else {
                names.join(", ")
            }
        );
    };
    if let Some(reason) = found.broken_reason() {
        bail!(
            "skill {:?} is broken: {reason} ({})",
            found.name,
            found.path.display()
        );
    }
    let Some(skill) = found.skill() else {
        bail!("skill {:?} did not load", found.name);
    };
    let meta = &skill.meta;
    println!(
        "{} {}",
        style.bold(&meta.name),
        style.dim(&format!("({})", found.source.label()))
    );
    println!("{} {}", style.dim("path:"), found.path.display());
    if !meta.description.is_empty() {
        println!("{} {}", style.dim("description:"), meta.description);
    }
    if let Some(version) = &meta.version {
        println!("{} {version}", style.dim("version:"));
    }
    if !meta.tags.is_empty() {
        println!("{} {}", style.dim("tags:"), meta.tags.join(", "));
    }
    if !meta.requires.is_empty() {
        println!("{} {}", style.dim("requires:"), meta.requires.join(", "));
    }
    for shadowed in &found.shadows {
        println!(
            "{} {} ({})",
            style.dim("shadows:"),
            shadowed.path.display(),
            shadowed.source.label()
        );
    }
    println!();
    println!("{}", skill.body);
    let linked = skills::linked_files(&found.dir);
    if !linked.is_empty() {
        println!();
        println!("{}", style.dim("linked files:"));
        for file in linked {
            println!("  {file}");
        }
    }
    Ok(())
}

/// `eclipse skills validate`: fails when any skill is broken, and says which.
pub fn validate(cfg: &Config, style: &Style) -> Result<()> {
    let (_, report) = discover_for(cfg);
    let mut failures = 0;
    for found in report.broken() {
        failures += 1;
        println!(
            "{} {} ({}) {}: {}",
            style.red("broken:"),
            found.name,
            found.source.label(),
            found.path.display(),
            found.broken_reason().unwrap_or("unknown reason")
        );
    }
    for problem in &report.problems {
        failures += 1;
        println!("{} {problem}", style.red("unreadable:"));
    }
    if failures > 0 {
        bail!("{failures} problem(s) found in skills");
    }
    println!(
        "{} {} skill(s)",
        style.green("ok:"),
        report.active().count()
    );
    Ok(())
}