use crate::config::{Config, EnvFn};
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
Ok,
Note,
Warn,
Problem,
}
impl Level {
pub fn label(&self) -> &'static str {
match self {
Level::Ok => "ok",
Level::Note => "note",
Level::Warn => "warn",
Level::Problem => "problem",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Repair {
MakeDir(PathBuf),
Chmod(PathBuf, u32),
ClearLocks(Vec<PathBuf>),
DisablePlugin(String),
ForgetTask(PathBuf),
}
impl Repair {
pub fn describe(&self) -> String {
match self {
Repair::MakeDir(p) => format!("created {}", p.display()),
Repair::Chmod(p, mode) => format!("set {} to {mode:o}", p.display()),
Repair::ClearLocks(paths) => match paths.len() {
1 => format!("removed the stale lock {}", paths[0].display()),
n => format!("removed {n} stale lock files"),
},
Repair::DisablePlugin(name) => {
format!("removed `{name}` from [plugins] enabled (the directory stays)")
}
Repair::ForgetTask(path) => format!("forgot the background task {}", path.display()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
pub level: Level,
pub area: &'static str,
pub detail: String,
pub fix: Option<String>,
pub repair: Option<Repair>,
}
impl Finding {
pub fn ok(area: &'static str, detail: impl Into<String>) -> Self {
Self {
level: Level::Ok,
area,
detail: detail.into(),
fix: None,
repair: None,
}
}
pub fn new(level: Level, area: &'static str, detail: impl Into<String>) -> Self {
Self {
level,
area,
detail: detail.into(),
fix: None,
repair: None,
}
}
pub fn fix(mut self, what: impl Into<String>) -> Self {
self.fix = Some(what.into());
self
}
pub fn repair(mut self, repair: Repair) -> Self {
self.repair = Some(repair);
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Tally {
pub problems: usize,
pub warnings: usize,
pub repairable: usize,
}
impl Tally {
pub fn of(findings: &[Finding]) -> Tally {
let mut t = Tally::default();
for f in findings {
match f.level {
Level::Problem => t.problems += 1,
Level::Warn => t.warnings += 1,
_ => {}
}
if f.repair.is_some() {
t.repairable += 1;
}
}
t
}
pub fn summary(&self) -> String {
if self.problems == 0 && self.warnings == 0 {
return "nothing to fix".to_string();
}
let mut parts = Vec::new();
if self.problems > 0 {
parts.push(format!("{} problem(s)", self.problems));
}
if self.warnings > 0 {
parts.push(format!("{} warning(s)", self.warnings));
}
parts.join(", ")
}
}
pub fn check(cfg: &Config, env: EnvFn<'_>) -> Vec<Finding> {
let mut found = Vec::new();
check_layout(cfg, env, &mut found);
check_permissions(cfg, env, &mut found);
check_sessions(cfg, env, &mut found);
check_plugins(cfg, env, &mut found);
check_skills(cfg, env, &mut found);
check_tool_schemas(cfg, env, &mut found);
check_vision(cfg, env, &mut found);
check_shell(cfg, env, &mut found);
check_tasks(cfg, env, &mut found);
check_dashboard_auth(cfg, env, &mut found);
check_config_version(cfg, env, &mut found);
found
}
fn check_config_version(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
let built = crate::config::CONFIG_VERSION;
if cfg.config_version >= built {
return;
}
let Some(path) = crate::config::config_path(env) else {
return;
};
if !path.exists() {
return;
}
found.push(
Finding::new(
Level::Warn,
"config",
format!(
"the config file was written for shape v{} and this build writes v{}: a setting \
added since then is filled by its default and never appears in the file",
cfg.config_version, built
),
)
.fix("eclipse config migrate --dry-run # shows what it would add; then run it without --dry-run"),
);
}
fn check_dashboard_auth(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
if cfg
.web
.auth_token
.as_deref()
.is_none_or(|t| t.trim().is_empty())
{
return; }
let lookup = |name: &str| env(name).or_else(|| cfg.dotenv.values.get(name).cloned());
match crate::auth::Credentials::resolve(lookup) {
Ok(crate::auth::Credentials::Password { user, .. }) => found.push(Finding::ok(
"web",
format!("the dashboard signs in as {user} with a password (the token is the API's)"),
)),
Ok(crate::auth::Credentials::Token) => found.push(
Finding::new(
Level::Warn,
"web",
"the dashboard still signs in with `web.auth_token`: one shared string, pasted into \
a box, with no user to say who signed in",
)
.fix("eclipse web passwd — sets a username and a password hash in .env; the token \
keeps working for `/v1`"),
),
Err(why) => found.push(
Finding::new(
Level::Problem,
"web",
format!("the dashboard's password is set but unusable — {why}"),
)
.fix("eclipse web passwd — rewrites the line it cannot read"),
),
}
}
fn check_tasks(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
let Ok(state) = cfg.state_dir(env) else {
return;
};
let registry = crate::tasks::Registry::new(state);
let tasks = registry.list();
if tasks.is_empty() {
return;
}
let mut reported = 0;
for task in tasks.iter().filter(|t| t.died()) {
reported += 1;
found.push(
Finding::new(
Level::Warn,
"tasks",
format!(
"background task {} died and its entry was never closed: it was last seen {} ({})",
task.session,
crate::session::ago_words(task.updated_ms),
task.last
),
)
.fix(format!(
"rm {} — the transcript stays in `eclipse sessions`",
registry.path(&task.session).display()
))
.repair(Repair::ForgetTask(registry.path(&task.session))),
);
}
for task in tasks
.iter()
.filter(|t| t.state == crate::tasks::State::Waiting)
{
reported += 1;
found.push(Finding::new(
Level::Note,
"tasks",
format!(
"background task {} is waiting for an approval: {}",
task.session, task.detail
),
));
}
if reported == 0 {
let running = tasks.iter().filter(|t| !t.settled()).count();
let done = tasks.len() - running;
found.push(Finding::ok(
"tasks",
format!(
"{running} background task(s) running, {done} finished, none with a missing process"
),
));
}
}
fn check_layout(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
let mut made_note = Vec::new();
if let Some(dir) = cfg.global_context_dir(env) {
for name in ["memory", "skills", "plugins", "scripts"] {
let path = dir.join(name);
if path.is_dir() {
continue;
}
made_note.push(name);
found.push(
Finding::new(
Level::Note,
"layout",
format!(
"{} does not exist yet (it is created on first use)",
path.display()
),
)
.fix("nothing to do: `eclipse config init` creates the layout")
.repair(Repair::MakeDir(path.clone())),
);
}
}
if let Ok(dir) = cfg.sessions_dir(env) {
if !dir.is_dir() {
found.push(
Finding::new(
Level::Warn,
"layout",
format!(
"{} does not exist: the first run will create it",
dir.display()
),
)
.fix("`eclipse sessions list` creates it, or `eclipse doctor --fix`")
.repair(Repair::MakeDir(dir.clone())),
);
}
}
if made_note.is_empty() {
found.push(Finding::ok(
"layout",
"the config, state and session directories exist",
));
}
}
#[cfg(unix)]
fn check_permissions(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
use std::os::unix::fs::PermissionsExt;
let mut checked = 0;
let mut bad = 0;
let mut wanted: Vec<PathBuf> = Vec::new();
if let Some(dir) = cfg.global_context_dir(env) {
wanted.push(dir.join(".env"));
if let Some(profile) = cfg.global_context_dir(env) {
if cfg.profile_name() != "default" {
wanted.push(
profile
.join("profiles")
.join(cfg.profile_name())
.join(".env"),
);
}
}
}
if let Ok(dir) = cfg.sessions_dir(env) {
wanted.push(dir.join("sessions.db"));
}
for path in wanted {
let Ok(meta) = std::fs::metadata(&path) else {
continue;
};
checked += 1;
let mode = meta.permissions().mode() & 0o777;
if mode & 0o077 == 0 {
continue;
}
bad += 1;
found.push(
Finding::new(
Level::Warn,
"permissions",
format!(
"{} is {mode:o}; only its owner should be able to read it",
path.display()
),
)
.fix(format!("chmod 600 {}", path.display()))
.repair(Repair::Chmod(path.clone(), 0o600)),
);
}
if checked > 0 && bad == 0 {
found.push(Finding::ok("permissions", "private files are owner-only"));
}
}
#[cfg(not(unix))]
fn check_permissions(_: &Config, _: EnvFn<'_>, _: &mut Vec<Finding>) {}
fn check_sessions(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
let Ok(dir) = cfg.sessions_dir(env) else {
found.push(
Finding::new(
Level::Problem,
"sessions",
"no session directory can be resolved (HOME is not set)",
)
.fix("set HOME"),
);
return;
};
let store = crate::session::SessionStore::new(dir.clone());
let mut known: std::collections::HashSet<String> = std::collections::HashSet::new();
match store.list_with_archived() {
Ok(list) => {
for session in &list {
known.insert(session.id.clone());
}
let archived = list.iter().filter(|s| s.archived).count();
let mut detail = match archived {
0 => format!("{} session(s) in {}", list.len(), dir.display()),
n => format!(
"{} session(s) in {} ({} archived, out of the list — `sessions list --archived`)",
list.len(),
dir.display(),
n
),
};
if !store.has_fts() {
detail.push_str("; full-text search is unavailable in this build (LIKE is used instead)");
}
found.push(Finding::ok("sessions", detail));
}
Err(e) => found.push(
Finding::new(Level::Problem, "sessions", format!("the session database will not open: {e}"))
.fix("check the disk, then the permissions on sessions.db; the transcripts are still on disk"),
),
}
let stale = crate::session::stale_locks(&dir);
if !stale.is_empty() {
let orphans: Vec<&crate::session::StaleLock> = stale
.iter()
.filter(|lock| !known.contains(&lock.id))
.collect();
let mut detail = format!(
"{} lock file(s) with no holder in {} (checked with flock)",
stale.len(),
dir.display()
);
let level = if orphans.is_empty() {
detail.push_str(" — normal for sessions that are not running");
Level::Note
} else {
let names: Vec<&str> = orphans.iter().take(3).map(|l| l.id.as_str()).collect();
let more = orphans.len().saturating_sub(names.len());
detail.push_str(&format!(
", {} of them naming a session this store does not have: {}{}",
orphans.len(),
names.join(", "),
if more > 0 {
format!(" and {more} more")
} else {
String::new()
}
));
Level::Warn
};
found.push(
Finding::new(level, "sessions", detail)
.fix("`eclipse doctor --fix` removes them; the sessions themselves are unaffected")
.repair(Repair::ClearLocks(
stale.iter().map(|lock| lock.path.clone()).collect(),
)),
);
}
let held = crate::session::held_locks(&dir);
if !held.is_empty() {
let names: Vec<String> = held
.iter()
.take(3)
.map(|lock| format!("{} ({})", lock.id, lock.holder))
.collect();
let more = held.len().saturating_sub(names.len());
found.push(Finding::new(
Level::Warn,
"sessions",
format!(
"{} session(s) in use right now: {}{} — the lock is released when that run ends",
held.len(),
names.join(", "),
if more > 0 {
format!(" and {more} more")
} else {
String::new()
}
),
));
}
}
fn check_plugins(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
let dirs = cfg.plugins_dirs(env);
let loaded = crate::plugins::load(&dirs, &cfg.plugins.enabled);
for problem in &loaded.problems {
found.push(
Finding::new(Level::Warn, "plugins", problem.clone())
.fix("fix the manifest, or remove the plugin from [plugins] enabled"),
);
}
for name in &cfg.plugins.enabled {
if !dirs.iter().any(|d| d.join(name).is_dir()) {
found.push(
Finding::new(
Level::Problem,
"plugins",
format!("`{name}` is enabled but its directory is not there"),
)
.fix("remove it from [plugins] enabled, or restore the directory")
.repair(Repair::DisablePlugin(name.clone())),
);
}
}
let workspace = cfg.workspace_root(env);
let (tools, _skipped) = loaded.tools(&workspace, 1024, &[]);
let tools = tools.len();
if loaded.problems.is_empty() && !cfg.plugins.enabled.is_empty() {
found.push(Finding::ok(
"plugins",
format!("{} enabled, {tools} tool(s)", cfg.plugins.enabled.len()),
));
}
}
fn check_skills(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
let plugins = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled);
let workspace = cfg.workspace_root(env);
let roots = crate::skills::roots_for(cfg, env, &plugins, &workspace);
let report = crate::skills::discover(&roots);
for problem in &report.problems {
found.push(
Finding::new(Level::Warn, "skills", problem.clone())
.fix("check the directory's permissions"),
);
}
for broken in report.broken() {
let why = broken
.state
.as_ref()
.err()
.cloned()
.unwrap_or_else(|| "it did not load".into());
found.push(
Finding::new(
Level::Warn,
"skills",
format!("`{}` cannot be used: {why}", broken.name),
)
.fix(format!(
"fix {}; the agent is running without it",
broken.path.display()
)),
);
}
let active = report.active().count();
if report.problems.is_empty() && report.broken().next().is_none() {
found.push(Finding::ok("skills", format!("{active} load(s)")));
}
let (index, _) = crate::skills::index(&report, cfg.skills.index_budget_chars);
let kept = index.as_ref().map(|i| i.names.len()).unwrap_or(0);
if kept < active {
found.push(
Finding::new(
Level::Warn,
"skills",
format!(
"the index fits {kept} of {active} skill(s); the rest are reachable only by \
name (`skill_search`, then `skill_view`)"
),
)
.fix(format!(
"raise `[skills] index_budget_chars` ({} now) if the dropped ones matter, or leave \
it: the model is told they exist",
cfg.skills.index_budget_chars
)),
);
}
}
fn check_tool_schemas(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
let loaded = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled)
.with_mcp(crate::plugins::McpSettings::from_config(cfg))
.with_config_mcp(cfg);
let workspace = cfg.workspace_root(env);
let mut problems = Vec::new();
let registry = crate::runtime::registry_for(cfg, &loaded, &workspace, &env, &mut problems);
let described = registry.descriptors();
let offered: Vec<&crate::tools::ToolDescriptor> =
described.iter().filter(|d| d.advertised).collect();
if offered.is_empty() {
found.push(Finding::ok("tools", "no tool is offered"));
return;
}
let cost = |d: &crate::tools::ToolDescriptor| {
d.name.chars().count()
+ d.description.chars().count()
+ d.parameters.to_string().chars().count()
};
let total: usize = offered.iter().map(|d| cost(d)).sum();
let mut by_source: std::collections::BTreeMap<String, (usize, usize)> =
std::collections::BTreeMap::new();
for d in &offered {
let entry = by_source.entry(d.source.label()).or_insert((0, 0));
entry.0 += 1;
entry.1 += cost(d);
}
let mut rows: Vec<(String, usize, usize)> = by_source
.into_iter()
.map(|(label, (count, chars))| (label, count, chars))
.collect();
rows.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0)));
let split = rows
.iter()
.map(|(label, count, chars)| format!("{label} {count} tool(s) {chars} chars"))
.collect::<Vec<_>>()
.join(", ");
let deferred = described.iter().filter(|d| d.deferred).count();
let line = format!(
"{total} chars of schema in every request from {} tool(s) ({split}){}",
offered.len(),
if deferred == 0 {
String::new()
} else {
format!("; {deferred} more deferred behind `tool_search`")
}
);
let builtin_chars = rows
.iter()
.find(|(label, _, _)| label == "builtin")
.map(|(_, _, chars)| *chars)
.unwrap_or(0);
let heavy = offered.len() > 20 || total.saturating_sub(builtin_chars) > 4_000;
let heaviest = rows
.iter()
.find(|(label, _, _)| label != "builtin")
.map(|(label, _, _)| label.clone())
.unwrap_or_else(|| "plugin:mcp:*".to_string());
let fix = format!(
"defer it with `[tools] deferred = [\"{heaviest}\"]` (now: {:?}); a deferred tool stays \
callable through `tool_search` then `tool_call`",
cfg.tools.deferred
);
found.push(if heavy {
Finding::new(Level::Warn, "tools", line).fix(fix)
} else {
Finding::ok("tools", line)
});
}
fn check_vision(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
use crate::config::VisionMode;
let mode = cfg.vision.mode;
let plugins = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled);
let profiles = plugins.provider_profiles();
let routes = cfg.declared_routes();
let seeing: Vec<String> = routes
.iter()
.filter(|r| crate::vision::route_sees(&r.config, &profiles))
.map(|r| r.name.clone())
.collect();
if mode == VisionMode::Auto {
let route = cfg.vision.route.trim();
if !route.is_empty() {
if let Some(named) = routes.iter().find(|r| r.name == route) {
if !crate::vision::route_sees(&named.config, &profiles) {
let profile = named.config.profile.as_deref().unwrap_or("openai");
found.push(
Finding::new(
Level::Warn,
"vision",
format!(
"`vision route = \"{route}\"` (profile `{profile}`) does not \
declare vision, so a picture sent there would be refused"
),
)
.fix(format!(
"add `vision = true` under route `{route}` (or in profile \
`{profile}`) if it can see"
)),
);
}
}
return;
}
if seeing.is_empty() {
let route_list = routes
.iter()
.map(|r| r.name.as_str())
.collect::<Vec<_>>()
.join(", ");
found.push(
Finding::new(
Level::Note,
"vision",
format!(
"`[vision] mode = \"auto\"` with no route that declares vision: every \
attach is refused — add `vision = true` under a route that can see (and \
set `[vision] route` if it is not the default). Routes: {route_list}"
),
)
.fix(
"add `vision = true` under a route that can see, and set `[vision] route` \
if it is not the default",
),
);
} else if !routes
.first()
.is_some_and(|r| crate::vision::route_sees(&r.config, &profiles))
{
found.push(
Finding::new(
Level::Note,
"vision",
format!(
"`[vision] mode = \"auto\"` with no `[vision] route`: the default route \
does not declare vision, so attaches will be refused unless `[vision] \
route` names a seeing route ({})",
seeing.join(", ")
),
)
.fix("set `[vision] route` to one of the routes that declares `vision = true`"),
);
}
return;
}
if mode == VisionMode::Native && seeing.is_empty() {
found.push(
Finding::new(
Level::Warn,
"vision",
format!(
"`[vision] mode = \"native\"` with no route that declares vision: every \
attach is refused. Routes: {}",
routes
.iter()
.map(|r| r.name.as_str())
.collect::<Vec<_>>()
.join(", ")
),
)
.fix(
"add `vision = true` under a route that can see, or set `vision.mode = \"auto\"` \
and name a seeing route in `vision.route`",
),
);
return;
}
if mode == VisionMode::Text {
let route = cfg.vision.route.trim();
if route.is_empty() {
found.push(
Finding::new(
Level::Warn,
"vision",
"`[vision] mode = \"text\"` with no `vision route`: there is nothing to \
describe a picture, so every attach is refused",
)
.fix("set `vision route` to a route that declares `vision = true`"),
);
} else if let Some(named) = routes.iter().find(|r| r.name == route) {
if !crate::vision::route_sees(&named.config, &profiles) {
let profile = named.config.profile.as_deref().unwrap_or("openai");
found.push(
Finding::new(
Level::Warn,
"vision",
format!(
"`vision route = \"{route}\"` (profile `{profile}`) does not declare \
vision, so a picture sent there would be unreadable"
),
)
.fix(format!(
"add `vision = true` under route `{route}` (or in profile `{profile}`) \
if it can see"
)),
);
}
}
}
}
fn check_shell(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
use crate::config::ShellIsolate;
let sandbox = crate::sandbox::Sandbox::new(&cfg.tools, &cfg.workspace_root(env), None);
match cfg.tools.shell_isolate {
ShellIsolate::Off => found.push(Finding::ok(
"shell",
"shell_isolate = \"off\": commands run uncontained by request",
)),
ShellIsolate::Process => {
if !sandbox.degraded() && !sandbox.refuses() {
found.push(Finding::ok(
"shell",
format!("shell_isolate = \"process\" through {}", sandbox.status()),
));
} else {
found.push(
Finding::new(
Level::Warn,
"shell",
"shell_isolate = \"process\" but bubblewrap is not on PATH: commands run uncontained",
)
.fix("install bubblewrap (apt install bubblewrap), or set [tools] shell_isolate = \"off\" to stop the warning"),
);
}
}
ShellIsolate::Fs => {
if !sandbox.degraded() && !sandbox.refuses() {
found.push(Finding::ok(
"shell",
format!("shell_isolate = \"fs\" through {}", sandbox.status()),
));
} else {
found.push(
Finding::new(
Level::Problem,
"shell",
"shell_isolate = \"fs\" refuses every command: bubblewrap is not on PATH",
)
.fix("install bubblewrap (apt install bubblewrap), or set [tools] shell_isolate = \"process\""),
);
}
}
}
if cfg.tools.shell_isolate == ShellIsolate::Fs {
let unapplied: Vec<String> = sandbox
.skipped_hides()
.into_iter()
.filter(|(path, why)| {
!(*why == crate::sandbox::HideSkip::Missing && sandbox.is_suggested_hide(path))
})
.map(|(path, why)| format!("{} ({})", path.display(), why.why()))
.collect();
if !unapplied.is_empty() {
found.push(
Finding::new(
Level::Warn,
"shell",
format!("shell_isolate_hide is not hiding {}", unapplied.join(", ")),
)
.fix(
"correct the path, or drop the entry: a hide that is not applied leaves that \
file readable inside the sandbox",
),
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn env_of(home: &std::path::Path) -> impl Fn(&str) -> Option<String> {
let home = home.display().to_string();
move |k: &str| (k == "HOME").then(|| home.clone())
}
fn temp() -> (tempfile::TempDir, impl Fn(&str) -> Option<String>) {
let dir = tempfile::tempdir().unwrap();
let env = env_of(dir.path());
(dir, env)
}
fn areas<'a>(findings: &'a [Finding], area: &str) -> Vec<&'a Finding> {
findings.iter().filter(|f| f.area == area).collect()
}
#[test]
fn native_with_no_route_that_declares_vision_is_reported_and_says_what_to_change() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
let cfg = Config::from_toml_str(
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
[vision]\nmode = \"native\"\n",
)
.unwrap();
let findings = check(&cfg, &env);
let found = areas(&findings, "vision")
.into_iter()
.find(|f| f.level == Level::Warn)
.expect("a warn");
assert!(found.detail.contains("native"), "{}", found.detail);
let fix = found.fix.as_deref().expect("a fix");
assert!(fix.contains("auto"), "{fix}");
}
#[test]
fn text_without_a_route_is_reported() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
let cfg = Config::from_toml_str(
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
[vision]\nmode = \"text\"\n",
)
.unwrap();
let findings = check(&cfg, &env);
let found = areas(&findings, "vision")
.into_iter()
.find(|f| f.level == Level::Warn)
.expect("a warn");
assert!(found.detail.contains("vision route"), "{}", found.detail);
}
#[test]
fn auto_reports_when_no_route_declares_vision() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
let cfg = Config::from_toml_str(
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n",
)
.unwrap();
let findings = check(&cfg, &env);
let vision = areas(&findings, "vision");
assert_eq!(vision.len(), 1, "{findings:?}");
assert!(
vision[0].detail.contains("no route that declares vision"),
"{}",
vision[0].detail
);
assert!(
vision[0].detail.contains("vision = true"),
"{}",
vision[0].detail
);
let seeing_default = Config::from_toml_str(
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\nvision = true\n",
)
.unwrap();
assert!(areas(&check(&seeing_default, &env), "vision").is_empty());
let blind_route = Config::from_toml_str(
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
[[provider.route]]\nname = \"aux\"\nbase_url = \"http://127.0.0.1:2/v1\"\nmodel = \"v\"\nprofile = \"llamacpp\"\n\
[vision]\nmode = \"auto\"\nroute = \"aux\"\n",
)
.unwrap();
let findings = check(&blind_route, &env);
let found = areas(&findings, "vision")
.into_iter()
.find(|f| f.level == Level::Warn)
.expect("blind describe route warns in auto mode");
assert!(found.detail.contains("aux"), "{}", found.detail);
assert!(found.detail.contains("llamacpp"), "{}", found.detail);
assert!(
found.fix.as_deref().unwrap_or("").contains("vision = true"),
"{:?}",
found.fix
);
}
#[test]
fn a_stale_lock_names_the_check_that_was_made_and_not_a_liveness_test() {
let (dir, env) = temp();
let sessions = dir.path().join(".eclipse/state/sessions");
std::fs::create_dir_all(&sessions).unwrap();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
let lock = sessions.join("1796000000000-4242-0.lock");
std::fs::write(&lock, "4242\n").unwrap();
crate::session::SessionStore::new(sessions.clone())
.append(
"1796000000000-4242-0",
&crate::message::Message::user("hello"),
)
.unwrap();
let findings = check(&Config::default(), &env);
let stale = areas(&findings, "sessions")
.into_iter()
.find(|f| f.detail.contains("no holder"))
.expect("the unheld lock is counted");
assert_eq!(stale.level, Level::Note, "{}", stale.detail);
assert!(
stale.detail.contains("flock"),
"the sentence names the check it made: {}",
stale.detail
);
assert!(
!stale.detail.contains("which is not running"),
"and never implies a liveness test: {}",
stale.detail
);
assert!(
stale
.detail
.contains("normal for sessions that are not running"),
"it says the state is the ordinary one: {}",
stale.detail
);
}
#[test]
fn a_pile_of_finished_sessions_is_one_finding_about_locks() {
let (dir, env) = temp();
let sessions = dir.path().join(".eclipse/state/sessions");
std::fs::create_dir_all(&sessions).unwrap();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
let store = crate::session::SessionStore::new(sessions.clone());
for i in 0..40u32 {
let id = format!("17960000000{i:02}-4400-0");
store
.append(&id, &crate::message::Message::user("hi"))
.unwrap();
std::fs::write(
sessions.join(format!("{id}.lock")),
format!("{}\n", 4400 + i),
)
.unwrap();
}
let findings = check(&Config::default(), &env);
let about_locks: Vec<&Finding> = areas(&findings, "sessions")
.into_iter()
.filter(|f| f.detail.contains("lock"))
.collect();
assert_eq!(
about_locks.len(),
1,
"one line for the whole pile: {about_locks:#?}"
);
assert!(
about_locks[0].detail.contains("40"),
"{}",
about_locks[0].detail
);
assert_eq!(about_locks[0].level, Level::Note);
match about_locks[0].repair {
Some(Repair::ClearLocks(ref paths)) => assert_eq!(paths.len(), 40),
ref other => panic!("expected a ClearLocks repair, got {other:?}"),
}
}
#[test]
fn a_lock_with_no_session_behind_it_warns() {
let (dir, env) = temp();
let sessions = dir.path().join(".eclipse/state/sessions");
std::fs::create_dir_all(&sessions).unwrap();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
std::fs::write(sessions.join("1796000000009-9090-0.lock"), "9090\n").unwrap();
let findings = check(&Config::default(), &env);
let orphan = areas(&findings, "sessions")
.into_iter()
.find(|f| f.detail.contains("no holder"))
.expect("the lock is counted");
assert_eq!(orphan.level, Level::Warn, "{}", orphan.detail);
assert!(
orphan.detail.contains("1796000000009-9090-0"),
"it names the session nothing has: {}",
orphan.detail
);
}
#[test]
fn a_lock_a_run_holds_is_reported_as_in_use_and_never_as_stale() {
let (dir, env) = temp();
let sessions = dir.path().join(".eclipse/state/sessions");
std::fs::create_dir_all(&sessions).unwrap();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
let held = sessions.join("1796000000001-4243-0.lock");
let file = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(&held)
.unwrap();
{
use std::os::unix::io::AsRawFd;
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) };
assert_eq!(
rc,
0,
"taking the lock: {}",
std::io::Error::last_os_error()
);
}
std::fs::write(&held, "4243\n").unwrap();
let findings = check(&Config::default(), &env);
assert!(
!areas(&findings, "sessions")
.iter()
.any(|f| f.detail.contains("no holder")
|| f.detail.contains("1796000000001-4243-0.lock")),
"a lock this process holds is not stale: {findings:#?}"
);
let in_use = areas(&findings, "sessions")
.into_iter()
.find(|f| f.detail.contains("in use right now"))
.expect("a held lock is a session in use");
assert_eq!(in_use.level, Level::Warn);
assert!(
in_use.detail.contains("1796000000001-4243-0"),
"{}",
in_use.detail
);
drop(file);
}
#[test]
fn a_healthy_install_has_nothing_to_report() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
let cfg = Config::default();
let findings = check(&cfg, &env);
let tally = Tally::of(&findings);
assert_eq!(tally.problems, 0, "{findings:#?}");
let elsewhere: Vec<&Finding> = findings
.iter()
.filter(|f| f.area != "shell" && f.level >= Level::Warn)
.collect();
assert!(elsewhere.is_empty(), "{elsewhere:#?}");
if tally.warnings == 0 {
assert!(tally.summary().contains("nothing to fix"));
}
}
#[test]
fn a_hide_that_cannot_be_applied_is_named_with_its_reason() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
let mut cfg = Config::default();
cfg.tools.shell_isolate = crate::config::ShellIsolate::Fs;
cfg.tools.shell_isolate_hide = vec![dir.path().join(".netrcc")];
let findings = check(&cfg, &env);
let warned = areas(&findings, "shell")
.into_iter()
.find(|f| f.detail.contains("shell_isolate_hide"))
.unwrap_or_else(|| panic!("{findings:#?}"));
assert_eq!(warned.level, Level::Warn);
assert!(warned.detail.contains(".netrcc"), "{:?}", warned.detail);
assert!(
warned.detail.contains("no such path"),
"{:?}",
warned.detail
);
}
#[test]
fn a_suggested_hide_that_this_machine_does_not_have_is_not_a_finding() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
let mut cfg = Config::default();
cfg.tools.shell_isolate = crate::config::ShellIsolate::Fs;
cfg.tools.shell_isolate_hide = crate::config::default_hidden_paths();
let findings = check(&cfg, &env);
assert!(
!areas(&findings, "shell")
.iter()
.any(|f| f.detail.contains("shell_isolate_hide")),
"{findings:#?}"
);
}
#[test]
fn the_dashboard_sign_in_is_reported_and_a_broken_hash_is_a_problem() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
let quiet = check(&Config::default(), &env);
assert!(areas(&quiet, "web").is_empty(), "{quiet:#?}");
let mut cfg = Config::default();
cfg.web.auth_token = Some("t".repeat(64));
let token_only = check(&cfg, &env);
let web = areas(&token_only, "web");
assert_eq!(web.len(), 1, "{token_only:#?}");
assert_eq!(web[0].level, Level::Warn);
assert!(web[0].detail.contains("web.auth_token"), "{:?}", web[0]);
assert!(
web[0]
.fix
.as_deref()
.unwrap_or_default()
.contains("eclipse web passwd"),
"{:?}",
web[0]
);
let hash = crate::auth::hash_password("open sesame").unwrap();
std::fs::write(
dir.path().join(".env"),
format!("ECLIPSE_WEB_USER=max\nECLIPSE_WEB_PASSWORD_HASH={hash}\n"),
)
.unwrap();
let mut cfg = cfg.clone();
cfg.dotenv
.values
.insert("ECLIPSE_WEB_USER".into(), "max".into());
cfg.dotenv
.values
.insert("ECLIPSE_WEB_PASSWORD_HASH".into(), hash);
let signed_in = check(&cfg, &env);
let web = areas(&signed_in, "web");
assert_eq!(web.len(), 1, "{signed_in:#?}");
assert_eq!(web[0].level, Level::Ok);
assert!(web[0].detail.contains("max"), "{:?}", web[0]);
cfg.dotenv.values.insert(
"ECLIPSE_WEB_PASSWORD_HASH".into(),
"argon2id$600000$aabb$ccdd".into(),
);
let broken = check(&cfg, &env);
let web = areas(&broken, "web");
assert_eq!(web.len(), 1, "{broken:#?}");
assert_eq!(web[0].level, Level::Problem);
assert!(web[0].detail.contains("unknown scheme"), "{:?}", web[0]);
}
#[test]
fn a_missing_session_directory_is_offered_as_a_repair() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
let findings = check(&Config::default(), &env);
let layout: Vec<&Finding> = areas(&findings, "layout");
let sessions = layout.iter().find_map(|f| match &f.repair {
Some(Repair::MakeDir(p)) if p.ends_with("sessions") => Some(p.clone()),
_ => None,
});
let path =
sessions.unwrap_or_else(|| panic!("no MakeDir for sessions offered: {layout:#?}"));
std::fs::create_dir_all(&path).unwrap();
assert!(path.is_dir());
let again = check(&Config::default(), &env);
assert!(!areas(&again, "layout")
.iter()
.any(|f| f.level >= Level::Warn && f.detail.contains("does not exist")));
}
#[cfg(unix)]
#[test]
fn a_world_readable_dotenv_is_a_warning_with_a_chmod_repair() {
use std::os::unix::fs::PermissionsExt;
let (dir, env) = temp();
let cfg_dir = dir.path().join(".eclipse");
std::fs::create_dir_all(&cfg_dir).unwrap();
let dotenv = cfg_dir.join(".env");
std::fs::write(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN=secret\n").unwrap();
std::fs::set_permissions(&dotenv, std::fs::Permissions::from_mode(0o644)).unwrap();
let findings = check(&Config::default(), &env);
let perms: Vec<&Finding> = areas(&findings, "permissions");
let bad = perms
.iter()
.find(|f| f.level == Level::Warn)
.unwrap_or_else(|| panic!("no warning: {perms:#?}"));
assert!(bad.detail.contains(".env"), "{:?}", bad.detail);
assert!(matches!(bad.repair, Some(Repair::Chmod(_, 0o600))));
assert!(bad
.fix
.as_deref()
.unwrap_or_default()
.starts_with("chmod 600"));
}
#[test]
fn a_plugin_named_but_missing_is_a_problem_with_a_repair() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse/plugins")).unwrap();
let mut cfg = Config::default();
cfg.plugins.enabled = vec!["gone".into()];
let findings = check(&cfg, &env);
let plugins: Vec<&Finding> = areas(&findings, "plugins");
let problem = plugins
.iter()
.find(|f| f.level == Level::Problem)
.unwrap_or_else(|| panic!("no problem: {plugins:#?}"));
assert!(problem.detail.contains("gone"), "{:?}", problem.detail);
assert_eq!(problem.repair, Some(Repair::DisablePlugin("gone".into())));
}
#[test]
fn a_broken_skill_is_named_and_not_touched() {
let (dir, env) = temp();
let skills = dir.path().join(".eclipse/skills/broken");
std::fs::create_dir_all(&skills).unwrap();
std::fs::write(
skills.join("SKILL.md"),
"---\ndescription: no name\n---\nbody\n",
)
.unwrap();
let findings = check(&Config::default(), &env);
let named: Vec<&Finding> = areas(&findings, "skills")
.into_iter()
.filter(|f| f.level == Level::Warn)
.collect();
assert!(!named.is_empty(), "{findings:#?}");
assert!(
named.iter().all(|f| f.repair.is_none()),
"a skill has no disabled list to repair into: {named:#?}"
);
}
#[test]
fn an_index_that_cannot_fit_every_skill_names_the_count_and_the_knob() {
let (dir, env) = temp();
for name in ["alpha", "beta", "gamma"] {
let dir = dir.path().join(format!(".eclipse/skills/{name}"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("SKILL.md"),
format!(
"---\nname: {name}\ndescription: {}\n---\nbody\n",
"x".repeat(120)
),
)
.unwrap();
}
let mut cfg = Config::default();
cfg.skills.index_budget_chars = 120;
let findings = check(&cfg, &env);
let warn = areas(&findings, "skills")
.into_iter()
.find(|f| f.level == Level::Warn && f.detail.contains("index fits"))
.unwrap_or_else(|| panic!("{findings:#?}"));
assert!(warn.detail.contains("of 3 skill(s)"), "{}", warn.detail);
assert!(
warn.fix
.as_deref()
.unwrap_or("")
.contains("index_budget_chars"),
"{warn:#?}"
);
let mut roomy = Config::default();
roomy.skills.index_budget_chars = 0;
let findings = check(&roomy, &env);
assert!(
!areas(&findings, "skills")
.into_iter()
.any(|f| f.detail.contains("index fits")),
"{findings:#?}"
);
}
#[test]
fn a_background_task_whose_process_died_is_a_warning_a_person_can_clear() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
let registry = crate::tasks::Registry::new(dir.path().join(".eclipse/state"));
let mut child = std::process::Command::new("true").spawn().expect("spawn");
let pid = child.id();
child.wait().expect("reap");
let mut gone = crate::tasks::Task::spawned("1700000000000-4242-0", pid, "summarise");
gone.state = crate::tasks::State::Running;
registry.write(&gone).unwrap();
let findings = check(&Config::default(), &env);
let tasks: Vec<&Finding> = areas(&findings, "tasks");
let warned = tasks
.iter()
.find(|f| f.level == Level::Warn)
.unwrap_or_else(|| panic!("no warning about the dead task: {tasks:#?}"));
assert!(
warned.detail.contains("1700000000000-4242-0") && warned.detail.contains("died"),
"{:?}",
warned.detail
);
assert_eq!(
warned.repair,
Some(Repair::ForgetTask(registry.path("1700000000000-4242-0")))
);
assert!(
warned
.fix
.as_deref()
.unwrap_or_default()
.contains("eclipse sessions"),
"the transcript stays: {:?}",
warned.fix
);
}
#[test]
fn a_task_still_running_is_reported_as_healthy_and_no_task_at_all_is_silent() {
let (dir, env) = temp();
std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
let quiet = check(&Config::default(), &env);
assert!(
areas(&quiet, "tasks").is_empty(),
"nothing was ever started, so there is nothing to say"
);
let registry = crate::tasks::Registry::new(dir.path().join(".eclipse/state"));
let mut live = crate::tasks::Task::begun("1700000000001-4243-0", "count the files");
live.pid = std::process::id();
live.pid_since = None;
registry.write(&live).unwrap();
let findings = check(&Config::default(), &env);
let tasks = areas(&findings, "tasks");
assert_eq!(tasks.len(), 1, "{tasks:#?}");
assert_eq!(tasks[0].level, Level::Ok, "{tasks:#?}");
assert!(tasks[0].detail.contains("1 background task(s) running"));
}
#[test]
fn the_summary_counts_what_a_person_has_to_decide() {
let findings = vec![
Finding::ok("a", "fine"),
Finding::new(Level::Warn, "b", "meh"),
Finding::new(Level::Problem, "c", "broken").repair(Repair::MakeDir("/tmp/x".into())),
];
let tally = Tally::of(&findings);
assert_eq!(
(tally.problems, tally.warnings, tally.repairable),
(1, 1, 1)
);
assert_eq!(tally.summary(), "1 problem(s), 1 warning(s)");
}
}