use std::path::{Path, PathBuf};
pub const RULE_FILES: [&str; 3] = [".blyte/rules.md", ".claude/agy-rules.md", "AGENTS.md"];
pub const MAX_RULES_CHARS: usize = 12_000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoRules {
pub source: PathBuf,
pub text: String,
}
fn main_checkout(root: &Path) -> Option<PathBuf> {
let out = std::process::Command::new("git")
.args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
.current_dir(root)
.output()
.ok()?;
if !out.status.success() {
return None;
}
let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
let main = common.parent()?.to_path_buf();
let same = main.canonicalize().ok()? == root.canonicalize().ok()?;
(!same).then_some(main)
}
pub fn load(root: &Path) -> Option<RepoRules> {
let mut roots = vec![root.to_path_buf()];
roots.extend(main_checkout(root));
for name in RULE_FILES {
for base in &roots {
let path = base.join(name);
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let text = text.trim();
if text.is_empty() {
continue;
}
let text = if text.chars().count() > MAX_RULES_CHARS {
let cut: String = text.chars().take(MAX_RULES_CHARS).collect();
format!("{cut}\n\n[cut at {MAX_RULES_CHARS} characters; the rest is in {name}]")
} else {
text.to_string()
};
return Some(RepoRules { source: path, text });
}
}
None
}
pub fn prompt_section(root: &Path) -> String {
match load(root) {
Some(r) => format!(
"## Repository rules\nThe repository's own rules for agents, from `{}`. Follow them \
unless the task says otherwise; where they name a check command, it is the same \
check that decides completion.\n\n{}\n\n",
r.source.display(),
r.text
),
None => String::new(),
}
}