Skip to main content

eclipse_core/
problems.rs

1//! `#505`: what the loaders complained about, in one answer.
2//!
3//! Every manifest, skill and plugin warning this build produces used to exist only on stderr: the
4//! CLI printed it at startup and nobody else ever saw it. `doctor` was the only other consumer, and
5//! a dashboard user has no reason to run a command in another window. This module is the answer
6//! both read — one `Report` with one shape, so the panes and the terminal cannot disagree about what
7//! is wrong.
8//!
9//! It is deliberately a *collection* and not a second implementation: the plugin problems are the
10//! ones `plugins::load` produced, the broken skills are the ones `skills::discover` marked, the skill
11//! notes are `context_files`' own budget notes. A problem that is not produced by a loader cannot
12//! appear here, which is what keeps the list honest.
13//!
14//! Re-reading the loaders is cheap — they are file walks, no process — and it is what makes the
15//! report live: a fixed skill disappears from the next `GET /api/problems` with nothing to reload.
16
17use crate::config::{Config, EnvFn};
18use std::path::PathBuf;
19
20/// What kind of thing complained. The dashboard groups by this, and a person reads the group name
21/// before the sentence.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Kind {
24    /// A `plugin.toml` that did not parse, a plugin that could not be enabled, an MCP server a
25    /// manifest declared and could not start.
26    Plugin,
27    /// A `SKILL.md` that is missing its frontmatter, has no description, or is unreadable.
28    Skill,
29    /// The context a request is built from: a file that could not be read, a skills index that had
30    /// to drop entries to fit its budget (`#350`).
31    Context,
32    /// The configuration itself — a route that is not a route, a value that is the wrong type.
33    Config,
34}
35
36impl Kind {
37    /// The word the dashboard shows, and the one `eclipse doctor` prints.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            Kind::Plugin => "plugin",
41            Kind::Skill => "skill",
42            Kind::Context => "context",
43            Kind::Config => "config",
44        }
45    }
46}
47
48/// One complaint, with where it came from.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Problem {
51    pub kind: Kind,
52    pub text: String,
53    /// The file or directory the complaint is about, when the loader named one.
54    pub path: Option<PathBuf>,
55}
56
57impl Problem {
58    pub fn new(kind: Kind, text: impl Into<String>) -> Self {
59        Self {
60            kind,
61            text: text.into(),
62            path: None,
63        }
64    }
65
66    pub fn at(mut self, path: impl Into<PathBuf>) -> Self {
67        self.path = Some(path.into());
68        self
69    }
70}
71
72/// Everything the loaders said, and what they looked at.
73#[derive(Debug, Clone, Default, PartialEq, Eq)]
74pub struct Report {
75    pub problems: Vec<Problem>,
76    /// The things that loaded cleanly, by their own names — so an empty list is visibly "nothing
77    /// found" rather than "nothing checked". `plugin:seeing`, `skill:deploy`, `context:USER.md`.
78    pub checked: Vec<String>,
79}
80
81impl Report {
82    pub fn is_empty(&self) -> bool {
83        self.problems.is_empty()
84    }
85
86    /// Count by kind, for the readout.
87    pub fn count(&self, kind: Kind) -> usize {
88        self.problems.iter().filter(|p| p.kind == kind).count()
89    }
90
91    /// The one line a front shows when there is nothing to say.
92    pub fn summary(&self) -> String {
93        if self.problems.is_empty() {
94            format!(
95                "nothing to fix — {} thing(s) checked and all of them loaded",
96                self.checked.len()
97            )
98        } else {
99            format!(
100                "{} problem(s): {} plugin, {} skill, {} context, {} config",
101                self.problems.len(),
102                self.count(Kind::Plugin),
103                self.count(Kind::Skill),
104                self.count(Kind::Context),
105                self.count(Kind::Config)
106            )
107        }
108    }
109}
110
111/// Ask the loaders what they think, the same way a run does.
112///
113/// The order is the one the agent uses: plugins first (they carry skills and prompts), then the
114/// skills roots, then the context that is assembled from both. Nothing here starts a process, so it
115/// can be called from a request handler.
116pub fn collect(cfg: &Config, env: EnvFn) -> Report {
117    let workspace = cfg.workspace_root(env);
118    let plugin_dirs = cfg.plugins_dirs(env);
119    let loaded = crate::plugins::load(&plugin_dirs, &cfg.plugins.enabled)
120        .with_scripts_dir(cfg.scripts_dir(env))
121        .with_mcp(crate::plugins::McpSettings::from_config(cfg))
122        .with_config_mcp(cfg);
123    let mut report = Report::default();
124
125    // What was *searched* is part of the answer: "nothing to fix" over zero directories is a
126    // different statement from "nothing to fix" over four, and only one of them is reassuring.
127    for dir in &plugin_dirs {
128        report
129            .checked
130            .push(format!("plugin dir: {}", dir.display()));
131    }
132    for problem in &loaded.problems {
133        report
134            .problems
135            .push(Problem::new(Kind::Plugin, problem.clone()));
136    }
137    for plugin in &loaded.plugins {
138        report.checked.push(format!("plugin:{}", plugin.name));
139    }
140
141    let roots = crate::skills::roots_for(cfg, env, &loaded, &workspace);
142    for root in &roots {
143        report
144            .checked
145            .push(format!("skill root: {}", root.dir.display()));
146    }
147    let skills = crate::skills::discover(&roots);
148    for problem in &skills.problems {
149        report
150            .problems
151            .push(Problem::new(Kind::Skill, problem.clone()));
152    }
153    for broken in skills.broken() {
154        // The loader keeps a broken skill as a `Found` with its reason, which is the thing a person
155        // needs: the file and the sentence. A broken skill is never silently absent from the count.
156        let why = match &broken.state {
157            Ok(_) => continue,
158            Err(why) => why.clone(),
159        };
160        report.problems.push(
161            Problem::new(Kind::Skill, format!("{}: {why}", broken.name)).at(broken.path.clone()),
162        );
163    }
164    for (found, _) in skills.active() {
165        report.checked.push(format!("skill:{}", found.name));
166    }
167    for shadowed in skills.found.iter().filter(|f| !f.shadows.is_empty()) {
168        report.checked.push(format!(
169            "skill:{} (won the name in {})",
170            shadowed.name,
171            shadowed.dir.display()
172        ));
173    }
174
175    let ctx = crate::context_files::for_config(cfg, env, &loaded);
176    for note in &ctx.skill_notes {
177        report
178            .problems
179            .push(Problem::new(Kind::Context, note.clone()));
180    }
181    // The context layers are what an agent's prompt is built from, so "checked" names them the way
182    // `context show` does: the file, not the internal type.
183    for layer in ctx
184        .instructions
185        .iter()
186        .chain(ctx.user.iter())
187        .chain(ctx.memory.iter())
188    {
189        report
190            .checked
191            .push(format!("context:{}", layer.path.display()));
192    }
193
194    report
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    fn config_with(home: &std::path::Path) -> Config {
202        let env = [("HOME".to_string(), home.display().to_string())];
203        let lookup = move |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
204        Config::load_with_profile(None, None, &lookup).expect("a config")
205    }
206
207    #[test]
208    fn a_directory_that_is_not_there_is_not_a_problem() {
209        let dir = tempfile::tempdir().unwrap();
210        let home = dir.path().join("home");
211        std::fs::create_dir_all(home.join(".eclipse")).unwrap();
212        let cfg = config_with(&home);
213        let env = [("HOME".to_string(), home.display().to_string())];
214        let lookup = move |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
215        let report = collect(&cfg, &lookup);
216        assert!(
217            report.is_empty(),
218            "an empty install has nothing to fix: {:?}",
219            report.problems
220        );
221        assert!(report.summary().contains("nothing to fix"));
222        assert!(
223            report.checked.iter().any(|c| c.starts_with("skill root:")),
224            "the readout says what was searched, even when it found nothing: {:?}",
225            report.checked
226        );
227    }
228
229    #[test]
230    fn a_broken_skill_and_a_broken_manifest_both_appear() {
231        let dir = tempfile::tempdir().unwrap();
232        let home = dir.path().join("home");
233        let config_dir = home.join(".eclipse");
234        std::fs::create_dir_all(config_dir.join("skills/broken")).unwrap();
235        // No frontmatter at all: the loader's own refusal, not one invented here.
236        std::fs::write(
237            config_dir.join("skills/broken/SKILL.md"),
238            "just some text with no frontmatter\n",
239        )
240        .unwrap();
241        // An unenabled plugin with a broken manifest stays quiet on purpose (`plugins::load`: not
242        // the user's problem until they enable it) — so it is enabled here, which is the state in
243        // which a person would be looking at the dashboard and wondering why it did nothing.
244        std::fs::write(
245            config_dir.join("config.toml"),
246            "[plugins]\nenabled = [\"bad\"]\n",
247        )
248        .unwrap();
249        std::fs::create_dir_all(config_dir.join("plugins/bad")).unwrap();
250        std::fs::write(config_dir.join("plugins/bad/plugin.toml"), "name = \n").unwrap();
251
252        let cfg = config_with(&home);
253        let env = [("HOME".to_string(), home.display().to_string())];
254        let lookup = move |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
255        let report = collect(&cfg, &lookup);
256        assert!(
257            report.count(Kind::Skill) >= 1,
258            "the broken skill is reported: {:?}",
259            report.problems
260        );
261        assert!(
262            report.count(Kind::Plugin) >= 1,
263            "the broken manifest is reported: {:?}",
264            report.problems
265        );
266        let summary = report.summary();
267        assert!(summary.contains("skill"), "{summary}");
268        assert!(summary.contains("plugin"), "{summary}");
269        // Fix it, and it goes away with no reload: the report is a re-read, not a cache.
270        std::fs::write(
271            config_dir.join("skills/broken/SKILL.md"),
272            "---\nname: broken\ndescription: now valid\n---\n\nbody\n",
273        )
274        .unwrap();
275        std::fs::write(
276            config_dir.join("plugins/bad/plugin.toml"),
277            "name = \"bad\"\nversion = \"0.1.0\"\n",
278        )
279        .unwrap();
280        let after = collect(&cfg, &lookup);
281        assert!(
282            after.is_empty(),
283            "both are gone once fixed: {:?}",
284            after.problems
285        );
286    }
287
288    #[test]
289    fn a_kind_says_the_word_the_dashboard_groups_by() {
290        assert_eq!(Kind::Plugin.as_str(), "plugin");
291        assert_eq!(Kind::Skill.as_str(), "skill");
292        assert_eq!(Kind::Context.as_str(), "context");
293        assert_eq!(Kind::Config.as_str(), "config");
294    }
295}