agengo 0.5.3

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Which agent a command uses. Nothing is chosen when agengo is installed:
//! each command looks at the flag, the environment, the repository's
//! configuration and the agents installed, in that order.

use crate::{adapter, config, process::resolve};
use anyhow::Result;
use std::{ffi::OsStr, path::Path};

/// The agent name for Claude Code, which has its own driver.
pub const CLAUDE: &str = "claude";
/// Configuration value meaning "use the only agent installed".
pub const AUTO: &str = "auto";
/// Environment variable that names the agent, below the flag.
pub const ENV: &str = "AGENGO_AGENT";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
    Flag,
    Env,
    Config,
    OnlyOneInstalled,
}

impl Source {
    pub fn describe(self) -> &'static str {
        match self {
            Self::Flag => "--agent",
            Self::Env => ENV,
            Self::Config => config::PATH,
            Self::OnlyOneInstalled => "the only agent installed",
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum Selection {
    Chosen {
        name: String,
        source: Source,
    },
    /// Several agents are installed and none is chosen.
    Several(Vec<String>),
    Nothing,
}

/// Every agent known by name, Claude Code first.
pub fn known() -> Vec<String> {
    let mut names = vec![CLAUDE.to_owned()];
    names.extend(super::known_agents());
    names
}

/// The program an agent known by name runs.
pub fn program(name: &str) -> Option<String> {
    if name == CLAUDE {
        Some(CLAUDE.to_owned())
    } else {
        super::known_program(name)
    }
}

/// The agents known by name whose program is on PATH.
pub fn installed(cwd: &Path) -> Vec<String> {
    known()
        .into_iter()
        .filter(|name| {
            program(name).is_some_and(|program| resolve(OsStr::new(&program), cwd).is_some())
        })
        .collect()
}

/// The decision, from the four inputs. The first of flag, environment and
/// configuration that names an agent wins; `auto` and empty values are skipped.
pub fn decide(
    flag: Option<&str>,
    env: Option<&str>,
    config: Option<&str>,
    installed: &[String],
) -> Selection {
    for (value, source) in [
        (flag, Source::Flag),
        (env, Source::Env),
        (config, Source::Config),
    ] {
        if let Some(name) = value
            .map(str::trim)
            .filter(|name| !name.is_empty() && *name != AUTO)
        {
            return Selection::Chosen {
                name: name.to_owned(),
                source,
            };
        }
    }
    match installed {
        [] => Selection::Nothing,
        [only] => Selection::Chosen {
            name: only.clone(),
            source: Source::OnlyOneInstalled,
        },
        several => Selection::Several(several.to_vec()),
    }
}

/// Look at the real flag, environment, configuration and PATH.
pub fn selection(flag: Option<&str>, root: &Path) -> Result<Selection> {
    let configured = config::load(root)?.agent;
    let env = std::env::var(ENV).ok();
    Ok(decide(
        flag,
        env.as_deref(),
        configured.as_deref(),
        &installed(root),
    ))
}

/// `agengo agent`: the agents installed and which one commands will use.
pub fn show(root: &Path) -> Result<()> {
    println!("[AGENTS] coding agents agengo can start");
    let cwd = std::env::current_dir()?;
    for name in known() {
        let program = program(&name).unwrap_or_default();
        match resolve(OsStr::new(&program), &cwd) {
            Some(path) => println!("- {name}: found ({})", path.display()),
            None => println!("- {name}: not found (agengo runs `{program}`)"),
        }
    }
    match selection(None, root)? {
        Selection::Chosen { name, source } => {
            println!("- Commands will use: {name} ({})", source.describe())
        }
        Selection::Several(names) => println!(
            "- Several are installed ({}) and none is chosen: run `agengo agent use NAME` to choose one for this repository, or pass --agent NAME.",
            names.join(", ")
        ),
        Selection::Nothing => println!(
            "- None found: install Claude Code, Codex or Antigravity, or pass --agent EXECUTABLE with a custom adapter."
        ),
    }
    Ok(())
}

/// `agengo agent use NAME`: keep the choice in `.agengo/config.yaml`.
/// `auto` removes it, so the only agent installed is used again.
pub fn use_agent(root: &Path, name: &str) -> Result<()> {
    if name == AUTO {
        config::set_agent(root, None)?;
        println!(
            "agengo: {} no longer names an agent; the only agent installed is used",
            config::PATH
        );
        return Ok(());
    }
    adapter::executable(Some(name))?;
    config::set_agent(root, Some(name))?;
    println!(
        "agengo: this repository now uses {name} ({}); `agengo agent use auto` undoes it",
        config::PATH
    );
    Ok(())
}

/// The agent name a run stored: nothing means Claude Code, a path means the
/// file name without its extension (`/usr/bin/codex` and `codex.exe` are
/// `codex`).
pub fn stored_name(stored: Option<&str>) -> String {
    stored.map_or_else(
        || CLAUDE.to_owned(),
        |path| {
            Path::new(path).file_stem().map_or_else(
                || path.to_owned(),
                |name| name.to_string_lossy().into_owned(),
            )
        },
    )
}

/// What `resume` says when it continues a run with the agent the run started
/// with and that is not the agent commands would use now.
pub fn resume_note(run: &str, stored: Option<&str>, current: &str) -> Option<String> {
    let pinned = stored_name(stored);
    (pinned != current).then(|| {
        format!(
            "agengo: run {run} started with {pinned} and keeps using it; the agent chosen now is {current}. Continue with {current} instead: agengo resume {run} --agent {current}"
        )
    })
}

/// What `agent use` says about runs that are not finished and started with
/// another agent: choosing an agent only affects new runs.
pub fn pinned_runs_note(runs: &[(String, Option<String>)], chosen: &str) -> Option<String> {
    let other: Vec<String> = runs
        .iter()
        .filter(|(_, agent)| stored_name(agent.as_deref()) != chosen)
        .map(|(id, agent)| format!("{id} ({})", stored_name(agent.as_deref())))
        .collect();
    (!other.is_empty()).then(|| {
        format!(
            "agengo: unfinished runs keep the agent they started with: {}. `agengo resume ID --agent {chosen}` moves one to {chosen}",
            other.join(", ")
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_run_that_keeps_another_agent_is_called_out() {
        assert_eq!(stored_name(None), "claude");
        assert_eq!(stored_name(Some("/usr/bin/codex")), "codex");
        assert_eq!(stored_name(Some("C:/tools/agy.exe")), "agy");
        assert!(resume_note("demo", None, "claude").is_none());
        let note = resume_note("demo", Some("/usr/bin/agy"), "codex").unwrap();
        assert!(
            note.contains("started with agy") && note.contains("resume demo --agent codex"),
            "{note}"
        );
        let runs = vec![
            ("a".to_owned(), None),
            ("b".to_owned(), Some("/bin/codex".to_owned())),
        ];
        let note = pinned_runs_note(&runs, "codex").unwrap();
        assert!(
            note.contains("a (claude)") && !note.contains("b ("),
            "{note}"
        );
        assert!(pinned_runs_note(&runs[1..], "codex").is_none());
    }

    fn names(items: &[&str]) -> Vec<String> {
        items.iter().map(|name| (*name).to_owned()).collect()
    }

    #[test]
    fn the_flag_beats_the_environment_beats_the_configuration() {
        let both = names(&["claude", "codex"]);
        let chosen = |flag, env, config| match decide(flag, env, config, &both) {
            Selection::Chosen { name, source } => (name, source),
            other => panic!("{other:?}"),
        };
        assert_eq!(
            chosen(Some("agy"), Some("codex"), Some("claude")),
            ("agy".into(), Source::Flag)
        );
        assert_eq!(
            chosen(None, Some("codex"), Some("claude")),
            ("codex".into(), Source::Env)
        );
        assert_eq!(
            chosen(None, None, Some("claude")),
            ("claude".into(), Source::Config)
        );
        // Empty and `auto` values do not choose.
        assert_eq!(
            chosen(Some(" "), Some("auto"), Some("codex")),
            ("codex".into(), Source::Config)
        );
    }

    #[test]
    fn without_a_choice_the_installed_agents_decide() {
        assert_eq!(decide(None, None, Some("auto"), &[]), Selection::Nothing);
        assert_eq!(
            decide(None, None, None, &names(&["codex"])),
            Selection::Chosen {
                name: "codex".into(),
                source: Source::OnlyOneInstalled
            }
        );
        assert_eq!(
            decide(None, None, None, &names(&["claude", "agy"])),
            Selection::Several(names(&["claude", "agy"]))
        );
    }

    #[test]
    fn a_choice_is_kept_even_when_that_agent_is_not_installed() {
        // The commands that use it say so; deciding is not checking.
        assert!(matches!(
            decide(Some("codex"), None, None, &[]),
            Selection::Chosen { .. }
        ));
    }

    #[test]
    fn every_agent_has_a_program() {
        for name in known() {
            assert!(program(&name).is_some(), "{name}");
        }
        assert_eq!(program("./adapter"), None);
    }
}