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.
";
#[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)?));
}
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
);
}
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");
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));
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(())
}
}