use crate::process::{git_command, resolve, run};
use anyhow::Result;
use std::{ffi::OsStr, fs, path::Path};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub 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();
let top = git(cwd, &["rev-parse", "--show-toplevel"]).map(std::path::PathBuf::from);
out.extend(crate::platform::doctor_lines(
&crate::platform::detect(),
Some(top.as_deref().unwrap_or(cwd)),
));
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,
};
let environment = crate::platform::detect();
for name in &installed {
let program = driver::program(name).unwrap_or_else(|| name.clone());
if let Some(path) = resolve(OsStr::new(&program), cwd) {
if crate::platform::is_windows_program_in_wsl(&environment, &path) {
out.push((
Level::Warn,
crate::platform::windows_program_warning(name, &path),
));
continue;
}
}
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::Boundary(reason) => out.push((
Level::Ok,
format!("{name}: no sandbox of its own is needed; {reason} (`--sandbox strict` accepts 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"
),
)),
}
}
if installed.iter().any(|name| name == "agy") {
out.push(agy_permission_check(settings_path().as_deref()));
}
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::Boundary(reason) => out.push((
Level::Ok,
format!("claude: no sandbox of its own is needed; {reason} (`--sandbox strict` accepts it)"),
)),
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
}
fn settings_path() -> Option<std::path::PathBuf> {
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.filter(|value| !value.is_empty())?;
Some(Path::new(&home).join(".gemini/antigravity-cli/settings.json"))
}
const AGY_RULES: &str = r#"{"permissions":{"allow":["command(*)","write_file(*)"]}}"#;
fn agy_permission_check(settings: Option<&Path>) -> (Level, String) {
let allowed = settings
.and_then(|path| std::fs::read_to_string(path).ok())
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
.and_then(|value| value["permissions"]["allow"].as_array().cloned())
.unwrap_or_default();
let has = |action: &str| {
allowed
.iter()
.filter_map(|rule| rule.as_str())
.any(|rule| rule.starts_with(&format!("{action}(")))
};
let missing: Vec<&str> = ["command", "write_file"]
.into_iter()
.filter(|action| !has(action))
.collect();
if missing.is_empty() {
return (
Level::Ok,
"agy: permission rules for `command` and `write_file` are set".into(),
);
}
(
Level::Warn,
format!(
"agy: no `allow` rule for {} in ~/.gemini/antigravity-cli/settings.json; agy cannot ask for approval when agengo starts it, so a run stops at the first tool it needs. Add under permissions.allow (or use {AGY_RULES} for the whole file; `*` allows everything, so scope it to the project folder if you prefer)",
missing.join(" and ")
),
)
}
fn code_for(text: &str) -> &'static str {
let has = |part: &str| text.contains(part);
if text.starts_with("environment:") {
"environment"
} else if text.starts_with("git identity") {
"git-identity"
} else if text.starts_with("git:") {
"git"
} else if text.starts_with("repository:") {
"repository"
} else if text.starts_with("working tree:") {
"working-tree"
} else if text.starts_with("ANTHROPIC_API_KEY") {
"api-key-in-environment"
} else if has("Windows program started through WSL interop") {
"agent-is-windows-program"
} else if has("logged in") || has("login") {
"agent-login"
} else if has("sandbox") {
"sandbox"
} else if text.starts_with("agent:") {
"agent-selection"
} else if has("found on PATH") {
"agent-found"
} else if has("SKILL.md") || has("AGENTS.md") || has(".agengo/") || has("agengo init") {
"init-file"
} else {
"other"
}
}
pub fn report(cwd: &Path, json: bool) -> Result<bool> {
let mut ready = true;
let found = checks(cwd);
let level_name = |level: &Level| match level {
Level::Ok => "ok",
Level::Warn => "warn",
Level::Fail => "fail",
};
if found.iter().any(|(level, _)| *level == Level::Fail) {
ready = false;
}
if json {
let environment = crate::platform::detect();
let checks: Vec<serde_json::Value> = found
.iter()
.map(|(level, text)| {
serde_json::json!({"level": level_name(level), "code": code_for(text), "text": text})
})
.collect();
println!(
"{}",
serde_json::json!({
"ready": ready,
"environment": {"name": environment.describe(), "tier": environment.tier()},
"checks": checks
})
);
return Ok(ready);
}
println!("[DOCTOR] agengo readiness");
for (level, text) in &found {
println!("- [{}] {text}", level_name(level));
}
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 checks_get_stable_codes() {
assert_eq!(
code_for("environment: Linux (reference environment)"),
"environment"
);
assert_eq!(
code_for("git identity: user.name and user.email are set"),
"git-identity"
);
assert_eq!(code_for("git: not found; install Git 2.31 or newer"), "git");
assert_eq!(
code_for("claude: not logged in; run `claude`, then `/login`"),
"agent-login"
);
assert_eq!(
code_for("claude: no sandbox (Claude Code has none)"),
"sandbox"
);
assert_eq!(code_for("codex: found on PATH (0.174.0)"), "agent-found");
assert_eq!(
code_for("codex: /mnt/c/x/codex is a Windows program started through WSL interop, with its own login"),
"agent-is-windows-program"
);
assert_eq!(
code_for("AGENTS.md: has no agengo section; run `agengo init` to add it"),
"init-file"
);
assert_eq!(code_for("something new"), "other");
}
#[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")));
}
#[test]
fn agy_permissions_are_read_from_its_settings() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("settings.json");
assert!(matches!(
agy_permission_check(Some(&file)),
(Level::Warn, _)
));
std::fs::write(&file, r#"{"permissions":{"allow":["command(git)"]}}"#).unwrap();
let (level, text) = agy_permission_check(Some(&file));
assert!(matches!(level, Level::Warn));
assert!(
text.contains("write_file") && !text.contains("command and"),
"{text}"
);
std::fs::write(
&file,
r#"{"permissions":{"allow":["command(*)","write_file(*)"]}}"#,
)
.unwrap();
assert!(matches!(agy_permission_check(Some(&file)), (Level::Ok, _)));
}
}