agengo 0.5.4

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! `agengo doctor`: check that this machine and repository are ready for a run.
//!
//! Each check prints one line, `ok`, `warn` or `fail`, with what to do about
//! it. The command exits with 1 only when something would stop a run.

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())
}

/// The (major, minor) of `git version 2.43.0.windows.1`.
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()??))
}

/// One line per file `agengo init` writes: present, or how to get it back.
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
}

/// The first line of `<program> --version`, if it can be run.
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())
}

/// Which coding agents are installed, which one commands will use, and
/// whether Claude Code is logged in when it is the one in use.
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"),
            )),
        }
        // Not being logged in only stops a run that uses Claude Code.
        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
}

/// agy's own settings file, where its permission rules live.
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"))
}

/// What to add to agy's settings so a run without a terminal is not stopped
/// by a permission it cannot ask for.
const AGY_RULES: &str = r#"{"permissions":{"allow":["command(*)","write_file(*)"]}}"#;

/// agy cannot ask for approval when agengo starts it, so a tool it needs and
/// has no `allow` rule for is denied and the run ends without a result.
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 ")
        ),
    )
}

/// Print every check; returns whether none failed.
/// A stable name for what a check is about, so a coding agent can act on it
/// without matching prose.
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"
    }
}

/// Print every check; returns whether none failed. With `json` the checks go
/// out as one JSON object, which `agengo doctor --json` documents.
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, _)));
    }
}