agengo 0.4.0

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};

pub const SKILL: &str = include_str!("../specs/skill/SKILL.md");
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",
];
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.yaml,
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 a plan,
validate it with `agengo plan --file plan.yaml --brief`, get the user's
approval, then `agengo run plan.yaml --id <run-id>`. When the request is still
a rough idea for an app or feature, settle it first with
`agengo spec --idea \"...\"`: put each question to the user and let them
approve the spec. 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();
    for relative in SKILL_PATHS {
        changes.push((relative.to_owned(), write(&root.join(relative), 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, PRINCIPLES_TEMPLATE)?
    };
    changes.push((crate::spec::PRINCIPLES_PATH.to_owned(), 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(changes: &[(String, Change)]) {
    println!("[INIT] agengo skill");
    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
    );
}

/// `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 front = SKILL
            .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());
    }

    #[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 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(), 3);
        assert!(!other.path().join("AGENTS.md").exists());
        Ok(())
    }
}