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 all 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    // `#552`: a hide the run cannot apply is the difference between a file withheld and a file
927    // readable inside the sandbox, and nothing used to say which. Only `fs` hides anything, so
928    // only `fs` is asked — in the other modes the list is inert by design, not by mistake.
929    //
930    // A path the build *suggests* and this machine happens not to have is not a finding: `~/.aws`
931    // is absent on a great many hosts, and a warning nobody can act on is how a check stops being
932    // read.
933    if cfg.tools.shell_isolate == ShellIsolate::Fs {
934        let unapplied: Vec<String> = sandbox
935            .skipped_hides()
936            .into_iter()
937            .filter(|(path, why)| {
938                !(*why == crate::sandbox::HideSkip::Missing && sandbox.is_suggested_hide(path))
939            })
940            .map(|(path, why)| format!("{} ({})", path.display(), why.why()))
941            .collect();
942        if !unapplied.is_empty() {
943            found.push(
944                Finding::new(
945                    Level::Warn,
946                    "shell",
947                    format!("shell_isolate_hide is not hiding {}", unapplied.join(", ")),
948                )
949                .fix(
950                    "correct the path, or drop the entry: a hide that is not applied leaves that \
951                     file readable inside the sandbox",
952                ),
953            );
954        }
955    }
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961
962    fn env_of(home: &std::path::Path) -> impl Fn(&str) -> Option<String> {
963        let home = home.display().to_string();
964        move |k: &str| (k == "HOME").then(|| home.clone())
965    }
966
967    fn temp() -> (tempfile::TempDir, impl Fn(&str) -> Option<String>) {
968        let dir = tempfile::tempdir().unwrap();
969        let env = env_of(dir.path());
970        (dir, env)
971    }
972
973    fn areas<'a>(findings: &'a [Finding], area: &str) -> Vec<&'a Finding> {
974        findings.iter().filter(|f| f.area == area).collect()
975    }
976
977    /// #346: `native` is a promise that the turn's model can see. A config that makes it and has
978    /// no route declaring vision refuses every attach, and `doctor` is where that is found before
979    /// somebody attaches a screenshot at 1am.
980    #[test]
981    fn native_with_no_route_that_declares_vision_is_reported_and_says_what_to_change() {
982        let (dir, env) = temp();
983        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
984        let cfg = Config::from_toml_str(
985            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
986             [vision]\nmode = \"native\"\n",
987        )
988        .unwrap();
989        let findings = check(&cfg, &env);
990        let found = areas(&findings, "vision")
991            .into_iter()
992            .find(|f| f.level == Level::Warn)
993            .expect("a warn");
994        assert!(found.detail.contains("native"), "{}", found.detail);
995        let fix = found.fix.as_deref().expect("a fix");
996        assert!(fix.contains("auto"), "{fix}");
997    }
998
999    #[test]
1000    fn text_without_a_route_is_reported() {
1001        let (dir, env) = temp();
1002        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1003        let cfg = Config::from_toml_str(
1004            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
1005             [vision]\nmode = \"text\"\n",
1006        )
1007        .unwrap();
1008        let findings = check(&cfg, &env);
1009        let found = areas(&findings, "vision")
1010            .into_iter()
1011            .find(|f| f.level == Level::Warn)
1012            .expect("a warn");
1013        assert!(found.detail.contains("vision route"), "{}", found.detail);
1014    }
1015
1016    /// `#491`: the shipped default (`mode = "auto"`, no route, nothing declares vision) refuses
1017    /// every attach, so `doctor` must report a vision finding instead of staying silent.
1018    #[test]
1019    fn auto_reports_when_no_route_declares_vision() {
1020        let (dir, env) = temp();
1021        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1022        let cfg = Config::from_toml_str(
1023            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n",
1024        )
1025        .unwrap();
1026        let findings = check(&cfg, &env);
1027        let vision = areas(&findings, "vision");
1028        assert_eq!(vision.len(), 1, "{findings:?}");
1029        assert!(
1030            vision[0].detail.contains("no route that declares vision"),
1031            "{}",
1032            vision[0].detail
1033        );
1034        assert!(
1035            vision[0].detail.contains("vision = true"),
1036            "{}",
1037            vision[0].detail
1038        );
1039
1040        // Once a route declares `vision = true` (or `[vision] route` points to one), `auto` is quiet.
1041        let seeing_default = Config::from_toml_str(
1042            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\nvision = true\n",
1043        )
1044        .unwrap();
1045        assert!(areas(&check(&seeing_default, &env), "vision").is_empty());
1046
1047        let blind_route = Config::from_toml_str(
1048            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
1049             [[provider.route]]\nname = \"aux\"\nbase_url = \"http://127.0.0.1:2/v1\"\nmodel = \"v\"\nprofile = \"llamacpp\"\n\
1050             [vision]\nmode = \"auto\"\nroute = \"aux\"\n",
1051        )
1052        .unwrap();
1053        let findings = check(&blind_route, &env);
1054        let found = areas(&findings, "vision")
1055            .into_iter()
1056            .find(|f| f.level == Level::Warn)
1057            .expect("blind describe route warns in auto mode");
1058        assert!(found.detail.contains("aux"), "{}", found.detail);
1059        assert!(found.detail.contains("llamacpp"), "{}", found.detail);
1060        assert!(
1061            found.fix.as_deref().unwrap_or("").contains("vision = true"),
1062            "{:?}",
1063            found.fix
1064        );
1065    }
1066
1067    /// #327: the sentence used to read "is held by pid X, which is not running", which sounds like a
1068    /// liveness check. Nothing checks liveness — the decision is `flock`, which the kernel answers
1069    /// for the whole machine — and a model reading the old wording inside the `shell` sandbox (whose
1070    /// PID namespace hides every host process) concluded the warnings were false positives and wrote
1071    /// that into `MEMORY.md`. The wording has to name the check that was actually made.
1072    #[test]
1073    fn a_stale_lock_names_the_check_that_was_made_and_not_a_liveness_test() {
1074        let (dir, env) = temp();
1075        let sessions = dir.path().join(".eclipse/state/sessions");
1076        std::fs::create_dir_all(&sessions).unwrap();
1077        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1078        let lock = sessions.join("1796000000000-4242-0.lock");
1079        std::fs::write(&lock, "4242\n").unwrap();
1080        // The session is in the store, so this lock is a finished session's leftover and not an
1081        // orphan: the report says so, at the level that says "nothing is wrong".
1082        crate::session::SessionStore::new(sessions.clone())
1083            .append(
1084                "1796000000000-4242-0",
1085                &crate::message::Message::user("hello"),
1086            )
1087            .unwrap();
1088
1089        let findings = check(&Config::default(), &env);
1090        let stale = areas(&findings, "sessions")
1091            .into_iter()
1092            .find(|f| f.detail.contains("no holder"))
1093            .expect("the unheld lock is counted");
1094        assert_eq!(stale.level, Level::Note, "{}", stale.detail);
1095        assert!(
1096            stale.detail.contains("flock"),
1097            "the sentence names the check it made: {}",
1098            stale.detail
1099        );
1100        assert!(
1101            !stale.detail.contains("which is not running"),
1102            "and never implies a liveness test: {}",
1103            stale.detail
1104        );
1105        assert!(
1106            stale
1107                .detail
1108                .contains("normal for sessions that are not running"),
1109            "it says the state is the ordinary one: {}",
1110            stale.detail
1111        );
1112    }
1113
1114    /// `#497`: every session ever run leaves a lock file, so a per-file finding made the report a
1115    /// list of the box's history — 348 warnings on one install, of which 30 were shown. One box
1116    /// gets one line, whatever the pile is.
1117    #[test]
1118    fn a_pile_of_finished_sessions_is_one_finding_about_locks() {
1119        let (dir, env) = temp();
1120        let sessions = dir.path().join(".eclipse/state/sessions");
1121        std::fs::create_dir_all(&sessions).unwrap();
1122        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1123        let store = crate::session::SessionStore::new(sessions.clone());
1124        for i in 0..40u32 {
1125            let id = format!("17960000000{i:02}-4400-0");
1126            store
1127                .append(&id, &crate::message::Message::user("hi"))
1128                .unwrap();
1129            std::fs::write(
1130                sessions.join(format!("{id}.lock")),
1131                format!("{}\n", 4400 + i),
1132            )
1133            .unwrap();
1134        }
1135
1136        let findings = check(&Config::default(), &env);
1137        let about_locks: Vec<&Finding> = areas(&findings, "sessions")
1138            .into_iter()
1139            .filter(|f| f.detail.contains("lock"))
1140            .collect();
1141        assert_eq!(
1142            about_locks.len(),
1143            1,
1144            "one line for the whole pile: {about_locks:#?}"
1145        );
1146        assert!(
1147            about_locks[0].detail.contains("40"),
1148            "{}",
1149            about_locks[0].detail
1150        );
1151        assert_eq!(about_locks[0].level, Level::Note);
1152        // And the repair is the pile, not one file: `--fix` has to be able to clear what was
1153        // counted, or the next run reports the same 40.
1154        match about_locks[0].repair {
1155            Some(Repair::ClearLocks(ref paths)) => assert_eq!(paths.len(), 40),
1156            ref other => panic!("expected a ClearLocks repair, got {other:?}"),
1157        }
1158    }
1159
1160    /// A lock that names no session this store has is the case worth a warning: nothing will ever
1161    /// resume it and nothing removes it.
1162    #[test]
1163    fn a_lock_with_no_session_behind_it_warns() {
1164        let (dir, env) = temp();
1165        let sessions = dir.path().join(".eclipse/state/sessions");
1166        std::fs::create_dir_all(&sessions).unwrap();
1167        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1168        std::fs::write(sessions.join("1796000000009-9090-0.lock"), "9090\n").unwrap();
1169
1170        let findings = check(&Config::default(), &env);
1171        let orphan = areas(&findings, "sessions")
1172            .into_iter()
1173            .find(|f| f.detail.contains("no holder"))
1174            .expect("the lock is counted");
1175        assert_eq!(orphan.level, Level::Warn, "{}", orphan.detail);
1176        assert!(
1177            orphan.detail.contains("1796000000009-9090-0"),
1178            "it names the session nothing has: {}",
1179            orphan.detail
1180        );
1181    }
1182
1183    /// The other half, and the one that proves the check is not pid-based: a lock this very process
1184    /// holds is a session in use, never a leftover, however invisible the holder is to `ps`.
1185    #[test]
1186    fn a_lock_a_run_holds_is_reported_as_in_use_and_never_as_stale() {
1187        let (dir, env) = temp();
1188        let sessions = dir.path().join(".eclipse/state/sessions");
1189        std::fs::create_dir_all(&sessions).unwrap();
1190        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1191        let held = sessions.join("1796000000001-4243-0.lock");
1192        let file = std::fs::OpenOptions::new()
1193            .create(true)
1194            .read(true)
1195            .write(true)
1196            .truncate(false)
1197            .open(&held)
1198            .unwrap();
1199        {
1200            use std::os::unix::io::AsRawFd;
1201            // SAFETY: `file` owns a valid descriptor for the duration of the call.
1202            let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) };
1203            assert_eq!(
1204                rc,
1205                0,
1206                "taking the lock: {}",
1207                std::io::Error::last_os_error()
1208            );
1209        }
1210        std::fs::write(&held, "4243\n").unwrap();
1211
1212        let findings = check(&Config::default(), &env);
1213        assert!(
1214            !areas(&findings, "sessions")
1215                .iter()
1216                .any(|f| f.detail.contains("no holder")
1217                    || f.detail.contains("1796000000001-4243-0.lock")),
1218            "a lock this process holds is not stale: {findings:#?}"
1219        );
1220        let in_use = areas(&findings, "sessions")
1221            .into_iter()
1222            .find(|f| f.detail.contains("in use right now"))
1223            .expect("a held lock is a session in use");
1224        assert_eq!(in_use.level, Level::Warn);
1225        assert!(
1226            in_use.detail.contains("1796000000001-4243-0"),
1227            "{}",
1228            in_use.detail
1229        );
1230        drop(file);
1231    }
1232
1233    #[test]
1234    fn a_healthy_install_has_nothing_to_report() {
1235        let (dir, env) = temp();
1236        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1237        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
1238        let cfg = Config::default();
1239        let findings = check(&cfg, &env);
1240        let tally = Tally::of(&findings);
1241        assert_eq!(tally.problems, 0, "{findings:#?}");
1242        // The one finding that depends on the machine rather than the install: a host without
1243        // bubblewrap really does run commands uncontained, and the doctor is right to say so. The
1244        // test holds the install to what a healthy *install* controls.
1245        let elsewhere: Vec<&Finding> = findings
1246            .iter()
1247            .filter(|f| f.area != "shell" && f.level >= Level::Warn)
1248            .collect();
1249        assert!(elsewhere.is_empty(), "{elsewhere:#?}");
1250        if tally.warnings == 0 {
1251            assert!(tally.summary().contains("nothing to fix"));
1252        }
1253    }
1254
1255    /// `#552`: a hide the mode cannot apply is the difference between a file withheld and a file
1256    /// readable inside the sandbox. The shell line mentions it in passing; the check names it,
1257    /// because that is the question `config check` was opened to answer.
1258    #[test]
1259    fn a_hide_that_cannot_be_applied_is_named_with_its_reason() {
1260        let (dir, env) = temp();
1261        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1262        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
1263        let mut cfg = Config::default();
1264        cfg.tools.shell_isolate = crate::config::ShellIsolate::Fs;
1265        cfg.tools.shell_isolate_hide = vec![dir.path().join(".netrcc")];
1266        let findings = check(&cfg, &env);
1267        let warned = areas(&findings, "shell")
1268            .into_iter()
1269            .find(|f| f.detail.contains("shell_isolate_hide"))
1270            .unwrap_or_else(|| panic!("{findings:#?}"));
1271        assert_eq!(warned.level, Level::Warn);
1272        assert!(warned.detail.contains(".netrcc"), "{:?}", warned.detail);
1273        assert!(
1274            warned.detail.contains("no such path"),
1275            "{:?}",
1276            warned.detail
1277        );
1278    }
1279
1280    /// The suggestion the build makes and a machine without `~/.aws` is not a finding: a warning
1281    /// nobody can act on is how a check stops being read.
1282    #[test]
1283    fn a_suggested_hide_that_this_machine_does_not_have_is_not_a_finding() {
1284        let (dir, env) = temp();
1285        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1286        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
1287        let mut cfg = Config::default();
1288        cfg.tools.shell_isolate = crate::config::ShellIsolate::Fs;
1289        // Every default, none of them created in the fake home.
1290        cfg.tools.shell_isolate_hide = crate::config::default_hidden_paths();
1291        let findings = check(&cfg, &env);
1292        assert!(
1293            !areas(&findings, "shell")
1294                .iter()
1295                .any(|f| f.detail.contains("shell_isolate_hide")),
1296            "{findings:#?}"
1297        );
1298    }
1299
1300    /// `#266`: the three states of the dashboard's sign-in, and the one that must not be silent.
1301    /// A doctor that said nothing about a token install would leave every existing dashboard on
1302    /// the shared string forever, with nothing to notice.
1303    #[test]
1304    fn the_dashboard_sign_in_is_reported_and_a_broken_hash_is_a_problem() {
1305        let (dir, env) = temp();
1306        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
1307        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
1308
1309        // No dashboard at all: no `web` line, not even an `ok` one.
1310        let quiet = check(&Config::default(), &env);
1311        assert!(areas(&quiet, "web").is_empty(), "{quiet:#?}");
1312
1313        // A dashboard on the token: a note that names the verb which ends it.
1314        let mut cfg = Config::default();
1315        cfg.web.auth_token = Some("t".repeat(64));
1316        let token_only = check(&cfg, &env);
1317        let web = areas(&token_only, "web");
1318        assert_eq!(web.len(), 1, "{token_only:#?}");
1319        // `Warn`, because that is the first level at which `doctor` prints a `fix:` line: advice
1320        // nobody is shown is not advice.
1321        assert_eq!(web[0].level, Level::Warn);
1322        assert!(web[0].detail.contains("web.auth_token"), "{:?}", web[0]);
1323        assert!(
1324            web[0]
1325                .fix
1326                .as_deref()
1327                .unwrap_or_default()
1328                .contains("eclipse web passwd"),
1329            "{:?}",
1330            web[0]
1331        );
1332
1333        // A password set: an `ok` line, and it names the user.
1334        let hash = crate::auth::hash_password("open sesame").unwrap();
1335        std::fs::write(
1336            dir.path().join(".env"),
1337            format!("ECLIPSE_WEB_USER=max\nECLIPSE_WEB_PASSWORD_HASH={hash}\n"),
1338        )
1339        .unwrap();
1340        let mut cfg = cfg.clone();
1341        cfg.dotenv
1342            .values
1343            .insert("ECLIPSE_WEB_USER".into(), "max".into());
1344        cfg.dotenv
1345            .values
1346            .insert("ECLIPSE_WEB_PASSWORD_HASH".into(), hash);
1347        let signed_in = check(&cfg, &env);
1348        let web = areas(&signed_in, "web");
1349        assert_eq!(web.len(), 1, "{signed_in:#?}");
1350        assert_eq!(web[0].level, Level::Ok);
1351        assert!(web[0].detail.contains("max"), "{:?}", web[0]);
1352
1353        // A hash this build cannot read stops the dashboard starting, so it is a problem, and the
1354        // parser's own words are the detail.
1355        cfg.dotenv.values.insert(
1356            "ECLIPSE_WEB_PASSWORD_HASH".into(),
1357            "argon2id$600000$aabb$ccdd".into(),
1358        );
1359        let broken = check(&cfg, &env);
1360        let web = areas(&broken, "web");
1361        assert_eq!(web.len(), 1, "{broken:#?}");
1362        assert_eq!(web[0].level, Level::Problem);
1363        assert!(web[0].detail.contains("unknown scheme"), "{:?}", web[0]);
1364    }
1365
1366    #[test]
1367    fn a_missing_session_directory_is_offered_as_a_repair() {
1368        let (dir, env) = temp();
1369        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
1370        let findings = check(&Config::default(), &env);
1371        let layout: Vec<&Finding> = areas(&findings, "layout");
1372        let sessions = layout.iter().find_map(|f| match &f.repair {
1373            Some(Repair::MakeDir(p)) if p.ends_with("sessions") => Some(p.clone()),
1374            _ => None,
1375        });
1376        let path =
1377            sessions.unwrap_or_else(|| panic!("no MakeDir for sessions offered: {layout:#?}"));
1378        std::fs::create_dir_all(&path).unwrap();
1379        assert!(path.is_dir());
1380        // And the second run is quiet about it.
1381        let again = check(&Config::default(), &env);
1382        assert!(!areas(&again, "layout")
1383            .iter()
1384            .any(|f| f.level >= Level::Warn && f.detail.contains("does not exist")));
1385    }
1386
1387    #[cfg(unix)]
1388    #[test]
1389    fn a_world_readable_dotenv_is_a_warning_with_a_chmod_repair() {
1390        use std::os::unix::fs::PermissionsExt;
1391        let (dir, env) = temp();
1392        let cfg_dir = dir.path().join(".eclipse");
1393        std::fs::create_dir_all(&cfg_dir).unwrap();
1394        let dotenv = cfg_dir.join(".env");
1395        std::fs::write(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN=secret\n").unwrap();
1396        std::fs::set_permissions(&dotenv, std::fs::Permissions::from_mode(0o644)).unwrap();
1397
1398        let findings = check(&Config::default(), &env);
1399        let perms: Vec<&Finding> = areas(&findings, "permissions");
1400        let bad = perms
1401            .iter()
1402            .find(|f| f.level == Level::Warn)
1403            .unwrap_or_else(|| panic!("no warning: {perms:#?}"));
1404        assert!(bad.detail.contains(".env"), "{:?}", bad.detail);
1405        assert!(matches!(bad.repair, Some(Repair::Chmod(_, 0o600))));
1406        assert!(bad
1407            .fix
1408            .as_deref()
1409            .unwrap_or_default()
1410            .starts_with("chmod 600"));
1411    }
1412
1413    #[test]
1414    fn a_plugin_named_but_missing_is_a_problem_with_a_repair() {
1415        let (dir, env) = temp();
1416        std::fs::create_dir_all(dir.path().join(".eclipse/plugins")).unwrap();
1417        let mut cfg = Config::default();
1418        cfg.plugins.enabled = vec!["gone".into()];
1419        let findings = check(&cfg, &env);
1420        let plugins: Vec<&Finding> = areas(&findings, "plugins");
1421        let problem = plugins
1422            .iter()
1423            .find(|f| f.level == Level::Problem)
1424            .unwrap_or_else(|| panic!("no problem: {plugins:#?}"));
1425        assert!(problem.detail.contains("gone"), "{:?}", problem.detail);
1426        assert_eq!(problem.repair, Some(Repair::DisablePlugin("gone".into())));
1427    }
1428
1429    #[test]
1430    fn a_broken_skill_is_named_and_not_touched() {
1431        let (dir, env) = temp();
1432        let skills = dir.path().join(".eclipse/skills/broken");
1433        std::fs::create_dir_all(&skills).unwrap();
1434        std::fs::write(
1435            skills.join("SKILL.md"),
1436            "---\ndescription: no name\n---\nbody\n",
1437        )
1438        .unwrap();
1439        let findings = check(&Config::default(), &env);
1440        let named: Vec<&Finding> = areas(&findings, "skills")
1441            .into_iter()
1442            .filter(|f| f.level == Level::Warn)
1443            .collect();
1444        assert!(!named.is_empty(), "{findings:#?}");
1445        assert!(
1446            named.iter().all(|f| f.repair.is_none()),
1447            "a skill has no disabled list to repair into: {named:#?}"
1448        );
1449    }
1450
1451    /// `#350`: an index that cannot fit every skill is a finding, not a stderr line only a
1452    /// terminal user ever sees. It names the count and the knob, and it is repairable by
1453    /// definition — the fix is the setting.
1454    #[test]
1455    fn an_index_that_cannot_fit_every_skill_names_the_count_and_the_knob() {
1456        let (dir, env) = temp();
1457        for name in ["alpha", "beta", "gamma"] {
1458            let dir = dir.path().join(format!(".eclipse/skills/{name}"));
1459            std::fs::create_dir_all(&dir).unwrap();
1460            std::fs::write(
1461                dir.join("SKILL.md"),
1462                format!(
1463                    "---\nname: {name}\ndescription: {}\n---\nbody\n",
1464                    "x".repeat(120)
1465                ),
1466            )
1467            .unwrap();
1468        }
1469        let mut cfg = Config::default();
1470        cfg.skills.index_budget_chars = 120;
1471        let findings = check(&cfg, &env);
1472        let warn = areas(&findings, "skills")
1473            .into_iter()
1474            .find(|f| f.level == Level::Warn && f.detail.contains("index fits"))
1475            .unwrap_or_else(|| panic!("{findings:#?}"));
1476        assert!(warn.detail.contains("of 3 skill(s)"), "{}", warn.detail);
1477        assert!(
1478            warn.fix
1479                .as_deref()
1480                .unwrap_or("")
1481                .contains("index_budget_chars"),
1482            "{warn:#?}"
1483        );
1484
1485        // With room for all three, no finding: the check is about a truncation, not about skills.
1486        let mut roomy = Config::default();
1487        roomy.skills.index_budget_chars = 0;
1488        let findings = check(&roomy, &env);
1489        assert!(
1490            !areas(&findings, "skills")
1491                .into_iter()
1492                .any(|f| f.detail.contains("index fits")),
1493            "{findings:#?}"
1494        );
1495    }
1496
1497    /// #225: the registry says `running` and the process is gone. That is the one state `/tasks`
1498    /// cannot correct by itself, so `doctor` names it — and offers to forget the entry, not the
1499    /// transcript.
1500    #[test]
1501    fn a_background_task_whose_process_died_is_a_warning_a_person_can_clear() {
1502        let (dir, env) = temp();
1503        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
1504        let registry = crate::tasks::Registry::new(dir.path().join(".eclipse/state"));
1505        let mut child = std::process::Command::new("true").spawn().expect("spawn");
1506        let pid = child.id();
1507        child.wait().expect("reap");
1508        let mut gone = crate::tasks::Task::spawned("1700000000000-4242-0", pid, "summarise");
1509        gone.state = crate::tasks::State::Running;
1510        registry.write(&gone).unwrap();
1511
1512        let findings = check(&Config::default(), &env);
1513        let tasks: Vec<&Finding> = areas(&findings, "tasks");
1514        let warned = tasks
1515            .iter()
1516            .find(|f| f.level == Level::Warn)
1517            .unwrap_or_else(|| panic!("no warning about the dead task: {tasks:#?}"));
1518        assert!(
1519            warned.detail.contains("1700000000000-4242-0") && warned.detail.contains("died"),
1520            "{:?}",
1521            warned.detail
1522        );
1523        assert_eq!(
1524            warned.repair,
1525            Some(Repair::ForgetTask(registry.path("1700000000000-4242-0")))
1526        );
1527        assert!(
1528            warned
1529                .fix
1530                .as_deref()
1531                .unwrap_or_default()
1532                .contains("eclipse sessions"),
1533            "the transcript stays: {:?}",
1534            warned.fix
1535        );
1536    }
1537
1538    #[test]
1539    fn a_task_still_running_is_reported_as_healthy_and_no_task_at_all_is_silent() {
1540        let (dir, env) = temp();
1541        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
1542        let quiet = check(&Config::default(), &env);
1543        assert!(
1544            areas(&quiet, "tasks").is_empty(),
1545            "nothing was ever started, so there is nothing to say"
1546        );
1547
1548        let registry = crate::tasks::Registry::new(dir.path().join(".eclipse/state"));
1549        let mut live = crate::tasks::Task::begun("1700000000001-4243-0", "count the files");
1550        live.pid = std::process::id();
1551        live.pid_since = None;
1552        registry.write(&live).unwrap();
1553        let findings = check(&Config::default(), &env);
1554        let tasks = areas(&findings, "tasks");
1555        assert_eq!(tasks.len(), 1, "{tasks:#?}");
1556        assert_eq!(tasks[0].level, Level::Ok, "{tasks:#?}");
1557        assert!(tasks[0].detail.contains("1 background task(s) running"));
1558    }
1559
1560    #[test]
1561    fn the_summary_counts_what_a_person_has_to_decide() {
1562        let findings = vec![
1563            Finding::ok("a", "fine"),
1564            Finding::new(Level::Warn, "b", "meh"),
1565            Finding::new(Level::Problem, "c", "broken").repair(Repair::MakeDir("/tmp/x".into())),
1566        ];
1567        let tally = Tally::of(&findings);
1568        assert_eq!(
1569            (tally.problems, tally.warnings, tally.repairable),
1570            (1, 1, 1)
1571        );
1572        assert_eq!(tally.summary(), "1 problem(s), 1 warning(s)");
1573    }
1574}