use crate::process::{git_command, resolve, run};
use anyhow::Result;
use std::{ffi::OsStr, fs, path::Path};
enum Level {
Ok,
Warn,
Fail,
}
fn git(cwd: &Path, args: &[&str]) -> Option<String> {
let output = run(git_command().current_dir(cwd).args(args), None, None).ok()?;
output
.status
.success()
.then(|| String::from_utf8_lossy(&output.stdout).trim().to_owned())
}
fn version(text: &str) -> Option<(u32, u32)> {
let number = text
.split_whitespace()
.find(|word| word.starts_with(|c: char| c.is_ascii_digit()))?;
let mut parts = number.split('.').map(|part| part.parse::<u32>().ok());
Some((parts.next()??, parts.next()??))
}
fn init_files(cwd: &Path, top: &Path) -> Vec<(Level, String)> {
let mut out = Vec::new();
let missing = |path: &str, what: &str| {
let tracked = git(cwd, &["ls-files", "--", path]).is_some_and(|names| !names.is_empty());
let fix = if tracked {
format!("it is committed, so `git restore {path}` brings it back (or `agengo init` rewrites it)")
} else {
"run `agengo init` to create it".to_owned()
};
(Level::Warn, format!("{path}: missing ({what}); {fix}"))
};
for path in [
".claude/skills/agengo/SKILL.md",
".agents/skills/agengo/SKILL.md",
] {
match fs::read_to_string(top.join(path)) {
Err(_) => out.push(missing(path, "agents will not know to call agengo")),
Ok(text) => {
let current = env!("CARGO_PKG_VERSION");
out.push(match crate::init::skill_version(&text) {
Some(found) if found == current => (Level::Ok, format!("{path}: matches agengo {current}")),
Some(found) => (Level::Warn, format!("{path}: written by agengo {found}, this is {current}; run `agengo init` to refresh it")),
None => (Level::Warn, format!("{path}: has no version stamp (older than agengo {current} or edited); run `agengo init` to refresh it")),
});
}
}
}
match fs::read_to_string(top.join("AGENTS.md")) {
Ok(text) if text.contains("<!-- agengo:begin -->") => {
out.push((Level::Ok, "AGENTS.md: has the agengo section".into()))
}
Ok(_) => out.push((
Level::Warn,
"AGENTS.md: has no agengo section; run `agengo init` to add it".into(),
)),
Err(_) => out.push(missing(
"AGENTS.md",
"agents that read only this file will not know about agengo",
)),
}
match crate::spec::principles(top) {
Ok(Some(_)) => out.push((Level::Ok, ".agengo/principles.md: filled in".into())),
Ok(None) if top.join(crate::spec::PRINCIPLES_PATH).is_file() => out.push((Level::Warn, ".agengo/principles.md: still empty; fill in your stack and commands so spec and plan agents do not guess".into())),
Ok(None) => out.push(missing(".agengo/principles.md", "spec and plan agents will guess your stack")),
Err(error) => out.push((Level::Fail, format!(".agengo/principles.md: {error}"))),
}
if top.join(".agengo/plans").is_dir() {
out.push((Level::Ok, ".agengo/plans: exists".into()));
} else {
out.push(missing(
".agengo/plans/",
"plans are kept here, one per run",
));
}
out
}
fn checks(cwd: &Path) -> Vec<(Level, String)> {
let mut out = Vec::new();
match git(cwd, &["--version"]).as_deref().and_then(version) {
None => out.push((
Level::Fail,
"git: not found; install Git 2.31 or newer".into(),
)),
Some(found) if found < (2, 31) => out.push((
Level::Fail,
format!(
"git: {}.{} is too old; agengo needs 2.31 or newer",
found.0, found.1
),
)),
Some(_) => out.push((Level::Ok, "git: 2.31 or newer".into())),
}
let (name, email) = (
git(cwd, &["config", "user.name"]),
git(cwd, &["config", "user.email"]),
);
if name.as_deref().is_some_and(|v| !v.is_empty())
&& email.as_deref().is_some_and(|v| !v.is_empty())
{
out.push((
Level::Ok,
"git identity: user.name and user.email are set".into(),
));
} else {
out.push((
Level::Fail,
"git identity: set it with `git config --global user.name \"Your Name\"` and `git config --global user.email you@example.com`".into(),
));
}
if git(cwd, &["rev-parse", "--show-toplevel"]).is_none() {
out.push((Level::Fail, "repository: this folder is not a Git repository; run `git init`, then make a first commit".into()));
} else if git(cwd, &["rev-parse", "--verify", "--quiet", "HEAD"]).is_none() {
out.push((Level::Fail, "repository: no commits yet; run `git add -A && git commit -m \"Initial commit\"` so agengo has a base".into()));
} else {
out.push((Level::Ok, "repository: has commits".into()));
match git(cwd, &["status", "--porcelain"]) {
Some(status) if !status.is_empty() => out.push((
Level::Warn,
format!("working tree: {} file(s) not committed; agents see only the last commit, so commit what the run needs", status.lines().count()),
)),
_ => out.push((Level::Ok, "working tree: clean".into())),
}
if let Some(top) = git(cwd, &["rev-parse", "--show-toplevel"]) {
out.extend(init_files(cwd, Path::new(&top)));
}
}
let root = git(cwd, &["rev-parse", "--show-toplevel"])
.map_or_else(|| cwd.to_path_buf(), std::path::PathBuf::from);
out.extend(agent_checks(cwd, &root));
if std::env::var_os("ANTHROPIC_API_KEY").is_some() {
out.push((
Level::Warn,
"ANTHROPIC_API_KEY is set; agengo removes it for agents unless you pass `--auth api`"
.into(),
));
}
out
}
fn program_version(program: &str, cwd: &Path) -> Option<String> {
let path = resolve(OsStr::new(program), cwd)?;
let output = run(
std::process::Command::new(path)
.current_dir(cwd)
.arg("--version"),
None,
Some(10),
)
.ok()?;
let text = String::from_utf8_lossy(&output.stdout);
let line = text.lines().next().unwrap_or_default().trim();
(output.status.success() && !line.is_empty()).then(|| line.to_owned())
}
fn agent_checks(cwd: &Path, root: &Path) -> Vec<(Level, String)> {
use crate::driver::{self, Selection};
let mut out = Vec::new();
let installed = driver::installed(cwd);
let selection = driver::selection(None, root);
let uses_claude = match &selection {
Ok(Selection::Chosen { name, .. }) => name == driver::CLAUDE,
_ => false,
};
for name in &installed {
let program = driver::program(name).unwrap_or_else(|| name.clone());
match program_version(&program, cwd) {
Some(version) if name != driver::CLAUDE => {
out.push((Level::Ok, format!("{name}: found on PATH ({version})")))
}
_ => out.push((Level::Ok, format!("{name}: found on PATH"))),
}
}
for name in installed.iter().filter(|name| *name != driver::CLAUDE) {
match driver::for_agent(Some(name)).sandbox_support() {
crate::sandbox::Support::Enforced => out.push((
Level::Ok,
format!("{name}: sandbox available (`--sandbox strict` can use it)"),
)),
crate::sandbox::Support::Unchecked(reason)
| crate::sandbox::Support::Unavailable(reason) => out.push((
Level::Warn,
format!(
"{name}: sandbox not checkable ({reason}); `--sandbox strict` would refuse it"
),
)),
}
}
match selection {
Err(error) => out.push((Level::Fail, format!("agent: {error:#}"))),
Ok(Selection::Nothing) => out.push((Level::Warn, "agent: none found on PATH; install Claude Code, Codex or Antigravity, or pass `--agent <executable>` to use a custom adapter".into())),
Ok(Selection::Several(names)) => out.push((Level::Fail, format!("agent: {} are installed and none is chosen, so a run would stop; run `agengo agent use NAME`", names.join(", ")))),
Ok(Selection::Chosen { name, source }) => {
let known = driver::program(&name).is_some();
if known && !installed.contains(&name) {
out.push((Level::Fail, format!("agent: {name} ({}) is not on PATH; install it or choose another with `agengo agent use NAME`", source.describe())));
} else {
out.push((Level::Ok, format!("agent: {name} ({})", source.describe())));
}
}
}
if installed.iter().any(|name| name == driver::CLAUDE) {
let status = run(
std::process::Command::new("claude")
.current_dir(cwd)
.args(["auth", "status"]),
None,
None,
)
.ok();
match crate::sandbox::claude_support(cwd) {
crate::sandbox::Support::Enforced => out.push((
Level::Ok,
"claude: sandbox available (`--sandbox auto` or `strict` can use it)".into(),
)),
crate::sandbox::Support::Unchecked(reason)
| crate::sandbox::Support::Unavailable(reason) => out.push((
Level::Warn,
format!("claude: no sandbox ({reason}); `--sandbox strict` would refuse it"),
)),
}
let unusable = if uses_claude {
Level::Fail
} else {
Level::Warn
};
match status {
Some(o) if o.status.success() && String::from_utf8_lossy(&o.stdout).contains("\"loggedIn\": false") => {
out.push((unusable, "claude: not logged in; run `claude`, then `/login`".into()))
}
Some(o) if o.status.success() => out.push((Level::Ok, "claude: logged in".into())),
_ => out.push((Level::Warn, "claude: could not confirm login; if a run fails at once, run `claude` and `/login`".into())),
}
}
out
}
pub fn report(cwd: &Path) -> Result<bool> {
let mut ready = true;
println!("[DOCTOR] agengo readiness");
for (level, text) in checks(cwd) {
let label = match level {
Level::Ok => "ok",
Level::Warn => "warn",
Level::Fail => {
ready = false;
"fail"
}
};
println!("- [{label}] {text}");
}
println!(
"- {}",
if ready {
"Ready. Describe what you want built to your coding agent, or write a plan and run `agengo run`."
} else {
"Fix the failed checks above, then run `agengo doctor` again."
}
);
Ok(ready)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_git_versions() {
assert_eq!(version("git version 2.43.0.windows.1"), Some((2, 43)));
assert_eq!(version("git version 2.31.0"), Some((2, 31)));
assert_eq!(version("nonsense"), None);
}
#[test]
fn a_deleted_file_says_how_to_get_it_back() {
let dir = tempfile::tempdir().unwrap();
let found = init_files(dir.path(), dir.path());
assert!(found
.iter()
.any(|(level, text)| matches!(level, Level::Warn)
&& text.starts_with("AGENTS.md: missing")
&& text.contains("agengo init")));
crate::init::install(dir.path(), true).unwrap();
let found = init_files(dir.path(), dir.path());
assert!(found.iter().all(|(level, _)| !matches!(level, Level::Fail)));
assert!(found
.iter()
.any(|(_, text)| text.starts_with(".agengo/principles.md: still empty")));
}
#[test]
fn a_folder_outside_git_fails_with_a_hint() {
let dir = tempfile::tempdir().unwrap();
let found = checks(dir.path());
assert!(found
.iter()
.any(|(level, text)| matches!(level, Level::Fail) && text.contains("git init")));
}
}