Skip to main content

eclipse_core/
doctor.rs

1//! `eclipse doctor`: reach for each thing that can be wrong, and say what to do about it.
2//!
3//! The point is not a health score. It is that every finding carries **the command that fixes
4//! it**, and that the repairs which are safe to make unattended are made unattended: create a
5//! directory an install is supposed to have, restore a permission, clear a lock whose holder is
6//! gone, and drop a plugin that will not load from `[plugins] enabled` — that last one because an
7//! operator who has to remove a broken plugin by hand before the agent will start has been given
8//! a service that limps.
9//!
10//! Nothing here is a policy of its own. The probes read the same config, the same store, the same
11//! plugin and skill loaders the agent uses; a doctor with a second opinion about what "loads" is a
12//! doctor that reports green while the run fails.
13//!
14//! **What is deliberately not repaired.** A broken *skill* is named and left alone: there is no
15//! `[skills] disabled` list, and inventing one here would be a config key with one reader. A
16//! config that does not parse is not repaired at all — a guessed fix to somebody's file is worse
17//! than a sentence saying which line is wrong.
18
19use crate::config::{Config, EnvFn};
20use std::path::PathBuf;
21
22/// How bad a finding is. `Note` is information worth printing on a healthy install; `Problem` is
23/// something that will stop a run working.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
25pub enum Level {
26    Ok,
27    Note,
28    Warn,
29    Problem,
30}
31
32impl Level {
33    pub fn label(&self) -> &'static str {
34        match self {
35            Level::Ok => "ok",
36            Level::Note => "note",
37            Level::Warn => "warn",
38            Level::Problem => "problem",
39        }
40    }
41}
42
43/// A repair that is safe to apply without asking.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum Repair {
46    /// `mkdir -p`
47    MakeDir(PathBuf),
48    /// `chmod <mode>`, for a file that holds something private.
49    Chmod(PathBuf, u32),
50    /// Remove the session lock files that no process holds a lock on.
51    ClearLocks(Vec<PathBuf>),
52    /// Take a plugin out of `[plugins] enabled`, which is what makes the next run start clean.
53    DisablePlugin(String),
54    /// Forget a background task whose process is gone. Its session and its log stay: what is
55    /// dropped is the registry entry that claims to be alive.
56    ForgetTask(PathBuf),
57}
58
59impl Repair {
60    /// One line saying what was done, for `--fix`'s output.
61    pub fn describe(&self) -> String {
62        match self {
63            Repair::MakeDir(p) => format!("created {}", p.display()),
64            Repair::Chmod(p, mode) => format!("set {} to {mode:o}", p.display()),
65            Repair::ClearLocks(paths) => match paths.len() {
66                1 => format!("removed the stale lock {}", paths[0].display()),
67                n => format!("removed {n} stale lock files"),
68            },
69            Repair::DisablePlugin(name) => {
70                format!("removed `{name}` from [plugins] enabled (the directory stays)")
71            }
72            Repair::ForgetTask(path) => format!("forgot the background task {}", path.display()),
73        }
74    }
75}
76
77/// One thing the doctor looked at.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Finding {
80    pub level: Level,
81    /// The area, printed first: `config`, `provider`, `layout`, `permissions`, `sessions`,
82    /// `plugins`, `skills`, `shell`.
83    pub area: &'static str,
84    pub detail: String,
85    /// What a person should run, or change, when this is not `Ok`.
86    pub fix: Option<String>,
87    /// A repair `--fix` may apply. `None` means a human decision.
88    pub repair: Option<Repair>,
89}
90
91impl Finding {
92    pub fn ok(area: &'static str, detail: impl Into<String>) -> Self {
93        Self {
94            level: Level::Ok,
95            area,
96            detail: detail.into(),
97            fix: None,
98            repair: None,
99        }
100    }
101
102    pub fn new(level: Level, area: &'static str, detail: impl Into<String>) -> Self {
103        Self {
104            level,
105            area,
106            detail: detail.into(),
107            fix: None,
108            repair: None,
109        }
110    }
111
112    pub fn fix(mut self, what: impl Into<String>) -> Self {
113        self.fix = Some(what.into());
114        self
115    }
116
117    pub fn repair(mut self, repair: Repair) -> Self {
118        self.repair = Some(repair);
119        self
120    }
121}
122
123/// Whether anything is wrong, and how wrong.
124#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
125pub struct Tally {
126    pub problems: usize,
127    pub warnings: usize,
128    pub repairable: usize,
129}
130
131impl Tally {
132    pub fn of(findings: &[Finding]) -> Tally {
133        let mut t = Tally::default();
134        for f in findings {
135            match f.level {
136                Level::Problem => t.problems += 1,
137                Level::Warn => t.warnings += 1,
138                _ => {}
139            }
140            if f.repair.is_some() {
141                t.repairable += 1;
142            }
143        }
144        t
145    }
146
147    /// `1 problem, 2 warnings` — or `nothing to fix` when there is nothing to say.
148    pub fn summary(&self) -> String {
149        if self.problems == 0 && self.warnings == 0 {
150            return "nothing to fix".to_string();
151        }
152        let mut parts = Vec::new();
153        if self.problems > 0 {
154            parts.push(format!("{} problem(s)", self.problems));
155        }
156        if self.warnings > 0 {
157            parts.push(format!("{} warning(s)", self.warnings));
158        }
159        parts.join(", ")
160    }
161}
162
163/// Everything that can be checked without a network.
164///
165/// `cfg` is the config that actually loaded — if it did not load, the caller says so and stops,
166/// because every probe below would then be guessing.
167pub fn check(cfg: &Config, env: EnvFn<'_>) -> Vec<Finding> {
168    let mut found = Vec::new();
169    check_layout(cfg, env, &mut found);
170    check_permissions(cfg, env, &mut found);
171    check_sessions(cfg, env, &mut found);
172    check_plugins(cfg, env, &mut found);
173    check_skills(cfg, env, &mut found);
174    check_tool_schemas(cfg, env, &mut found);
175    check_vision(cfg, env, &mut found);
176    check_shell(cfg, env, &mut found);
177    check_tasks(cfg, env, &mut found);
178    check_dashboard_auth(cfg, env, &mut found);
179    check_config_version(cfg, env, &mut found);
180    found
181}
182
183/// The file's `config_version`, against the one this build writes.
184///
185/// A `Warn`, not a `Note`, for the reason `check_dashboard_auth` gives: `doctor` only prints a
186/// `fix:` line from `Warn` up, and the finding *is* the command. Only when a config file exists —
187/// a run against built-in defaults has nothing to migrate, and saying so would be noise on every
188/// box that never ran `config init`.
189fn check_config_version(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
190    let built = crate::config::CONFIG_VERSION;
191    if cfg.config_version >= built {
192        return;
193    }
194    // A run against built-in defaults has no file to migrate, and says nothing about it.
195    let Some(path) = crate::config::config_path(env) else {
196        return;
197    };
198    if !path.exists() {
199        return;
200    }
201    found.push(
202        Finding::new(
203            Level::Warn,
204            "config",
205            format!(
206                "the config file was written for shape v{} and this build writes v{}: a setting \
207                 added since then is filled by its default and never appears in the file",
208                cfg.config_version, built
209            ),
210        )
211        .fix("eclipse config migrate --dry-run  # shows what it would add; then run it without --dry-run"),
212    );
213}
214
215/// The dashboard's sign-in (`#266`), and whether the install has moved off the shared token.
216///
217/// It only speaks when a dashboard exists — a token in `web.auth_token` is the proof somebody runs
218/// one — because `ok` lines about a feature nobody uses are noise (`check_tasks` draws the line in
219/// the same place). Two things it can find:
220///
221/// - **A password is set and does not parse.** That is a `Problem`, not a `Note`: the dashboard
222///   refuses to start on it, and the person's next click is a browser error page, not a shell. The
223///   fix names the file and the verb.
224/// - **Only the token is set.** A `Warn`, not a `Note`: it still works — the migration case — but
225///   nothing else in this install will ever mention that the door is one shared 64-character string
226///   with no user attached to it, and `doctor` also only prints a `fix:` line from `Warn` up. A
227///   `Note` here would be advice nobody is shown.
228fn check_dashboard_auth(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
229    // `map_or` rather than `is_none_or`: that one is 1.82 and this workspace still promises 1.75.
230    if cfg
231        .web
232        .auth_token
233        .as_deref()
234        .is_none_or(|t| t.trim().is_empty())
235    {
236        return; // no dashboard: nothing to say
237    }
238    let lookup = |name: &str| env(name).or_else(|| cfg.dotenv.values.get(name).cloned());
239    match crate::auth::Credentials::resolve(lookup) {
240        Ok(crate::auth::Credentials::Password { user, .. }) => found.push(Finding::ok(
241            "web",
242            format!("the dashboard signs in as {user} with a password (the token is the API's)"),
243        )),
244        Ok(crate::auth::Credentials::Token) => found.push(
245            Finding::new(
246                Level::Warn,
247                "web",
248                "the dashboard still signs in with `web.auth_token`: one shared string, pasted into \
249                 a box, with no user to say who signed in",
250            )
251            .fix("eclipse web passwd — sets a username and a password hash in .env; the token \
252                  keeps working for `/v1`"),
253        ),
254        // A hash this build cannot read stops the dashboard from starting at all, so it outranks
255        // "you could migrate": `Problem`, with what exactly the parser said.
256        Err(why) => found.push(
257            Finding::new(
258                Level::Problem,
259                "web",
260                format!("the dashboard's password is set but unusable — {why}"),
261            )
262            .fix("eclipse web passwd — rewrites the line it cannot read"),
263        ),
264    }
265}
266
267/// The background tasks: an entry whose process is gone is a finding, because it is the one state
268/// nothing else can correct — the process that would have written `done` never got there.
269///
270/// The pid is read through, not believed: [`crate::tasks::Task::state_now`] turns a stored
271/// `running` beside a dead pid into `died`, which is the same answer `/tasks` prints. Nothing is
272/// said when no task was ever started: an `ok` line about a feature nobody used is noise.
273fn check_tasks(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
274    let Ok(state) = cfg.state_dir(env) else {
275        return;
276    };
277    let registry = crate::tasks::Registry::new(state);
278    let tasks = registry.list();
279    if tasks.is_empty() {
280        return;
281    }
282    let mut reported = 0;
283    for task in tasks.iter().filter(|t| t.died()) {
284        reported += 1;
285        found.push(
286            Finding::new(
287                Level::Warn,
288                "tasks",
289                format!(
290                    "background task {} died and its entry was never closed: it was last seen {}                      ({})",
291                    task.session,
292                    crate::session::ago_words(task.updated_ms),
293                    task.last
294                ),
295            )
296            .fix(format!(
297                "rm {} — the transcript stays in `eclipse sessions`",
298                registry.path(&task.session).display()
299            ))
300            .repair(Repair::ForgetTask(registry.path(&task.session))),
301        );
302    }
303    // A run parked on an approval is a person's decision, not a defect: named, never repaired.
304    for task in tasks
305        .iter()
306        .filter(|t| t.state == crate::tasks::State::Waiting)
307    {
308        reported += 1;
309        found.push(Finding::new(
310            Level::Note,
311            "tasks",
312            format!(
313                "background task {} is waiting for an approval: {}",
314                task.session, task.detail
315            ),
316        ));
317    }
318    if reported == 0 {
319        let running = tasks.iter().filter(|t| !t.settled()).count();
320        let done = tasks.len() - running;
321        found.push(Finding::ok(
322            "tasks",
323            format!(
324                "{running} background task(s) running, {done} finished, none with a missing process"
325            ),
326        ));
327    }
328}
329
330/// The directories an install is supposed to have. A missing `skills/` is harmless; a missing
331/// state directory is a run that will fail on its first write, which is why it is a problem.
332fn check_layout(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
333    let mut made_note = Vec::new();
334    if let Some(dir) = cfg.global_context_dir(env) {
335        for name in ["memory", "skills", "plugins", "scripts"] {
336            let path = dir.join(name);
337            if path.is_dir() {
338                continue;
339            }
340            // `skills/`, `plugins/` and `scripts/` are created on demand by the thing that
341            // writes them; only `memory/` is expected from an install, and even that is created
342            // on first write. So these are notes, not problems.
343            made_note.push(name);
344            found.push(
345                Finding::new(
346                    Level::Note,
347                    "layout",
348                    format!(
349                        "{} does not exist yet (it is created on first use)",
350                        path.display()
351                    ),
352                )
353                .fix("nothing to do: `eclipse config init` creates the layout")
354                .repair(Repair::MakeDir(path.clone())),
355            );
356        }
357    }
358    if let Ok(dir) = cfg.sessions_dir(env) {
359        if !dir.is_dir() {
360            found.push(
361                Finding::new(
362                    Level::Warn,
363                    "layout",
364                    format!(
365                        "{} does not exist: the first run will create it",
366                        dir.display()
367                    ),
368                )
369                .fix("`eclipse sessions list` creates it, or `eclipse doctor --fix`")
370                .repair(Repair::MakeDir(dir.clone())),
371            );
372        }
373    }
374    if made_note.is_empty() {
375        found.push(Finding::ok(
376            "layout",
377            "the config, state and session directories exist",
378        ));
379    }
380}
381
382/// A file that holds a secret, or a session database, belongs to one user and to nobody else.
383#[cfg(unix)]
384fn check_permissions(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
385    use std::os::unix::fs::PermissionsExt;
386    let mut checked = 0;
387    let mut bad = 0;
388    let mut wanted: Vec<PathBuf> = Vec::new();
389    if let Some(dir) = cfg.global_context_dir(env) {
390        wanted.push(dir.join(".env"));
391        if let Some(profile) = cfg.global_context_dir(env) {
392            if cfg.profile_name() != "default" {
393                wanted.push(
394                    profile
395                        .join("profiles")
396                        .join(cfg.profile_name())
397                        .join(".env"),
398                );
399            }
400        }
401    }
402    if let Ok(dir) = cfg.sessions_dir(env) {
403        wanted.push(dir.join("sessions.db"));
404    }
405    for path in wanted {
406        let Ok(meta) = std::fs::metadata(&path) else {
407            continue;
408        };
409        checked += 1;
410        let mode = meta.permissions().mode() & 0o777;
411        if mode & 0o077 == 0 {
412            continue;
413        }
414        bad += 1;
415        found.push(
416            Finding::new(
417                Level::Warn,
418                "permissions",
419                format!(
420                    "{} is {mode:o}; only its owner should be able to read it",
421                    path.display()
422                ),
423            )
424            .fix(format!("chmod 600 {}", path.display()))
425            .repair(Repair::Chmod(path.clone(), 0o600)),
426        );
427    }
428    // One line per area: an `ok` under a warning about the same files reads as a contradiction.
429    if checked > 0 && bad == 0 {
430        found.push(Finding::ok("permissions", "private files are owner-only"));
431    }
432}
433
434#[cfg(not(unix))]
435fn check_permissions(_: &Config, _: EnvFn<'_>, _: &mut Vec<Finding>) {}
436
437/// The archive: it opens, it has full-text search, and no lock outlived the process that took it.
438fn check_sessions(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
439    let Ok(dir) = cfg.sessions_dir(env) else {
440        found.push(
441            Finding::new(
442                Level::Problem,
443                "sessions",
444                "no session directory can be resolved (HOME is not set)",
445            )
446            .fix("set HOME"),
447        );
448        return;
449    };
450    let store = crate::session::SessionStore::new(dir.clone());
451    // The ids this store actually holds, so a leftover lock from a session that is gone can be
452    // told apart from one whose session is still here and merely not running.
453    let mut known: std::collections::HashSet<String> = std::collections::HashSet::new();
454    match store.list_with_archived() {
455        Ok(list) => {
456            // Every row, archived ones included: "0 session(s)" on a store of filed-away work
457            // would read as a lost database (`#240`).
458            for session in &list {
459                known.insert(session.id.clone());
460            }
461            let archived = list.iter().filter(|s| s.archived).count();
462            let mut detail = match archived {
463                0 => format!("{} session(s) in {}", list.len(), dir.display()),
464                n => format!(
465                    "{} session(s) in {} ({} archived, out of the list — `sessions list --archived`)",
466                    list.len(),
467                    dir.display(),
468                    n
469                ),
470            };
471            if !store.has_fts() {
472                detail.push_str("; full-text search is unavailable in this build (LIKE is used instead)");
473            }
474            found.push(Finding::ok("sessions", detail));
475        }
476        Err(e) => found.push(
477            Finding::new(Level::Problem, "sessions", format!("the session database will not open: {e}"))
478                .fix("check the disk, then the permissions on sessions.db; the transcripts are still on disk"),
479        ),
480    }
481
482    // A lock file left behind by a process that no longer exists blocks the session until the
483    // kernel releases it — which it did, when the process died. The file is then just a file, and
484    // that is the *normal* state of a session that is not running right now: one finding per
485    // finished session turns the report into a list of the box's history (`#497` — 348 of them on
486    // one install, against a report that shows 30 and hides the count).
487    let stale = crate::session::stale_locks(&dir);
488    if !stale.is_empty() {
489        let orphans: Vec<&crate::session::StaleLock> = stale
490            .iter()
491            .filter(|lock| !known.contains(&lock.id))
492            .collect();
493        let mut detail = format!(
494            "{} lock file(s) with no holder in {} (checked with flock)",
495            stale.len(),
496            dir.display()
497        );
498        // Not "held by pid X, which is not running": nothing checked whether X lives. The
499        // decision is the `flock` probe in `session::stale_locks`, which the kernel answers for
500        // the whole machine -- so this finding is right even when `doctor` runs inside the `shell`
501        // sandbox, whose PID namespace hides every host process. A model read the old sentence as
502        // a pid check it could watch failing, concluded the warnings were false positives, and
503        // wrote that into MEMORY.md (#327).
504        let level = if orphans.is_empty() {
505            detail.push_str(" — normal for sessions that are not running");
506            Level::Note
507        } else {
508            let names: Vec<&str> = orphans.iter().take(3).map(|l| l.id.as_str()).collect();
509            let more = orphans.len().saturating_sub(names.len());
510            detail.push_str(&format!(
511                ", {} of them naming a session this store does not have: {}{}",
512                orphans.len(),
513                names.join(", "),
514                if more > 0 {
515                    format!(" and {more} more")
516                } else {
517                    String::new()
518                }
519            ));
520            Level::Warn
521        };
522        found.push(
523            Finding::new(level, "sessions", detail)
524                .fix("`eclipse doctor --fix` removes them; the sessions themselves are unaffected")
525                .repair(Repair::ClearLocks(
526                    stale.iter().map(|lock| lock.path.clone()).collect(),
527                )),
528        );
529    }
530
531    // A lock something is holding is a session in use right now — the case a lock file exists
532    // for. Worth one line, because it is what an "a run is in progress" refusal is talking about.
533    let held = crate::session::held_locks(&dir);
534    if !held.is_empty() {
535        let names: Vec<String> = held
536            .iter()
537            .take(3)
538            .map(|lock| format!("{} ({})", lock.id, lock.holder))
539            .collect();
540        let more = held.len().saturating_sub(names.len());
541        found.push(Finding::new(
542            Level::Warn,
543            "sessions",
544            format!(
545                "{} session(s) in use right now: {}{} — the lock is released when that run ends",
546                held.len(),
547                names.join(", "),
548                if more > 0 {
549                    format!(" and {more} more")
550                } else {
551                    String::new()
552                }
553            ),
554        ));
555    }
556}
557
558/// Plugins: what loaded, what did not, and what the config names but the disk does not have.
559fn check_plugins(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
560    let dirs = cfg.plugins_dirs(env);
561    let loaded = crate::plugins::load(&dirs, &cfg.plugins.enabled);
562    for problem in &loaded.problems {
563        found.push(
564            Finding::new(Level::Warn, "plugins", problem.clone())
565                .fix("fix the manifest, or remove the plugin from [plugins] enabled"),
566        );
567    }
568    for name in &cfg.plugins.enabled {
569        if !dirs.iter().any(|d| d.join(name).is_dir()) {
570            found.push(
571                Finding::new(
572                    Level::Problem,
573                    "plugins",
574                    format!("`{name}` is enabled but its directory is not there"),
575                )
576                .fix("remove it from [plugins] enabled, or restore the directory")
577                .repair(Repair::DisablePlugin(name.clone())),
578            );
579        }
580    }
581    // The tool count is what a listing would show, so the doctor and `eclipse tools list` agree
582    // about whether a plugin contributes anything.
583    let workspace = cfg.workspace_root(env);
584    let (tools, _skipped) = loaded.tools(&workspace, 1024, &[]);
585    let tools = tools.len();
586    if loaded.problems.is_empty() && !cfg.plugins.enabled.is_empty() {
587        found.push(Finding::ok(
588            "plugins",
589            format!("{} enabled, {tools} tool(s)", cfg.plugins.enabled.len()),
590        ));
591    }
592}
593
594/// Skills: a broken one is named with its reason and left alone — there is no `disabled` list for
595/// skills, and inventing one here would be a config key with a single reader.
596fn check_skills(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
597    let plugins = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled);
598    let workspace = cfg.workspace_root(env);
599    let roots = crate::skills::roots_for(cfg, env, &plugins, &workspace);
600    let report = crate::skills::discover(&roots);
601    for problem in &report.problems {
602        found.push(
603            Finding::new(Level::Warn, "skills", problem.clone())
604                .fix("check the directory's permissions"),
605        );
606    }
607    for broken in report.broken() {
608        let why = broken
609            .state
610            .as_ref()
611            .err()
612            .cloned()
613            .unwrap_or_else(|| "it did not load".into());
614        found.push(
615            Finding::new(
616                Level::Warn,
617                "skills",
618                format!("`{}` cannot be used: {why}", broken.name),
619            )
620            .fix(format!(
621                "fix {}; the agent is running without it",
622                broken.path.display()
623            )),
624        );
625    }
626    let active = report.active().count();
627    if report.problems.is_empty() && report.broken().next().is_none() {
628        found.push(Finding::ok("skills", format!("{active} load(s)")));
629    }
630    // `#350`: an index that does not fit used to be a stderr line on the CLI and nothing at all on
631    // the dashboard. The model now reads the omission in its own prompt; this is the operator's
632    // copy of the same fact, and the only one that names the knob.
633    let (index, _) = crate::skills::index(&report, cfg.skills.index_budget_chars);
634    let kept = index.as_ref().map(|i| i.names.len()).unwrap_or(0);
635    if kept < active {
636        found.push(
637            Finding::new(
638                Level::Warn,
639                "skills",
640                format!(
641                    "the index fits {kept} of {active} skill(s); the rest are reachable only by \
642                     name (`skill_search`, then `skill_view`)"
643                ),
644            )
645            .fix(format!(
646                "raise `[skills] index_budget_chars` ({} now) if the dropped ones matter, or leave \
647                 it: the model is told they exist",
648                cfg.skills.index_budget_chars
649            )),
650        );
651    }
652}
653
654/// `[tools]`: what the tool schemas cost, and where they come from (`#351`).
655///
656/// Every tool described in a request is paid for on every turn, whether or not the model calls it.
657/// Fourteen built-ins are a fair price; forty from an MCP server are not, and nothing used to say
658/// so — the deferral existed, defaulted to nothing, and was invisible. This is the number, split by
659/// the loader that contributed it, plus the knob that moves a source behind `tool_search`.
660fn check_tool_schemas(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
661    let loaded = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled)
662        .with_mcp(crate::plugins::McpSettings::from_config(cfg))
663        .with_config_mcp(cfg);
664    let workspace = cfg.workspace_root(env);
665    let mut problems = Vec::new();
666    let registry = crate::runtime::registry_for(cfg, &loaded, &workspace, &env, &mut problems);
667    let described = registry.descriptors();
668    let offered: Vec<&crate::tools::ToolDescriptor> =
669        described.iter().filter(|d| d.advertised).collect();
670    if offered.is_empty() {
671        found.push(Finding::ok("tools", "no tool is offered"));
672        return;
673    }
674    // What one schema costs: the name, the description and the arguments document, which is what
675    // goes into the `tools` array. Close enough to the token cost to compare one source to another.
676    let cost = |d: &crate::tools::ToolDescriptor| {
677        d.name.chars().count()
678            + d.description.chars().count()
679            + d.parameters.to_string().chars().count()
680    };
681    let total: usize = offered.iter().map(|d| cost(d)).sum();
682    // Split by loader, biggest first: the reader wants to know which one to defer, not a table.
683    let mut by_source: std::collections::BTreeMap<String, (usize, usize)> =
684        std::collections::BTreeMap::new();
685    for d in &offered {
686        let entry = by_source.entry(d.source.label()).or_insert((0, 0));
687        entry.0 += 1;
688        entry.1 += cost(d);
689    }
690    let mut rows: Vec<(String, usize, usize)> = by_source
691        .into_iter()
692        .map(|(label, (count, chars))| (label, count, chars))
693        .collect();
694    rows.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0)));
695    let split = rows
696        .iter()
697        .map(|(label, count, chars)| format!("{label} {count} tool(s) {chars} chars"))
698        .collect::<Vec<_>>()
699        .join(", ");
700    let deferred = described.iter().filter(|d| d.deferred).count();
701    let line = format!(
702        "{total} chars of schema in every request from {} tool(s) ({split}){}",
703        offered.len(),
704        if deferred == 0 {
705            String::new()
706        } else {
707            format!("; {deferred} more deferred behind `tool_search`")
708        }
709    );
710    // The built-ins are the baseline this build was designed around, so what is measured is what
711    // everything *else* adds: past twenty tools, or past four thousand characters contributed by a
712    // plugin or an MCP server, the cost is somebody's choice and worth a warning. A stock install
713    // is fourteen built-ins and no warning — that is the price of the tools Eclipse is.
714    let builtin_chars = rows
715        .iter()
716        .find(|(label, _, _)| label == "builtin")
717        .map(|(_, _, chars)| *chars)
718        .unwrap_or(0);
719    let heavy = offered.len() > 20 || total.saturating_sub(builtin_chars) > 4_000;
720    // Name the source that costs the most, so the example is about *this* box rather than about
721    // MCP in general — the reader came here because something specific got expensive.
722    let heaviest = rows
723        .iter()
724        .find(|(label, _, _)| label != "builtin")
725        .map(|(label, _, _)| label.clone())
726        .unwrap_or_else(|| "plugin:mcp:*".to_string());
727    let fix = format!(
728        "defer it with `[tools] deferred = [\"{heaviest}\"]` (now: {:?}); a deferred tool stays \
729         callable through `tool_search` then `tool_call`",
730        cfg.tools.deferred
731    );
732    // Under the ceilings the number is still worth printing — it is the answer to "what do my
733    // tools cost?" — but it is a confirmation, not a finding to fix. A `Note` counts as a problem
734    // in the tally, and a healthy install has none.
735    found.push(if heavy {
736        Finding::new(Level::Warn, "tools", line).fix(fix)
737    } else {
738        Finding::ok("tools", line)
739    });
740}
741
742/// `[vision]`: whether the configured mode and routes can handle a picture (`#346`, `#491`).
743///
744/// The shipped default (`mode = "auto"`, no `[vision] route`, no route declaring `vision = true`)
745/// refuses every attach, so `doctor` checks `auto` too instead of leaving the default silent.
746fn check_vision(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
747    use crate::config::VisionMode;
748    let mode = cfg.vision.mode;
749    // Per-route `vision` in config overrides the manifest, and manifests are read from disk to
750    // answer the fallback case. It is a file read per plugin, no process is started.
751    let plugins = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled);
752    let profiles = plugins.provider_profiles();
753    let routes = cfg.declared_routes();
754    let seeing: Vec<String> = routes
755        .iter()
756        .filter(|r| crate::vision::route_sees(&r.config, &profiles))
757        .map(|r| r.name.clone())
758        .collect();
759
760    if mode == VisionMode::Auto {
761        let route = cfg.vision.route.trim();
762        if !route.is_empty() {
763            if let Some(named) = routes.iter().find(|r| r.name == route) {
764                if !crate::vision::route_sees(&named.config, &profiles) {
765                    let profile = named.config.profile.as_deref().unwrap_or("openai");
766                    found.push(
767                        Finding::new(
768                            Level::Warn,
769                            "vision",
770                            format!(
771                                "`vision route = \"{route}\"` (profile `{profile}`) does not \
772                                 declare vision, so a picture sent there would be refused"
773                            ),
774                        )
775                        .fix(format!(
776                            "add `vision = true` under route `{route}` (or in profile \
777                             `{profile}`) if it can see"
778                        )),
779                    );
780                }
781            }
782            return;
783        }
784        if seeing.is_empty() {
785            let route_list = routes
786                .iter()
787                .map(|r| r.name.as_str())
788                .collect::<Vec<_>>()
789                .join(", ");
790            found.push(
791                Finding::new(
792                    Level::Note,
793                    "vision",
794                    format!(
795                        "`[vision] mode = \"auto\"` with no route that declares vision: every \
796                         attach is refused — add `vision = true` under a route that can see (and \
797                         set `[vision] route` if it is not the default). Routes: {route_list}"
798                    ),
799                )
800                .fix(
801                    "add `vision = true` under a route that can see, and set `[vision] route` \
802                     if it is not the default",
803                ),
804            );
805        } else if !routes
806            .first()
807            .is_some_and(|r| crate::vision::route_sees(&r.config, &profiles))
808        {
809            found.push(
810                Finding::new(
811                    Level::Note,
812                    "vision",
813                    format!(
814                        "`[vision] mode = \"auto\"` with no `[vision] route`: the default route \
815                         does not declare vision, so attaches will be refused unless `[vision] \
816                         route` names a seeing route ({})",
817                        seeing.join(", ")
818                    ),
819                )
820                .fix("set `[vision] route` to one of the routes that declares `vision = true`"),
821            );
822        }
823        return;
824    }
825
826    if mode == VisionMode::Native && seeing.is_empty() {
827        found.push(
828            Finding::new(
829                Level::Warn,
830                "vision",
831                format!(
832                    "`[vision] mode = \"native\"` with no route that declares vision: every \
833                     attach is refused. Routes: {}",
834                    routes
835                        .iter()
836                        .map(|r| r.name.as_str())
837                        .collect::<Vec<_>>()
838                        .join(", ")
839                ),
840            )
841            .fix(
842                "add `vision = true` under a route that can see, or set `vision.mode = \"auto\"` \
843                 and name a seeing route in `vision.route`",
844            ),
845        );
846        return;
847    }
848    if mode == VisionMode::Text {
849        let route = cfg.vision.route.trim();
850        if route.is_empty() {
851            found.push(
852                Finding::new(
853                    Level::Warn,
854                    "vision",
855                    "`[vision] mode = \"text\"` with no `vision route`: there is nothing to \
856                     describe a picture, so every attach is refused",
857                )
858                .fix("set `vision route` to a route that declares `vision = true`"),
859            );
860        } else if let Some(named) = routes.iter().find(|r| r.name == route) {
861            if !crate::vision::route_sees(&named.config, &profiles) {
862                let profile = named.config.profile.as_deref().unwrap_or("openai");
863                found.push(
864                    Finding::new(
865                        Level::Warn,
866                        "vision",
867                        format!(
868                            "`vision route = \"{route}\"` (profile `{profile}`) does not declare \
869                             vision, so a picture sent there would be unreadable"
870                        ),
871                    )
872                    .fix(format!(
873                        "add `vision = true` under route `{route}` (or in profile `{profile}`) \
874                         if it can see"
875                    )),
876                );
877            }
878        }
879    }
880}
881
882fn check_shell(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
883    use crate::config::ShellIsolate;
884    let sandbox = crate::sandbox::Sandbox::new(&cfg.tools, &cfg.workspace_root(env), None);
885    match cfg.tools.shell_isolate {
886        ShellIsolate::Off => found.push(Finding::ok(
887            "shell",
888            "shell_isolate = \"off\": commands run uncontained by request",
889        )),
890        ShellIsolate::Process => {
891            if !sandbox.degraded() && !sandbox.refuses() {
892                found.push(Finding::ok(
893                    "shell",
894                    format!("shell_isolate = \"process\" through {}", sandbox.status()),
895                ));
896            } else {
897                found.push(
898                    Finding::new(
899                        Level::Warn,
900                        "shell",
901                        "shell_isolate = \"process\" but bubblewrap is not on PATH: commands run uncontained",
902                    )
903                    .fix("install bubblewrap (apt install bubblewrap), or set [tools] shell_isolate = \"off\" to stop the warning"),
904                );
905            }
906        }
907        ShellIsolate::Fs => {
908            if !sandbox.degraded() && !sandbox.refuses() {
909                found.push(Finding::ok(
910                    "shell",
911                    format!("shell_isolate = \"fs\" through {}", sandbox.status()),
912                ));
913            } else {
914                found.push(
915                    Finding::new(
916                        Level::Problem,
917                        "shell",
918                        "shell_isolate = \"fs\" refuses every command: bubblewrap is not on PATH",
919                    )
920                    .fix("install bubblewrap (apt install bubblewrap), or set [tools] shell_isolate = \"process\""),
921                );
922            }
923        }
924    }
925}
926
927#[cfg(test)]
928mod tests {
929    use super::*;
930
931    fn env_of(home: &std::path::Path) -> impl Fn(&str) -> Option<String> {
932        let home = home.display().to_string();
933        move |k: &str| (k == "HOME").then(|| home.clone())
934    }
935
936    fn temp() -> (tempfile::TempDir, impl Fn(&str) -> Option<String>) {
937        let dir = tempfile::tempdir().unwrap();
938        let env = env_of(dir.path());
939        (dir, env)
940    }
941
942    fn areas<'a>(findings: &'a [Finding], area: &str) -> Vec<&'a Finding> {
943        findings.iter().filter(|f| f.area == area).collect()
944    }
945
946    /// #346: `native` is a promise that the turn's model can see. A config that makes it and has
947    /// no route declaring vision refuses every attach, and `doctor` is where that is found before
948    /// somebody attaches a screenshot at 1am.
949    #[test]
950    fn native_with_no_route_that_declares_vision_is_reported_and_says_what_to_change() {
951        let (dir, env) = temp();
952        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
953        let cfg = Config::from_toml_str(
954            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
955             [vision]\nmode = \"native\"\n",
956        )
957        .unwrap();
958        let findings = check(&cfg, &env);
959        let found = areas(&findings, "vision")
960            .into_iter()
961            .find(|f| f.level == Level::Warn)
962            .expect("a warn");
963        assert!(found.detail.contains("native"), "{}", found.detail);
964        let fix = found.fix.as_deref().expect("a fix");
965        assert!(fix.contains("auto"), "{fix}");
966    }
967
968    #[test]
969    fn text_without_a_route_is_reported() {
970        let (dir, env) = temp();
971        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
972        let cfg = Config::from_toml_str(
973            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
974             [vision]\nmode = \"text\"\n",
975        )
976        .unwrap();
977        let findings = check(&cfg, &env);
978        let found = areas(&findings, "vision")
979            .into_iter()
980            .find(|f| f.level == Level::Warn)
981            .expect("a warn");
982        assert!(found.detail.contains("vision route"), "{}", found.detail);
983    }
984
985    /// `#491`: the shipped default (`mode = "auto"`, no route, nothing declares vision) refuses
986    /// every attach, so `doctor` must report a vision finding instead of staying silent.
987    #[test]
988    fn auto_reports_when_no_route_declares_vision() {
989        let (dir, env) = temp();
990        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
991        let cfg = Config::from_toml_str(
992            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n",
993        )
994        .unwrap();
995        let findings = check(&cfg, &env);
996        let vision = areas(&findings, "vision");
997        assert_eq!(vision.len(), 1, "{findings:?}");
998        assert!(
999            vision[0].detail.contains("no route that declares vision"),
1000            "{}",
1001            vision[0].detail
1002        );
1003        assert!(
1004            vision[0].detail.contains("vision = true"),
1005            "{}",
1006            vision[0].detail
1007        );
1008
1009        // Once a route declares `vision = true` (or `[vision] route` points to one), `auto` is quiet.
1010        let seeing_default = Config::from_toml_str(
1011            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\nvision = true\n",
1012        )
1013        .unwrap();
1014        assert!(areas(&check(&seeing_default, &env), "vision").is_empty());
1015
1016        let blind_route = Config::from_toml_str(
1017            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
1018             [[provider.route]]\nname = \"aux\"\nbase_url = \"http://127.0.0.1:2/v1\"\nmodel = \"v\"\nprofile = \"llamacpp\"\n\
1019             [vision]\nmode = \"auto\"\nroute = \"aux\"\n",
1020        )
1021        .unwrap();
1022        let findings = check(&blind_route, &env);
1023        let found = areas(&findings, "vision")
1024            .into_iter()
1025            .find(|f| f.level == Level::Warn)
1026            .expect("blind describe route warns in auto mode");
1027        assert!(found.detail.contains("aux"), "{}", found.detail);
1028        assert!(found.detail.contains("llamacpp"), "{}", found.detail);
1029        assert!(
1030            found.fix.as_deref().unwrap_or("").contains("vision = true"),
1031            "{:?}",
1032            found.fix
1033        );
1034    }
1035
1036    /// #327: the sentence used to read "is held by pid X, which is not running", which sounds like a
1037    /// liveness check. Nothing checks liveness — the decision is `flock`, which the kernel answers
1038    /// for the whole machine — and a model reading the old wording inside the `shell` sandbox (whose
1039    /// PID namespace hides every host process) concluded the warnings were false positives and wrote
1040    /// that into `MEMORY.md`. The wording has to name the check that was actually made.
1041    #[test]
1042    fn a_stale_lock_names_the_check_that_was_made_and_not_a_liveness_test() {
1043        let (dir, env) = temp();
1044        let sessions = dir.path().join(".eclipse/state/sessions");
1045        std::fs::create_dir_all(&sessions).unwrap();
1046        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1047        let lock = sessions.join("1796000000000-4242-0.lock");
1048        std::fs::write(&lock, "4242\n").unwrap();
1049        // The session is in the store, so this lock is a finished session's leftover and not an
1050        // orphan: the report says so, at the level that says "nothing is wrong".
1051        crate::session::SessionStore::new(sessions.clone())
1052            .append(
1053                "1796000000000-4242-0",
1054                &crate::message::Message::user("hello"),
1055            )
1056            .unwrap();
1057
1058        let findings = check(&Config::default(), &env);
1059        let stale = areas(&findings, "sessions")
1060            .into_iter()
1061            .find(|f| f.detail.contains("no holder"))
1062            .expect("the unheld lock is counted");
1063        assert_eq!(stale.level, Level::Note, "{}", stale.detail);
1064        assert!(
1065            stale.detail.contains("flock"),
1066            "the sentence names the check it made: {}",
1067            stale.detail
1068        );
1069        assert!(
1070            !stale.detail.contains("which is not running"),
1071            "and never implies a liveness test: {}",
1072            stale.detail
1073        );
1074        assert!(
1075            stale
1076                .detail
1077                .contains("normal for sessions that are not running"),
1078            "it says the state is the ordinary one: {}",
1079            stale.detail
1080        );
1081    }
1082
1083    /// `#497`: every session ever run leaves a lock file, so a per-file finding made the report a
1084    /// list of the box's history — 348 warnings on one install, of which 30 were shown. One box
1085    /// gets one line, whatever the pile is.
1086    #[test]
1087    fn a_pile_of_finished_sessions_is_one_finding_about_locks() {
1088        let (dir, env) = temp();
1089        let sessions = dir.path().join(".eclipse/state/sessions");
1090        std::fs::create_dir_all(&sessions).unwrap();
1091        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1092        let store = crate::session::SessionStore::new(sessions.clone());
1093        for i in 0..40u32 {
1094            let id = format!("17960000000{i:02}-4400-0");
1095            store
1096                .append(&id, &crate::message::Message::user("hi"))
1097                .unwrap();
1098            std::fs::write(
1099                sessions.join(format!("{id}.lock")),
1100                format!("{}\n", 4400 + i),
1101            )
1102            .unwrap();
1103        }
1104
1105        let findings = check(&Config::default(), &env);
1106        let about_locks: Vec<&Finding> = areas(&findings, "sessions")
1107            .into_iter()
1108            .filter(|f| f.detail.contains("lock"))
1109            .collect();
1110        assert_eq!(
1111            about_locks.len(),
1112            1,
1113            "one line for the whole pile: {about_locks:#?}"
1114        );
1115        assert!(
1116            about_locks[0].detail.contains("40"),
1117            "{}",
1118            about_locks[0].detail
1119        );
1120        assert_eq!(about_locks[0].level, Level::Note);
1121        // And the repair is the pile, not one file: `--fix` has to be able to clear what was
1122        // counted, or the next run reports the same 40.
1123        match about_locks[0].repair {
1124            Some(Repair::ClearLocks(ref paths)) => assert_eq!(paths.len(), 40),
1125            ref other => panic!("expected a ClearLocks repair, got {other:?}"),
1126        }
1127    }
1128
1129    /// A lock that names no session this store has is the case worth a warning: nothing will ever
1130    /// resume it and nothing removes it.
1131    #[test]
1132    fn a_lock_with_no_session_behind_it_warns() {
1133        let (dir, env) = temp();
1134        let sessions = dir.path().join(".eclipse/state/sessions");
1135        std::fs::create_dir_all(&sessions).unwrap();
1136        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1137        std::fs::write(sessions.join("1796000000009-9090-0.lock"), "9090\n").unwrap();
1138
1139        let findings = check(&Config::default(), &env);
1140        let orphan = areas(&findings, "sessions")
1141            .into_iter()
1142            .find(|f| f.detail.contains("no holder"))
1143            .expect("the lock is counted");
1144        assert_eq!(orphan.level, Level::Warn, "{}", orphan.detail);
1145        assert!(
1146            orphan.detail.contains("1796000000009-9090-0"),
1147            "it names the session nothing has: {}",
1148            orphan.detail
1149        );
1150    }
1151
1152    /// The other half, and the one that proves the check is not pid-based: a lock this very process
1153    /// holds is a session in use, never a leftover, however invisible the holder is to `ps`.
1154    #[test]
1155    fn a_lock_a_run_holds_is_reported_as_in_use_and_never_as_stale() {
1156        let (dir, env) = temp();
1157        let sessions = dir.path().join(".eclipse/state/sessions");
1158        std::fs::create_dir_all(&sessions).unwrap();
1159        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1160        let held = sessions.join("1796000000001-4243-0.lock");
1161        let file = std::fs::OpenOptions::new()
1162            .create(true)
1163            .read(true)
1164            .write(true)
1165            .truncate(false)
1166            .open(&held)
1167            .unwrap();
1168        {
1169            use std::os::unix::io::AsRawFd;
1170            // SAFETY: `file` owns a valid descriptor for the duration of the call.
1171            let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) };
1172            assert_eq!(
1173                rc,
1174                0,
1175                "taking the lock: {}",
1176                std::io::Error::last_os_error()
1177            );
1178        }
1179        std::fs::write(&held, "4243\n").unwrap();
1180
1181        let findings = check(&Config::default(), &env);
1182        assert!(
1183            !areas(&findings, "sessions")
1184                .iter()
1185                .any(|f| f.detail.contains("no holder")
1186                    || f.detail.contains("1796000000001-4243-0.lock")),
1187            "a lock this process holds is not stale: {findings:#?}"
1188        );
1189        let in_use = areas(&findings, "sessions")
1190            .into_iter()
1191            .find(|f| f.detail.contains("in use right now"))
1192            .expect("a held lock is a session in use");
1193        assert_eq!(in_use.level, Level::Warn);
1194        assert!(
1195            in_use.detail.contains("1796000000001-4243-0"),
1196            "{}",
1197            in_use.detail
1198        );
1199        drop(file);
1200    }
1201
1202    #[test]
1203    fn a_healthy_install_has_nothing_to_report() {
1204        let (dir, env) = temp();
1205        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1206        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
1207        let cfg = Config::default();
1208        let findings = check(&cfg, &env);
1209        let tally = Tally::of(&findings);
1210        assert_eq!(tally.problems, 0, "{findings:#?}");
1211        // The one finding that depends on the machine rather than the install: a host without
1212        // bubblewrap really does run commands uncontained, and the doctor is right to say so. The
1213        // test holds the install to what a healthy *install* controls.
1214        let elsewhere: Vec<&Finding> = findings
1215            .iter()
1216            .filter(|f| f.area != "shell" && f.level >= Level::Warn)
1217            .collect();
1218        assert!(elsewhere.is_empty(), "{elsewhere:#?}");
1219        if tally.warnings == 0 {
1220            assert!(tally.summary().contains("nothing to fix"));
1221        }
1222    }
1223
1224    /// `#266`: the three states of the dashboard's sign-in, and the one that must not be silent.
1225    /// A doctor that said nothing about a token install would leave every existing dashboard on
1226    /// the shared string forever, with nothing to notice.
1227    #[test]
1228    fn the_dashboard_sign_in_is_reported_and_a_broken_hash_is_a_problem() {
1229        let (dir, env) = temp();
1230        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1231        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
1232
1233        // No dashboard at all: no `web` line, not even an `ok` one.
1234        let quiet = check(&Config::default(), &env);
1235        assert!(areas(&quiet, "web").is_empty(), "{quiet:#?}");
1236
1237        // A dashboard on the token: a note that names the verb which ends it.
1238        let mut cfg = Config::default();
1239        cfg.web.auth_token = Some("t".repeat(64));
1240        let token_only = check(&cfg, &env);
1241        let web = areas(&token_only, "web");
1242        assert_eq!(web.len(), 1, "{token_only:#?}");
1243        // `Warn`, because that is the first level at which `doctor` prints a `fix:` line: advice
1244        // nobody is shown is not advice.
1245        assert_eq!(web[0].level, Level::Warn);
1246        assert!(web[0].detail.contains("web.auth_token"), "{:?}", web[0]);
1247        assert!(
1248            web[0]
1249                .fix
1250                .as_deref()
1251                .unwrap_or_default()
1252                .contains("eclipse web passwd"),
1253            "{:?}",
1254            web[0]
1255        );
1256
1257        // A password set: an `ok` line, and it names the user.
1258        let hash = crate::auth::hash_password("open sesame").unwrap();
1259        std::fs::write(
1260            dir.path().join(".env"),
1261            format!("ECLIPSE_WEB_USER=max\nECLIPSE_WEB_PASSWORD_HASH={hash}\n"),
1262        )
1263        .unwrap();
1264        let mut cfg = cfg.clone();
1265        cfg.dotenv
1266            .values
1267            .insert("ECLIPSE_WEB_USER".into(), "max".into());
1268        cfg.dotenv
1269            .values
1270            .insert("ECLIPSE_WEB_PASSWORD_HASH".into(), hash);
1271        let signed_in = check(&cfg, &env);
1272        let web = areas(&signed_in, "web");
1273        assert_eq!(web.len(), 1, "{signed_in:#?}");
1274        assert_eq!(web[0].level, Level::Ok);
1275        assert!(web[0].detail.contains("max"), "{:?}", web[0]);
1276
1277        // A hash this build cannot read stops the dashboard starting, so it is a problem, and the
1278        // parser's own words are the detail.
1279        cfg.dotenv.values.insert(
1280            "ECLIPSE_WEB_PASSWORD_HASH".into(),
1281            "argon2id$600000$aabb$ccdd".into(),
1282        );
1283        let broken = check(&cfg, &env);
1284        let web = areas(&broken, "web");
1285        assert_eq!(web.len(), 1, "{broken:#?}");
1286        assert_eq!(web[0].level, Level::Problem);
1287        assert!(web[0].detail.contains("unknown scheme"), "{:?}", web[0]);
1288    }
1289
1290    #[test]
1291    fn a_missing_session_directory_is_offered_as_a_repair() {
1292        let (dir, env) = temp();
1293        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
1294        let findings = check(&Config::default(), &env);
1295        let layout: Vec<&Finding> = areas(&findings, "layout");
1296        let sessions = layout.iter().find_map(|f| match &f.repair {
1297            Some(Repair::MakeDir(p)) if p.ends_with("sessions") => Some(p.clone()),
1298            _ => None,
1299        });
1300        let path =
1301            sessions.unwrap_or_else(|| panic!("no MakeDir for sessions offered: {layout:#?}"));
1302        std::fs::create_dir_all(&path).unwrap();
1303        assert!(path.is_dir());
1304        // And the second run is quiet about it.
1305        let again = check(&Config::default(), &env);
1306        assert!(!areas(&again, "layout")
1307            .iter()
1308            .any(|f| f.level >= Level::Warn && f.detail.contains("does not exist")));
1309    }
1310
1311    #[cfg(unix)]
1312    #[test]
1313    fn a_world_readable_dotenv_is_a_warning_with_a_chmod_repair() {
1314        use std::os::unix::fs::PermissionsExt;
1315        let (dir, env) = temp();
1316        let cfg_dir = dir.path().join(".eclipse");
1317        std::fs::create_dir_all(&cfg_dir).unwrap();
1318        let dotenv = cfg_dir.join(".env");
1319        std::fs::write(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN=secret\n").unwrap();
1320        std::fs::set_permissions(&dotenv, std::fs::Permissions::from_mode(0o644)).unwrap();
1321
1322        let findings = check(&Config::default(), &env);
1323        let perms: Vec<&Finding> = areas(&findings, "permissions");
1324        let bad = perms
1325            .iter()
1326            .find(|f| f.level == Level::Warn)
1327            .unwrap_or_else(|| panic!("no warning: {perms:#?}"));
1328        assert!(bad.detail.contains(".env"), "{:?}", bad.detail);
1329        assert!(matches!(bad.repair, Some(Repair::Chmod(_, 0o600))));
1330        assert!(bad
1331            .fix
1332            .as_deref()
1333            .unwrap_or_default()
1334            .starts_with("chmod 600"));
1335    }
1336
1337    #[test]
1338    fn a_plugin_named_but_missing_is_a_problem_with_a_repair() {
1339        let (dir, env) = temp();
1340        std::fs::create_dir_all(dir.path().join(".eclipse/plugins")).unwrap();
1341        let mut cfg = Config::default();
1342        cfg.plugins.enabled = vec!["gone".into()];
1343        let findings = check(&cfg, &env);
1344        let plugins: Vec<&Finding> = areas(&findings, "plugins");
1345        let problem = plugins
1346            .iter()
1347            .find(|f| f.level == Level::Problem)
1348            .unwrap_or_else(|| panic!("no problem: {plugins:#?}"));
1349        assert!(problem.detail.contains("gone"), "{:?}", problem.detail);
1350        assert_eq!(problem.repair, Some(Repair::DisablePlugin("gone".into())));
1351    }
1352
1353    #[test]
1354    fn a_broken_skill_is_named_and_not_touched() {
1355        let (dir, env) = temp();
1356        let skills = dir.path().join(".eclipse/skills/broken");
1357        std::fs::create_dir_all(&skills).unwrap();
1358        std::fs::write(
1359            skills.join("SKILL.md"),
1360            "---\ndescription: no name\n---\nbody\n",
1361        )
1362        .unwrap();
1363        let findings = check(&Config::default(), &env);
1364        let named: Vec<&Finding> = areas(&findings, "skills")
1365            .into_iter()
1366            .filter(|f| f.level == Level::Warn)
1367            .collect();
1368        assert!(!named.is_empty(), "{findings:#?}");
1369        assert!(
1370            named.iter().all(|f| f.repair.is_none()),
1371            "a skill has no disabled list to repair into: {named:#?}"
1372        );
1373    }
1374
1375    /// `#350`: an index that cannot fit every skill is a finding, not a stderr line only a
1376    /// terminal user ever sees. It names the count and the knob, and it is repairable by
1377    /// definition — the fix is the setting.
1378    #[test]
1379    fn an_index_that_cannot_fit_every_skill_names_the_count_and_the_knob() {
1380        let (dir, env) = temp();
1381        for name in ["alpha", "beta", "gamma"] {
1382            let dir = dir.path().join(format!(".eclipse/skills/{name}"));
1383            std::fs::create_dir_all(&dir).unwrap();
1384            std::fs::write(
1385                dir.join("SKILL.md"),
1386                format!(
1387                    "---\nname: {name}\ndescription: {}\n---\nbody\n",
1388                    "x".repeat(120)
1389                ),
1390            )
1391            .unwrap();
1392        }
1393        let mut cfg = Config::default();
1394        cfg.skills.index_budget_chars = 120;
1395        let findings = check(&cfg, &env);
1396        let warn = areas(&findings, "skills")
1397            .into_iter()
1398            .find(|f| f.level == Level::Warn && f.detail.contains("index fits"))
1399            .unwrap_or_else(|| panic!("{findings:#?}"));
1400        assert!(warn.detail.contains("of 3 skill(s)"), "{}", warn.detail);
1401        assert!(
1402            warn.fix
1403                .as_deref()
1404                .unwrap_or("")
1405                .contains("index_budget_chars"),
1406            "{warn:#?}"
1407        );
1408
1409        // With room for all three, no finding: the check is about a truncation, not about skills.
1410        let mut roomy = Config::default();
1411        roomy.skills.index_budget_chars = 0;
1412        let findings = check(&roomy, &env);
1413        assert!(
1414            !areas(&findings, "skills")
1415                .into_iter()
1416                .any(|f| f.detail.contains("index fits")),
1417            "{findings:#?}"
1418        );
1419    }
1420
1421    /// #225: the registry says `running` and the process is gone. That is the one state `/tasks`
1422    /// cannot correct by itself, so `doctor` names it — and offers to forget the entry, not the
1423    /// transcript.
1424    #[test]
1425    fn a_background_task_whose_process_died_is_a_warning_a_person_can_clear() {
1426        let (dir, env) = temp();
1427        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
1428        let registry = crate::tasks::Registry::new(dir.path().join(".eclipse/state"));
1429        let mut child = std::process::Command::new("true").spawn().expect("spawn");
1430        let pid = child.id();
1431        child.wait().expect("reap");
1432        let mut gone = crate::tasks::Task::spawned("1700000000000-4242-0", pid, "summarise");
1433        gone.state = crate::tasks::State::Running;
1434        registry.write(&gone).unwrap();
1435
1436        let findings = check(&Config::default(), &env);
1437        let tasks: Vec<&Finding> = areas(&findings, "tasks");
1438        let warned = tasks
1439            .iter()
1440            .find(|f| f.level == Level::Warn)
1441            .unwrap_or_else(|| panic!("no warning about the dead task: {tasks:#?}"));
1442        assert!(
1443            warned.detail.contains("1700000000000-4242-0") && warned.detail.contains("died"),
1444            "{:?}",
1445            warned.detail
1446        );
1447        assert_eq!(
1448            warned.repair,
1449            Some(Repair::ForgetTask(registry.path("1700000000000-4242-0")))
1450        );
1451        assert!(
1452            warned
1453                .fix
1454                .as_deref()
1455                .unwrap_or_default()
1456                .contains("eclipse sessions"),
1457            "the transcript stays: {:?}",
1458            warned.fix
1459        );
1460    }
1461
1462    #[test]
1463    fn a_task_still_running_is_reported_as_healthy_and_no_task_at_all_is_silent() {
1464        let (dir, env) = temp();
1465        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
1466        let quiet = check(&Config::default(), &env);
1467        assert!(
1468            areas(&quiet, "tasks").is_empty(),
1469            "nothing was ever started, so there is nothing to say"
1470        );
1471
1472        let registry = crate::tasks::Registry::new(dir.path().join(".eclipse/state"));
1473        let mut live = crate::tasks::Task::begun("1700000000001-4243-0", "count the files");
1474        live.pid = std::process::id();
1475        live.pid_since = None;
1476        registry.write(&live).unwrap();
1477        let findings = check(&Config::default(), &env);
1478        let tasks = areas(&findings, "tasks");
1479        assert_eq!(tasks.len(), 1, "{tasks:#?}");
1480        assert_eq!(tasks[0].level, Level::Ok, "{tasks:#?}");
1481        assert!(tasks[0].detail.contains("1 background task(s) running"));
1482    }
1483
1484    #[test]
1485    fn the_summary_counts_what_a_person_has_to_decide() {
1486        let findings = vec![
1487            Finding::ok("a", "fine"),
1488            Finding::new(Level::Warn, "b", "meh"),
1489            Finding::new(Level::Problem, "c", "broken").repair(Repair::MakeDir("/tmp/x".into())),
1490        ];
1491        let tally = Tally::of(&findings);
1492        assert_eq!(
1493            (tally.problems, tally.warnings, tally.repairable),
1494            (1, 1, 1)
1495        );
1496        assert_eq!(tally.summary(), "1 problem(s), 1 warning(s)");
1497    }
1498}