agengo 0.5.1

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! `agengo init`: tell the coding agents that work in a repository when to
//! hand work to agengo.
//!
//! Agents only reach for a tool they know about. `init` installs the agengo
//! skill where Claude Code (`.claude/skills/`) and Codex and other agents
//! that read `.agents/skills/` look for skills, and adds a short section to
//! `AGENTS.md` for agents that read only that file. Re-running `init`
//! refreshes everything it wrote and leaves the rest of `AGENTS.md` alone.
//! It also creates an empty `.agengo/principles.md` for the project's own
//! rules, and never overwrites one that exists.

use anyhow::{Context, Result};
use std::{fs, path::Path};

const SKILL_TEMPLATE: &str = include_str!("../specs/skill/SKILL.md");

/// The skill text this binary installs, stamped with its version so `doctor`
/// can tell when the installed copy is out of date.
pub fn skill() -> String {
    SKILL_TEMPLATE.replace("{{version}}", env!("CARGO_PKG_VERSION"))
}

/// The version stamped in an installed skill, if it has one: `metadata.version`
/// in the frontmatter, or the HTML comment that agengo 0.4.0 wrote.
pub fn skill_version(text: &str) -> Option<&str> {
    let front = text.strip_prefix("---\n")?.split_once("\n---\n")?.0;
    if let Some(line) = front
        .lines()
        .find_map(|line| line.strip_prefix("  version: "))
    {
        return Some(line.trim_matches('"'));
    }
    let rest = text.split_once("<!-- agengo-skill: ")?.1;
    rest.split_whitespace().next()
}

const PRINCIPLES_TEMPLATE: &str = include_str!("../specs/principles-template.md");

const SKILL_PATHS: [&str; 2] = [
    ".claude/skills/agengo/SKILL.md",
    ".agents/skills/agengo/SKILL.md",
];
/// Where a repository keeps one plan file per run, named after the run ID.
pub const PLANS_DIR: &str = ".agengo/plans";
/// Text every agengo skill contains, to tell it from one the user wrote.
const OWN_MARKER: &str = "agengo is a command-line tool";
const BEGIN: &str = "<!-- agengo:begin -->";
const END: &str = "<!-- agengo:end -->";
const SECTION: &str = "\
## agengo

When the user asks for multi-step coding work, mentions agengo or a plan file,
or wants work built in parallel, tested and independently reviewed before it
lands, hand it to agengo instead of building it in the chat: write the plan to
`.agengo/plans/<run-id>.yaml`, validate it with
`agengo plan --file .agengo/plans/<run-id>.yaml --brief`, get the user's
approval, then `agengo run .agengo/plans/<run-id>.yaml --id <run-id>`. When the
request is still a rough idea for an app or feature, settle it first with
`agengo spec --idea \"...\"` (written to `.agengo/spec.yaml`): put each
question to the user and let them approve the spec. agengo never touches
`main`, and work counts as done only when its checks pass and an independent
reviewer approves it. The full instructions are in
`.agents/skills/agengo/SKILL.md`. If agengo fails, report the failure; do not
build the tasks yourself instead.
";

/// What happened to one file.
#[derive(Debug, PartialEq)]
pub enum Change {
    Created,
    Updated,
    Unchanged,
}

impl Change {
    fn label(&self) -> &'static str {
        match self {
            Self::Created => "created",
            Self::Updated => "updated",
            Self::Unchanged => "unchanged",
        }
    }
}

