eclipse-core 0.13.3

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! `#505`: what the loaders complained about, in one answer.
//!
//! Every manifest, skill and plugin warning this build produces used to exist only on stderr: the
//! CLI printed it at startup and nobody else ever saw it. `doctor` was the only other consumer, and
//! a dashboard user has no reason to run a command in another window. This module is the answer
//! both read — one `Report` with one shape, so the panes and the terminal cannot disagree about what
//! is wrong.
//!
//! It is deliberately a *collection* and not a second implementation: the plugin problems are the
//! ones `plugins::load` produced, the broken skills are the ones `skills::discover` marked, the skill
//! notes are `context_files`' own budget notes. A problem that is not produced by a loader cannot
//! appear here, which is what keeps the list honest.
//!
//! Re-reading the loaders is cheap — they are file walks, no process — and it is what makes the
//! report live: a fixed skill disappears from the next `GET /api/problems` with nothing to reload.

use crate::config::{Config, EnvFn};
use std::path::PathBuf;

/// What kind of thing complained. The dashboard groups by this, and a person reads the group name
/// before the sentence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// A `plugin.toml` that did not parse, a plugin that could not be enabled, an MCP server a
    /// manifest declared and could not start.
    Plugin,
    /// A `SKILL.md` that is missing its frontmatter, has no description, or is unreadable.
    Skill,
    /// The context a request is built from: a file that could not be read, a skills index that had
    /// to drop entries to fit its budget (`#350`).
    Context,
    /// The configuration itself — a route that is not a route, a value that is the wrong type.
    Config,
}

impl Kind {
    /// The word the dashboard shows, and the one `eclipse doctor` prints.
    pub fn as_str(self) -> &'static str {
        match self {
            Kind::Plugin => "plugin",
            Kind::Skill => "skill",
            Kind::Context => "context",
            Kind::Config => "config",
        }
    }
}

/// One complaint, with where it came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem {
    pub kind: Kind,
    pub text: String,
    /// The file or directory the complaint is about, when the loader named one.
    pub path: Option<PathBuf>,
}

impl Problem {
    pub fn new(kind: Kind, text: impl Into<String>) -> Self {
        Self {
            kind,
            text: text.into(),
            path: None,
        }
    }

    pub fn at(mut self, path: impl Into<PathBuf>) -> Self {
        self.path = Some(path.into());
        self
    }
}

/// Everything the loaders said, and what they looked at.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Report {
    pub problems: Vec<Problem>,
    /// The things that loaded cleanly, by their own names — so an empty list is visibly "nothing
    /// found" rather than "nothing checked". `plugin:seeing`, `skill:deploy`, `context:USER.md`.
    pub checked: Vec<String>,
}

impl Report {
    pub fn is_empty(&self) -> bool {
        self.problems.is_empty()
    }

    /// Count by kind, for the readout.
    pub fn count(&self, kind: Kind) -> usize {
        self.problems.iter().filter(|p| p.kind == kind).count()
    }

    /// The one line a front shows when there is nothing to say.
    pub fn summary(&self) -> String {
        if self.problems.is_empty() {
            format!(
                "nothing to fix — {} thing(s) checked and all of them loaded",
                self.checked.len()
            )
        } else {
            format!(
                "{} problem(s): {} plugin, {} skill, {} context, {} config",
                self.problems.len(),
                self.count(Kind::Plugin),
                self.count(Kind::Skill),
                self.count(Kind::Context),
                self.count(Kind::Config)
            )
        }
    }
}

