use anyhow::Result;
use std::path::{Path, PathBuf};
const SKILL_PATH: &str = ".agents/skills/silcrow/SKILL.md";
const SKILL_OURS: [&str; 3] = [
"delegate to silcrow skill",
"thin pointer to the silcrow CLI",
"\nname: silcrow\n",
];
const NATIVE_SKILLS: [&str; 4] = [
".cursor/skills/silcrow/SKILL.md",
".claude/skills/silcrow/SKILL.md",
".codex/skills/silcrow/SKILL.md",
".opencode/skills/silcrow/SKILL.md",
];
fn skill_is_ours(text: &str) -> bool {
SKILL_OURS.iter().any(|mark| text.contains(mark))
}
fn read_if_present(path: &Path) -> Result<Option<String>> {
match std::fs::read_to_string(path) {
Ok(text) => Ok(Some(text)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(anyhow::Error::new(err).context(format!("read {}", path.display()))),
}
}
pub fn skill_copies(root: &Path) -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
for rel in std::iter::once(SKILL_PATH).chain(NATIVE_SKILLS) {
let path = root.join(rel);
if read_if_present(&path)?.is_some_and(|text| skill_is_ours(&text)) {
out.push(path);
}
}
Ok(out)
}
pub fn home_skills(home: &Path, ws_root: &Path) -> Vec<PathBuf> {
let home_is_root = std::fs::canonicalize(home).ok() == std::fs::canonicalize(ws_root).ok();
std::iter::once(SKILL_PATH)
.filter(|_| !home_is_root)
.chain(NATIVE_SKILLS)
.filter_map(|rel| Path::new(rel).parent())
.map(|dir| home.join(dir))
.filter(|dir| dir.exists())
.collect()
}
pub fn install_skill(root: &Path, dry_run: bool) -> Result<()> {
let path = root.join(SKILL_PATH);
let old = read_if_present(&path)?;
let body = crate::write::keep_line_endings(
old.as_deref().unwrap_or_default(),
&crate::skill::pointer(),
);
match old.as_deref() {
Some(text) if text == body => Ok(()),
Some(text) if !skill_is_ours(text) => {
eprintln!(
"left {} alone: it is not the Silcrow skill pointer",
path.display()
);
Ok(())
}
old => write_file(root, &path, old.unwrap_or_default(), &body, dry_run),
}
}
pub fn write_file(root: &Path, path: &Path, old: &str, body: &str, dry_run: bool) -> Result<()> {
if dry_run {
crate::write::print_diff(path.strip_prefix(root).unwrap_or(path), old, body);
return Ok(());
}
crate::walk::forget();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, body)?;
eprintln!("wrote {}", path.display());
Ok(())
}
const OPEN_TAG: &str = "<silcrow";
const CLOSE_TAG: &str = "</silcrow>";
pub struct Drift {
pub path: PathBuf,
pub versioned: bool,
pub add: Option<String>,
pub install_in: Option<PathBuf>,
pub manager: Option<(String, String)>,
}
pub fn project_drift(project: &Path) -> Result<Option<Drift>> {
let Some(branch) = default_branch_attr(project) else {
return Ok(Some(Drift {
path: project.join("AGENTS.md"),
versioned: true,
add: None,
install_in: None,
manager: None,
}));
};
Ok(agents_restore(project, &branch)?.map(|(path, _)| Drift {
path,
versioned: true,
add: None,
install_in: None,
manager: None,
}))
}
fn default_branch_attr(project: &Path) -> Option<String> {
let text = std::fs::read_to_string(project.join("AGENTS.md")).ok()?;
crate::scheme::attr_from_agents(&text, "default-branch")
}
pub fn drift_label(d: &Drift) -> String {
if let Some(line) = &d.add {
let root = d.path.parent().unwrap_or(&d.path);
match crate::hook::foreign_origin(root, &d.path) {
Some(origin) => format!(
"{} is a hook Silcrow did not write, not installed, and `silcrow install` leaves it: {origin}, `{line}`",
d.path.display()
),
None => format!(
"{} is a hook of another tool, not installed: Silcrow does not read it and `silcrow install` leaves it. To run Silcrow there, add `{line}` to it",
d.path.display()
),
}
} else if d.path.exists() {
format!("{} differs from this binary", d.path.display())
} else {
format!("{} is missing", d.path.display())
}
}
pub fn drift_text(d: &Drift) -> String {
if let Some((manager, line)) = &d.manager {
let state = match d.path.exists() {
true => "runs no Silcrow script of its own",
false => "is missing",
};
return format!(
"{} {state}: {manager} manages this repository's git hooks, so `silcrow install` writes none. Add `{line}` to that hook where {manager} runs it.",
d.path.display()
);
}
match &d.install_in {
Some(main) => format!(
"{}. Run `silcrow install` in the main checkout {}, whose hooks this worktree runs.",
drift_label(d),
main.display()
),
None => format!("{}. Run `silcrow install`.", drift_label(d)),
}
}
pub fn workspace_drift(ws_root: &Path) -> Result<Vec<Drift>> {
let mut out = Vec::new();
let skill = ws_root.join(SKILL_PATH);
if ws_root.join(".git").exists()
&& read_if_present(&skill)?.as_deref() != Some(crate::skill::pointer().as_str())
{
out.push(Drift {
path: skill,
versioned: true,
add: None,
install_in: None,
manager: None,
});
}
let hooks = crate::hook::drift(ws_root)?;
let (install_in, manager) = match hooks.is_empty() {
true => (None, None),
false => (
crate::hook::main_checkout(ws_root)?,
crate::hook::hook_manager(ws_root)?,
),
};
for (path, add) in hooks {
let event = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default();
let manager = manager
.clone()
.map(|m| (m, crate::hook::call_line(ws_root, event)));
out.push(Drift {
path,
versioned: false,
add: add.filter(|_| manager.is_none()),
install_in: install_in.clone(),
manager,
});
}
Ok(out)
}
pub fn probe_drift(ws_root: &Path) -> Result<Vec<Drift>> {
let ci = std::env::var("CI").ok();
let own_hooks = crate::walk::is_project(ws_root);
probe_drift_in(ws_root, crate::notice::ci_job(ci.as_deref()) || !own_hooks)
}
fn probe_drift_in(ws_root: &Path, no_hooks: bool) -> Result<Vec<Drift>> {
let mut drift = workspace_drift(ws_root)?;
drift.retain(|d| d.add.is_none() && (d.versioned || !no_hooks));
Ok(drift)
}
pub fn report_drift(ws_root: &Path, project: Option<&Path>) -> Result<()> {
let mut drift = probe_drift(ws_root)?;
drift.retain(|d| d.versioned);
if let Some(project) = project {
drift.extend(project_drift(project)?);
}
if drift.is_empty() {
return Ok(());
}
for d in &drift {
eprintln!("{}", drift_label(d));
}
eprintln!("run `silcrow install` to write them");
Ok(())
}
pub fn install_block_and_hooks(ws_root: &Path, project: &Path, dry_run: bool) -> Result<()> {
let branch = match default_branch_attr(project) {
Some(branch) => branch,
None => crate::published::default_branch(ws_root)?,
};
ensure_agents(ws_root, project, &branch, dry_run)?;
crate::hook::install(ws_root, dry_run)
}
fn agents_restore(root: &Path, branch: &str) -> Result<Option<(PathBuf, String)>> {
let path = root.join("AGENTS.md");
let notes = agents_notes(&path);
let policy = match crate::policy::ProjectPolicy::from_root(root) {
Ok(policy) => policy,
Err(_) if path.is_file() => return Ok(None),
Err(_) => crate::policy::ProjectPolicy::defaults(),
};
let canonical = canonical_block(¬es, branch, &policy);
if !path.is_file() {
return Ok(Some((path, format!("{canonical}\n"))));
}
let text = std::fs::read_to_string(&path)?;
Ok(restore_agents_text(&text, &canonical).map(|restored| (path, restored)))
}
fn ensure_agents(ws_root: &Path, root: &Path, branch: &str, dry_run: bool) -> Result<()> {
let Some((path, restored)) = agents_restore(root, branch)? else {
return Ok(());
};
let old = read_if_present(&path)?.unwrap_or_default();
let restored = crate::write::keep_line_endings(&old, &restored);
if restored == old {
return Ok(());
}
write_file(ws_root, &path, &old, &restored, dry_run)
}
fn agents_notes(path: &Path) -> String {
std::fs::read_to_string(path)
.ok()
.and_then(|text| crate::scheme::attr_from_agents(&text, "notes"))
.map_or_else(
|| crate::walk::DEFAULT_NOTES.to_string(),
|list| list.split_whitespace().collect::<Vec<_>>().join(" "),
)
}
pub(crate) fn block_range(text: &str) -> Option<(usize, usize)> {
let start = text.find(OPEN_TAG)?;
let end = start + text[start..].find(CLOSE_TAG)? + CLOSE_TAG.len();
Some((start, end))
}
pub fn strip_block(text: &str) -> Option<String> {
let (start, mut end) = block_range(text)?;
for _ in 0..2 {
if text[end..].starts_with("\r\n") {
end += 2;
} else if text[end..].starts_with('\n') {
end += 1;
}
}
Some(format!("{}{}", &text[..start], &text[end..]))
}
fn block_is_well_formed(text: &str, canonical: &str) -> bool {
let Some((start, end)) = block_range(text) else {
return false;
};
&text[start..end] == canonical
}
fn restore_agents_text(text: &str, canonical: &str) -> Option<String> {
if block_is_well_formed(text, canonical) {
return None;
}
if let Some((start, end)) = block_range(text) {
let mut out = String::new();
out.push_str(&text[..start]);
out.push_str(canonical);
out.push_str(&text[end..]);
return Some(out);
}
if text.trim().is_empty() {
return Some(format!("{canonical}\n"));
}
Some(format!("{canonical}\n\n{text}"))
}
const PRINCIPLES: &str = "Engineering principles:\n\
- Locality: keep behavior, data, and decisions close to where they are used, and fix a shared defect once at its source.\n\
- Explicitness: make inputs, outputs, dependencies, and failure modes visible.\n\
- Economy: use the smallest mechanism that completely solves the problem, reusing existing code before adding any, and finish every caller, test, and fixture it touches.\n\
- Stability: preserve observable behavior, including error handling and validation, across refactors unless a law changes it.\n\
- Decisions: state each law as a business decision, in plain and abstract words a person can reason about and steer behavior with, never as a restatement of the code, and leave out any value or detail with no reason behind it.\n\
- Verifiability: prefer deterministic behavior that can be checked directly, leave a test for new non-trivial logic, and name what was skipped or left unchecked.\n\
- Order: make it work, then make it right, then make it fast only when a measured need or a law demands it.\n";
fn canonical_block(notes: &str, branch: &str, policy: &crate::policy::ProjectPolicy) -> String {
let (tests, words) = (policy.tests_attr(), policy.note_words_attr());
let duties: String = [
("code", policy.code_attr()),
("docs", policy.docs_attr()),
("tests", tests.as_str()),
("test-markers", policy.test_markers.attr()),
("note-words", words.as_str()),
]
.into_iter()
.map(|(attr, value)| format!(" {attr}=\"{value}\""))
.collect();
format!(
"<silcrow notes=\"{notes}\" default-branch=\"{branch}\"{duties}>\n\
This repo follows [Silcrow](https://github.com/zifeo/silcrow).\n\
Decisions: `{notes}`. Usage: `silcrow help`.\n\
{PRINCIPLES}</silcrow>"
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn restores_missing_agents_file() {
let dir = tempfile::tempdir().unwrap();
ensure_agents(dir.path(), dir.path(), "main", false).unwrap();
let text = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
assert!(block_is_well_formed(
&text,
&canonical_block(
crate::walk::DEFAULT_NOTES,
"main",
&crate::policy::ProjectPolicy::defaults(),
)
));
assert!(
text.starts_with("<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" code=\"**/*\" docs=\"\" tests=\"conventions\" test-markers=\"error\" note-words=\"error:3000\">"),
"{text}"
);
}
#[test]
fn install_keeps_a_tests_list_the_block_writes() {
let dir = tempfile::tempdir().unwrap();
let block = "<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" code=\"**/*\" docs=\"\" tests=\"spec/**\">\nx\n</silcrow>\n";
std::fs::write(dir.path().join("AGENTS.md"), block).unwrap();
let (_, text) = agents_restore(dir.path(), "main").unwrap().unwrap();
assert!(
text.contains(" docs=\"\" tests=\"spec/**\" test-markers=\"error\""),
"{text}"
);
std::fs::write(dir.path().join("AGENTS.md"), &text).unwrap();
assert_eq!(agents_restore(dir.path(), "main").unwrap(), None);
}
#[test]
fn install_writes_the_default_of_each_attribute_a_block_omits() {
let dir = tempfile::tempdir().unwrap();
let block = "<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" docs=\"\" test-markers=\"warn\">\nx\n</silcrow>\n";
std::fs::write(dir.path().join("AGENTS.md"), block).unwrap();
let (_, text) = agents_restore(dir.path(), "main").unwrap().unwrap();
assert!(
text.starts_with("<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" code=\"**/*\" docs=\"\" tests=\"conventions\" test-markers=\"warn\" note-words=\"error:3000\">"),
"{text}"
);
std::fs::write(dir.path().join("AGENTS.md"), &text).unwrap();
assert_eq!(agents_restore(dir.path(), "main").unwrap(), None);
}
#[test]
fn install_leaves_a_block_with_doc_or_pin_alone() {
for original in [
"<silcrow doc=\"optional\">\nx\n</silcrow>\n",
"<silcrow notes=\"docs/decisions/**/*.md\" pin=\"optional\">\nx\n</silcrow>\n",
] {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("AGENTS.md"), original).unwrap();
assert_eq!(agents_restore(dir.path(), "main").unwrap(), None);
}
}
#[test]
fn a_custom_decisions_list_is_kept_with_its_words_joined() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/**/*.md !docs/archive/**\">\nx\n</silcrow>\n",
)
.unwrap();
let (_, text) = agents_restore(dir.path(), "main").unwrap().unwrap();
assert!(
text.starts_with(
"<silcrow notes=\"docs/**/*.md !docs/archive/**\" default-branch=\"main\""
),
"{text}"
);
assert!(
text.contains("Decisions: `docs/**/*.md !docs/archive/**`."),
"{text}"
);
}
#[test]
fn restores_missing_block() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("AGENTS.md"), "# hi\n").unwrap();
ensure_agents(dir.path(), dir.path(), "main", false).unwrap();
let text = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
assert!(text.contains("notes=\"docs/decisions/**/*.md\""));
assert!(text.contains("# hi"));
}
#[test]
fn accepts_present_block() {
let dir = tempfile::tempdir().unwrap();
let block = canonical_block(
crate::walk::DEFAULT_NOTES,
"main",
&crate::policy::ProjectPolicy::defaults(),
);
std::fs::write(dir.path().join("AGENTS.md"), format!("{block}\n")).unwrap();
assert!(ensure_agents(dir.path(), dir.path(), "main", false).is_ok());
let text = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
assert_eq!(text, format!("{block}\n"));
}
#[test]
fn dry_run_does_not_write() {
let dir = tempfile::tempdir().unwrap();
assert!(!dir.path().join("AGENTS.md").exists());
ensure_agents(dir.path(), dir.path(), "main", true).unwrap();
assert!(!dir.path().join("AGENTS.md").exists());
}
#[test]
fn leaves_unknown_policy_value_alone() {
let dir = tempfile::tempdir().unwrap();
let original = "<silcrow test-markers=\"maybe\">\nGraph: silcrow check.\n</silcrow>\n";
std::fs::write(dir.path().join("AGENTS.md"), original).unwrap();
ensure_agents(dir.path(), dir.path(), "main", false).unwrap();
let text = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
assert_eq!(text, original);
}
#[test]
fn install_skills_writes_only_agents() {
let dest = tempfile::tempdir().unwrap();
install_skill(dest.path(), false).unwrap();
let pointer = crate::skill::pointer();
let text =
std::fs::read_to_string(dest.path().join(".agents/skills/silcrow/SKILL.md")).unwrap();
assert_eq!(text, pointer);
for rel in [
".cursor/skills/silcrow/SKILL.md",
".claude/skills/silcrow/SKILL.md",
".codex/skills/silcrow/SKILL.md",
".opencode/skills/silcrow/SKILL.md",
] {
assert!(!dest.path().join(rel).exists(), "{rel}");
}
}
#[test]
fn install_skills_leaves_unmanaged_files() {
let dest = tempfile::tempdir().unwrap();
let foreign = dest.path().join(".agents/skills/silcrow/SKILL.md");
std::fs::create_dir_all(foreign.parent().unwrap()).unwrap();
std::fs::write(&foreign, "# mine\n").unwrap();
install_skill(dest.path(), false).unwrap();
assert_eq!(std::fs::read_to_string(&foreign).unwrap(), "# mine\n");
assert!(skill_copies(dest.path()).unwrap().is_empty());
}
#[test]
fn pointer_frontmatter_is_its_name_and_description() {
let pointer = crate::skill::pointer();
let front = pointer
.strip_prefix("---\n")
.and_then(|rest| rest.split_once("\n---\n"))
.map(|(front, _)| front)
.unwrap();
let keys: Vec<&str> = front
.lines()
.map(|line| line.split_once(':').unwrap().0)
.collect();
assert_eq!(keys, ["name", "description"]);
}
#[test]
fn committed_pointer_matches_this_binary() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let text = std::fs::read_to_string(root.join(".agents/skills/silcrow/SKILL.md")).unwrap();
assert_eq!(text, crate::skill::pointer());
}
#[test]
fn install_skills_refreshes_stale_pointer() {
let dest = tempfile::tempdir().unwrap();
let path = dest.path().join(".agents/skills/silcrow/SKILL.md");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
"---\nname: silcrow\ndescription: old\n---\n\nThis skill is a thin pointer to the silcrow CLI.\n",
)
.unwrap();
install_skill(dest.path(), false).unwrap();
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
crate::skill::pointer()
);
}
#[test]
fn install_skill_dry_run_writes_nothing() {
let dest = tempfile::tempdir().unwrap();
install_skill(dest.path(), true).unwrap();
assert!(!dest.path().join(SKILL_PATH).exists());
}
#[test]
fn skill_copies_names_the_pointer_and_native_copies_of_ours() {
let dest = tempfile::tempdir().unwrap();
install_skill(dest.path(), false).unwrap();
let native = dest.path().join(".claude/skills/silcrow/SKILL.md");
std::fs::create_dir_all(native.parent().unwrap()).unwrap();
std::fs::write(&native, "---\nname: silcrow\n---\n").unwrap();
let foreign = dest.path().join(".cursor/skills/silcrow/SKILL.md");
std::fs::create_dir_all(foreign.parent().unwrap()).unwrap();
std::fs::write(&foreign, "# mine\n").unwrap();
assert_eq!(
skill_copies(dest.path()).unwrap(),
vec![dest.path().join(SKILL_PATH), native]
);
}
}