pub fn install(root: &Path, agents_md: bool) -> Result<Vec<(String, Change)>> {
    let mut changes = Vec::new();
    let skill = skill();
    for relative in SKILL_PATHS {
        let path = root.join(relative);
        // A skill that is not an agengo skill was written by the user:
        // keep it beside the new one instead of overwriting it silently.
        if let Ok(existing) = fs::read_to_string(&path) {
            if existing != skill && !existing.contains(OWN_MARKER) {
                let backup = format!("{relative}.bak");
                fs::write(root.join(&backup), existing)
                    .with_context(|| format!("cannot write {backup}"))?;
                changes.push((backup, Change::Created));
            }
        }
        changes.push((relative.to_owned(), write(&path, &skill)?));
    }
    // The principles belong to the project: create the template once and
    // leave the file alone afterwards.
    let principles = root.join(crate::spec::PRINCIPLES_PATH);
    let change = if principles.exists() {
        Change::Unchanged
    } else {
        write(
            &principles,
            &crate::detect::fill(PRINCIPLES_TEMPLATE, &crate::detect::guess(root)),
        )?
    };
    changes.push((crate::spec::PRINCIPLES_PATH.to_owned(), change));
    // Plans are kept one file per run, so `agengo plan ... > .agengo/plans/<run-id>.yaml`
    // works without the user creating the directory first.
    let plans = root.join(PLANS_DIR);
    // Git does not keep an empty folder, so a `.gitkeep` makes a clone have it too.
    let keep = plans.join(".gitkeep");
    let change = if keep.exists() {
        Change::Unchanged
    } else {
        fs::create_dir_all(&plans).with_context(|| format!("cannot create {}", plans.display()))?;
        fs::write(&keep, "").with_context(|| format!("cannot write {}", keep.display()))?;
        Change::Created
    };
    changes.push((format!("{PLANS_DIR}/"), change));
    if agents_md {
        let path = root.join("AGENTS.md");
        let existing = match fs::read_to_string(&path) {
            Ok(text) => Some(text),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
            Err(error) => {
                return Err(error).with_context(|| format!("cannot read {}", path.display()))
            }
        };
        changes.push((
            "AGENTS.md".to_owned(),
            write(&path, &with_section(existing.as_deref().unwrap_or("")))?,
        ));
    }
    Ok(changes)
}

pub fn report(root: &Path, changes: &[(String, Change)]) {
    println!("[INIT] agengo skill in {}", root.display());
    for (path, change) in changes {
        println!("- {path}: {}", change.label());
    }
    println!(
        "- Agents that load skills or AGENTS.md now know when to call agengo. Commit these files so everyone working in the repository gets them."
    );
    println!(
        "- Fill in {} with your stack, commands and conventions; agengo gives it to the agents that write specs and plans.",
        crate::spec::PRINCIPLES_PATH
    );
    let tracked: Vec<&str> = [
        ".agengo",
        ".claude/skills/agengo",
        ".agents/skills/agengo",
        "AGENTS.md",
    ]
    .into_iter()
    .filter(|path| root.join(path).exists())
    .collect();
    println!("- To commit them: git add {}", tracked.join(" "));
    if changes.iter().any(|(path, _)| path.ends_with(".bak")) {
        println!(
            "- A skill you wrote was replaced; the previous text is saved as the .bak file above."
        );
    }
    if let Ok(claude_md) = fs::read_to_string(root.join("CLAUDE.md")) {
        if !claude_md.contains("AGENTS.md") {
            println!("- Claude Code reads CLAUDE.md, not AGENTS.md: it learns about agengo from the skill. To share the AGENTS.md section too, add the line `@AGENTS.md` to CLAUDE.md.");
        }
    }
    println!(
        "- Next: open your coding agent here and describe what you want built, or run `agengo doctor` to check this machine."
    );
}

/// `text` with the agengo section added at the end, or replaced in place if
/// it is already there.
fn with_section(text: &str) -> String {
    let block = format!("{BEGIN}\n{SECTION}{END}\n");
    if let (Some(start), Some(end)) = (text.find(BEGIN), text.find(END)) {
        if start < end {
            let after = &text[end + END.len()..];
            return format!(
                "{}{block}{}",
                &text[..start],
                after.strip_prefix('\n').unwrap_or(after)
            );
        }
    }
    if text.is_empty() {
        block
    } else if text.ends_with("\n\n") {
        format!("{text}{block}")
    } else if text.ends_with('\n') {
        format!("{text}\n{block}")
    } else {
        format!("{text}\n\n{block}")
    }
}