/// Ask the loaders what they think, the same way a run does.
///
/// The order is the one the agent uses: plugins first (they carry skills and prompts), then the
/// skills roots, then the context that is assembled from both. Nothing here starts a process, so it
/// can be called from a request handler.
pub fn collect(cfg: &Config, env: EnvFn) -> Report {
    let workspace = cfg.workspace_root(env);
    let plugin_dirs = cfg.plugins_dirs(env);
    let loaded = crate::plugins::load(&plugin_dirs, &cfg.plugins.enabled)
        .with_scripts_dir(cfg.scripts_dir(env))
        .with_mcp(crate::plugins::McpSettings::from_config(cfg))
        .with_config_mcp(cfg);
    let mut report = Report::default();

    // What was *searched* is part of the answer: "nothing to fix" over zero directories is a
    // different statement from "nothing to fix" over four, and only one of them is reassuring.
    for dir in &plugin_dirs {
        report
            .checked
            .push(format!("plugin dir: {}", dir.display()));
    }
    for problem in &loaded.problems {
        report
            .problems
            .push(Problem::new(Kind::Plugin, problem.clone()));
    }
    for plugin in &loaded.plugins {
        report.checked.push(format!("plugin:{}", plugin.name));
    }

    let roots = crate::skills::roots_for(cfg, env, &loaded, &workspace);
    for root in &roots {
        report
            .checked
            .push(format!("skill root: {}", root.dir.display()));
    }
    let skills = crate::skills::discover(&roots);
    for problem in &skills.problems {
        report
            .problems
            .push(Problem::new(Kind::Skill, problem.clone()));
    }
    for broken in skills.broken() {
        // The loader keeps a broken skill as a `Found` with its reason, which is the thing a person
        // needs: the file and the sentence. A broken skill is never silently absent from the count.
        let why = match &broken.state {
            Ok(_) => continue,
            Err(why) => why.clone(),
        };
        report.problems.push(
            Problem::new(Kind::Skill, format!("{}: {why}", broken.name)).at(broken.path.clone()),
        );
    }
    for (found, _) in skills.active() {
        report.checked.push(format!("skill:{}", found.name));
    }
    for shadowed in skills.found.iter().filter(|f| !f.shadows.is_empty()) {
        report.checked.push(format!(
            "skill:{} (won the name in {})",
            shadowed.name,
            shadowed.dir.display()
        ));
    }

    let ctx = crate::context_files::for_config(cfg, env, &loaded);
    for note in &ctx.skill_notes {
        report
            .problems
            .push(Problem::new(Kind::Context, note.clone()));
    }
    // The context layers are what an agent's prompt is built from, so "checked" names them the way
    // `context show` does: the file, not the internal type.
    for layer in ctx
        .instructions
        .iter()
        .chain(ctx.user.iter())
        .chain(ctx.memory.iter())
    {
        report
            .checked
            .push(format!("context:{}", layer.path.display()));
    }

    report
}

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

    fn config_with(home: &std::path::Path) -> Config {
        let env = [("HOME".to_string(), home.display().to_string())];
        let lookup = move |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
        Config::load_with_profile(None, None, &lookup).expect("a config")
    }

    #[test]
    fn a_directory_that_is_not_there_is_not_a_problem() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path().join("home");
        std::fs::create_dir_all(home.join(".eclipse")).unwrap();
        let cfg = config_with(&home);
        let env = [("HOME".to_string(), home.display().to_string())];
        let lookup = move |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
        let report = collect(&cfg, &lookup);
        assert!(
            report.is_empty(),
            "an empty install has nothing to fix: {:?}",
            report.problems
        );
        assert!(report.summary().contains("nothing to fix"));
        assert!(
            report.checked.iter().any(|c| c.starts_with("skill root:")),
            "the readout says what was searched, even when it found nothing: {:?}",
            report.checked
        );
    }

    #[test]
    fn a_broken_skill_and_a_broken_manifest_both_appear() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path().join("home");
        let config_dir = home.join(".eclipse");
        std::fs::create_dir_all(config_dir.join("skills/broken")).unwrap();
        // No frontmatter at all: the loader's own refusal, not one invented here.
        std::fs::write(
            config_dir.join("skills/broken/SKILL.md"),
            "just some text with no frontmatter\n",
        )
        .unwrap();
        // An unenabled plugin with a broken manifest stays quiet on purpose (`plugins::load`: not
        // the user's problem until they enable it) — so it is enabled here, which is the state in
        // which a person would be looking at the dashboard and wondering why it did nothing.
        std::fs::write(
            config_dir.join("config.toml"),
            "[plugins]\nenabled = [\"bad\"]\n",
        )
        .unwrap();
        std::fs::create_dir_all(config_dir.join("plugins/bad")).unwrap();
        std::fs::write(config_dir.join("plugins/bad/plugin.toml"), "name = \n").unwrap();

        let cfg = config_with(&home);
        let env = [("HOME".to_string(), home.display().to_string())];
        let lookup = move |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
        let report = collect(&cfg, &lookup);
        assert!(
            report.count(Kind::Skill) >= 1,
            "the broken skill is reported: {:?}",
            report.problems
        );
        assert!(
            report.count(Kind::Plugin) >= 1,
            "the broken manifest is reported: {:?}",
            report.problems
        );
        let summary = report.summary();
        assert!(summary.contains("skill"), "{summary}");
        assert!(summary.contains("plugin"), "{summary}");
        // Fix it, and it goes away with no reload: the report is a re-read, not a cache.
        std::fs::write(
            config_dir.join("skills/broken/SKILL.md"),
            "---\nname: broken\ndescription: now valid\n---\n\nbody\n",
        )
        .unwrap();
        std::fs::write(
            config_dir.join("plugins/bad/plugin.toml"),
            "name = \"bad\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        let after = collect(&cfg, &lookup);
        assert!(
            after.is_empty(),
            "both are gone once fixed: {:?}",
            after.problems
        );
    }

    #[test]
    fn a_kind_says_the_word_the_dashboard_groups_by() {
        assert_eq!(Kind::Plugin.as_str(), "plugin");
        assert_eq!(Kind::Skill.as_str(), "skill");
        assert_eq!(Kind::Context.as_str(), "context");
        assert_eq!(Kind::Config.as_str(), "config");
    }
}