use anyhow::{Context, Result};
use std::{fs, path::Path};
const SKILL_TEMPLATE: &str = include_str!("../specs/skill/SKILL.md");
pub fn skill() -> String {
SKILL_TEMPLATE.replace("{{version}}", env!("CARGO_PKG_VERSION"))
}
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",
];
pub const PLANS_DIR: &str = ".agengo/plans";
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.
";
#[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);
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)?));
}
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));
let plans = root.join(PLANS_DIR);
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."
);
}
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");
assert!(description.len() <= 1024, "{}", description.len());
assert!(!description.contains(['<', '>']), "{description}");
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());
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));
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(())
}
}