fn write(path: &Path, contents: &str) -> Result<Change> {
    let change = match fs::read_to_string(path) {
        Ok(existing) if existing == contents => return Ok(Change::Unchanged),
        Ok(_) => Change::Updated,
        Err(_) => Change::Created,
    };
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("cannot create {}", parent.display()))?;
    }
    fs::write(path, contents).with_context(|| format!("cannot write {}", path.display()))?;
    Ok(change)
}

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

    #[test]
    fn skill_has_frontmatter_agents_can_load() {
        let text = skill();
        let front = text
            .strip_prefix("---\n")
            .and_then(|rest| rest.split_once("\n---\n"))
            .map(|(front, _)| front)
            .expect("frontmatter");
        assert!(front.lines().any(|line| line == "name: agengo"));
        let description = front
            .lines()
            .find_map(|line| line.strip_prefix("description: "))
            .expect("description");
        // Claude Code and Codex both cap skill descriptions at 1024 characters.
        assert!(description.len() <= 1024, "{}", description.len());
        // Claude Code shows `<` and `>` in a description as `&lt;` and `&gt;`.
        assert!(!description.contains(['<', '>']), "{description}");
        // The Agent Skills standard: the name matches the folder, and
        // `compatibility` is at most 500 characters.
        assert!(SKILL_PATHS
            .iter()
            .all(|path| path.contains("/skills/agengo/")));
        let compatibility = front
            .lines()
            .find_map(|line| line.strip_prefix("compatibility: "))
            .expect("compatibility");
        assert!(compatibility.len() <= 500);
        assert_eq!(skill_version(&text), Some(env!("CARGO_PKG_VERSION")));
        assert!(front.lines().any(|line| line == "license: MIT"));
    }

    #[test]
    fn reads_both_version_stamps() {
        assert_eq!(
            skill_version("---\nname: agengo\nmetadata:\n  version: \"0.5.0\"\n---\nbody"),
            Some("0.5.0")
        );
        assert_eq!(
            skill_version("---\nname: agengo\n---\n\n<!-- agengo-skill: 0.4.0 (x) -->\n"),
            Some("0.4.0")
        );
        assert_eq!(skill_version("---\nname: agengo\n---\nbody"), None);
    }

    #[test]
    fn section_is_appended_once_and_replaced_in_place() {
        let first = with_section("# Project\n\nRules.\n");
        assert!(first.starts_with("# Project\n\nRules.\n\n<!-- agengo:begin -->\n"));
        assert_eq!(with_section(&first), first);

        let stale = first.replace("hand it to agengo", "OLD") + "## Later\n";
        let refreshed = with_section(&stale);
        assert_eq!(refreshed, first.clone() + "## Later\n");
        assert_eq!(refreshed.matches(BEGIN).count(), 1);
    }

    #[test]
    fn a_skill_written_by_the_user_is_backed_up_not_lost() -> Result<()> {
        let root = tempfile::tempdir()?;
        let path = root.path().join(".claude/skills/agengo/SKILL.md");
        fs::create_dir_all(path.parent().unwrap())?;
        fs::write(&path, "my own skill")?;
        let changes = install(root.path(), false)?;
        assert!(changes
            .iter()
            .any(|(name, _)| name == ".claude/skills/agengo/SKILL.md.bak"));
        assert_eq!(
            fs::read_to_string(path.with_extension("md.bak"))?,
            "my own skill"
        );
        assert_eq!(fs::read_to_string(&path)?, skill());
        // An older agengo skill is upgraded without a backup.
        fs::write(&path, format!("old\n{OWN_MARKER}"))?;
        let again = install(root.path(), false)?;
        assert!(!again.iter().any(|(name, _)| name.ends_with(".bak")));
        Ok(())
    }

    #[test]
    fn install_reports_created_then_unchanged() -> Result<()> {
        let root = tempfile::tempdir()?;
        let changes = install(root.path(), true)?;
        assert!(changes.iter().all(|(_, change)| *change == Change::Created));
        assert_eq!(
            fs::read_to_string(root.path().join(".agents/skills/agengo/SKILL.md"))?,
            skill()
        );
        let again = install(root.path(), true)?;
        assert!(again.iter().all(|(_, change)| *change == Change::Unchanged));

        // The project's own principles are never overwritten.
        let principles = root.path().join(crate::spec::PRINCIPLES_PATH);
        fs::write(&principles, "## Stack\nRust\n")?;
        install(root.path(), true)?;
        assert_eq!(fs::read_to_string(&principles)?, "## Stack\nRust\n");

        let other = tempfile::tempdir()?;
        let without = install(other.path(), false)?;
        assert_eq!(without.len(), 4);
        assert!(other.path().join(PLANS_DIR).is_dir());
        assert!(!other.path().join("AGENTS.md").exists());
        Ok(())
    }
}