Skip to main content

blyte_agent/
rules.rs

1//! The repository's own rules for agents, loaded on every run so that blyte gets them however it
2//! was started (2026-09-30: runs started with `blyte dispatch` directly saw only the task text,
3//! while the dispatch scripts appended `.claude/agy-rules.md`).
4//!
5//! The first file found wins: `.blyte/rules.md` (written for blyte), `.claude/agy-rules.md` (the
6//! implementer rules repositories already keep for headless agents), then `AGENTS.md` (the
7//! cross-tool convention). `CLAUDE.md` is not read: it is written for the conversation model. Each is
8//! looked for in the working tree, then in the main checkout, since the file may be untracked.
9
10use std::path::{Path, PathBuf};
11
12/// The files blyte reads rules from, in order of precedence (relative to the repository root).
13pub const RULE_FILES: [&str; 3] = [".blyte/rules.md", ".claude/agy-rules.md", "AGENTS.md"];
14
15/// Rules longer than this are cut, with a note, so one large file cannot crowd out the task.
16pub const MAX_RULES_CHARS: usize = 12_000;
17
18/// Repository rules: where they came from and their text (already capped).
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct RepoRules {
21    pub source: PathBuf,
22    pub text: String,
23}
24
25/// The main checkout's root when `root` is a linked git worktree, else `None`.
26fn main_checkout(root: &Path) -> Option<PathBuf> {
27    let out = std::process::Command::new("git")
28        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
29        .current_dir(root)
30        .output()
31        .ok()?;
32    if !out.status.success() {
33        return None;
34    }
35    let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
36    let main = common.parent()?.to_path_buf();
37    let same = main.canonicalize().ok()? == root.canonicalize().ok()?;
38    (!same).then_some(main)
39}
40
41/// Load the repository's rules for `root`, or `None` when it has none.
42pub fn load(root: &Path) -> Option<RepoRules> {
43    let mut roots = vec![root.to_path_buf()];
44    roots.extend(main_checkout(root));
45    for name in RULE_FILES {
46        for base in &roots {
47            let path = base.join(name);
48            let Ok(text) = std::fs::read_to_string(&path) else {
49                continue;
50            };
51            let text = text.trim();
52            if text.is_empty() {
53                continue;
54            }
55            let text = if text.chars().count() > MAX_RULES_CHARS {
56                let cut: String = text.chars().take(MAX_RULES_CHARS).collect();
57                format!("{cut}\n\n[cut at {MAX_RULES_CHARS} characters; the rest is in {name}]")
58            } else {
59                text.to_string()
60            };
61            return Some(RepoRules { source: path, text });
62        }
63    }
64    None
65}
66
67/// The system prompt section for the repository's rules; empty when it has none.
68pub fn prompt_section(root: &Path) -> String {
69    match load(root) {
70        Some(r) => format!(
71            "## Repository rules\nThe repository's own rules for agents, from `{}`. Follow them \
72             unless the task says otherwise; where they name a check command, it is the same \
73             check that decides completion.\n\n{}\n\n",
74            r.source.display(),
75            r.text
76        ),
77        None => String::new(),
78    }
79}