Skip to main content

blyte_cli/
config.rs

1//! `blyte.toml` repository configuration: gate detection, rendering, and loading.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
8#[serde(deny_unknown_fields)]
9pub struct DispatchConfig {
10    pub gate: Option<String>,
11    pub setup: Option<String>,
12    pub base_check: Option<bool>,
13    pub comments: Option<String>,
14    pub model: Option<String>,
15    pub max_seconds: Option<u64>,
16    pub max_turns: Option<u32>,
17    pub max_cost: Option<f64>,
18    pub fold_budget: Option<usize>,
19    pub network: Option<String>,
20    #[serde(default)]
21    pub env: BTreeMap<String, String>,
22    #[serde(default)]
23    pub allow_read: Vec<String>,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum CommentMode {
28    Gate,
29    Review,
30    Off,
31}
32
33pub fn comment_mode(value: Option<&str>) -> Result<CommentMode, String> {
34    match value {
35        None | Some("gate") => Ok(CommentMode::Gate),
36        Some("review") => Ok(CommentMode::Review),
37        Some("off") => Ok(CommentMode::Off),
38        Some(value) => Err(format!(
39            "blyte.toml: [dispatch] comments must be \"gate\", \"review\" or \"off\", not \"{value}\""
40        )),
41    }
42}
43
44#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct ReviewConfig {
47    #[serde(default)]
48    pub risky: Vec<String>,
49}
50
51#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
52#[serde(deny_unknown_fields)]
53pub struct RepoConfig {
54    #[serde(default)]
55    pub dispatch: DispatchConfig,
56    #[serde(default)]
57    pub review: ReviewConfig,
58}
59
60pub fn match_risky_paths(
61    patterns: &[String],
62    changed_files: &[String],
63) -> Result<Vec<String>, String> {
64    if patterns.is_empty() || changed_files.is_empty() {
65        return Ok(Vec::new());
66    }
67    let set = build_risky_globset(patterns)?;
68    let mut matched = Vec::new();
69    for file in changed_files {
70        if set.is_match(file) && !matched.contains(file) {
71            matched.push(file.clone());
72        }
73    }
74    Ok(matched)
75}
76
77fn build_risky_globset(patterns: &[String]) -> Result<globset::GlobSet, String> {
78    let mut builder = globset::GlobSetBuilder::new();
79    for raw in patterns {
80        let pat = raw.trim();
81        if pat.is_empty() {
82            return Err("[review] risky contains an empty glob".to_string());
83        }
84        let glob = globset::GlobBuilder::new(pat)
85            .literal_separator(true)
86            .build()
87            .map_err(|e| format!("[review] risky glob `{raw}` is invalid: {e}"))?;
88        builder.add(glob);
89    }
90    builder
91        .build()
92        .map_err(|e| format!("[review] risky globs are invalid: {e}"))
93}
94
95pub fn load(root: &Path) -> Result<Option<RepoConfig>, String> {
96    let path = root.join("blyte.toml");
97    if !path.exists() {
98        return Ok(None);
99    }
100    let content = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
101    let config: RepoConfig =
102        toml::from_str(&content).map_err(|e| format!("{}: {e}", path.display()))?;
103    for (name, value) in &config.dispatch.env {
104        if name.starts_with("BLYTE_") {
105            return Err(format!(
106                "{}: variable `{name}` starts with BLYTE_: blyte's own settings are not set from blyte.toml",
107                path.display()
108            ));
109        }
110        if blyte_agent::shell::credential_like(name, value) {
111            return Err(format!(
112                "{}: variable `{name}` looks like a credential; credentials are never set from blyte.toml",
113                path.display()
114            ));
115        }
116    }
117    let home = std::env::var_os("HOME").map(PathBuf::from);
118    let main = main_checkout(root).unwrap_or_else(|| root.to_path_buf());
119    expand_allow_read(&config.dispatch.allow_read, home.as_deref(), &main)?;
120    if !config.review.risky.is_empty() {
121        build_risky_globset(&config.review.risky)
122            .map_err(|e| format!("{}: {e}", path.display()))?;
123    }
124    Ok(Some(config))
125}
126
127pub fn expand_allow_read(
128    entries: &[String],
129    home: Option<&Path>,
130    main_checkout: &Path,
131) -> Result<Vec<PathBuf>, String> {
132    let mut expanded = Vec::with_capacity(entries.len());
133    for entry in entries {
134        if entry == "~" {
135            let h = home
136                .filter(|p| !p.as_os_str().is_empty())
137                .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
138            expanded.push(h.to_path_buf());
139        } else if let Some(suffix) = entry.strip_prefix("~/") {
140            let h = home
141                .filter(|p| !p.as_os_str().is_empty())
142                .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
143            expanded.push(h.join(suffix));
144        } else if entry == "$BLYTE_MAIN_CHECKOUT" {
145            expanded.push(main_checkout.to_path_buf());
146        } else if let Some(suffix) = entry.strip_prefix("$BLYTE_MAIN_CHECKOUT/") {
147            expanded.push(main_checkout.join(suffix));
148        } else if Path::new(entry).is_absolute() {
149            expanded.push(PathBuf::from(entry));
150        } else {
151            return Err(format!(
152                "blyte.toml: allow_read entry `{entry}` is a relative path; paths must be absolute, or start with ~/ or $BLYTE_MAIN_CHECKOUT"
153            ));
154        }
155    }
156    Ok(expanded)
157}
158
159pub fn main_checkout(root: &Path) -> Option<PathBuf> {
160    let out = Command::new("git")
161        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
162        .current_dir(root)
163        .output()
164        .ok()?;
165    if !out.status.success() {
166        return None;
167    }
168    let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
169    if common.file_name()? != ".git" {
170        return None;
171    }
172    let parent = common.parent()?;
173    let parent_canon = parent.canonicalize().ok()?;
174    let root_canon = root.canonicalize().ok()?;
175    if parent_canon == root_canon {
176        return None;
177    }
178    Some(parent.to_path_buf())
179}
180
181pub fn load_with_fallback(root: &Path) -> Result<Option<(RepoConfig, bool)>, String> {
182    if let Some(cfg) = load(root)? {
183        return Ok(Some((cfg, false)));
184    }
185    if let Some(main) = main_checkout(root) {
186        if let Some(cfg) = load(&main)? {
187            return Ok(Some((cfg, true)));
188        }
189    }
190    Ok(None)
191}
192
193pub fn detect(root: &Path) -> Vec<String> {
194    // A Makefile's own targets are how a repository says it is checked: blyte-eval's
195    // `make lint` runs ruff and pyright, which per-language guessing would miss.
196    let make = make_targets(root);
197    if make.iter().any(|t| t == "check") {
198        return vec!["make check".to_string()];
199    }
200    let from_make: Vec<String> = ["lint", "test"]
201        .iter()
202        .filter(|t| make.iter().any(|m| m == *t))
203        .map(|t| format!("make {t}"))
204        .collect();
205    if !from_make.is_empty() {
206        return from_make;
207    }
208
209    let mut steps = Vec::new();
210
211    // Rust (Cargo.toml)
212    if root.join("Cargo.toml").exists() {
213        steps.push("cargo fmt --all --check".to_string());
214        steps.push("cargo clippy --all-targets -- -D warnings".to_string());
215        steps.push("cargo test --workspace --all-targets".to_string());
216    }
217
218    // Python (pyproject.toml)
219    if root.join("pyproject.toml").exists() {
220        let pyproject = std::fs::read_to_string(root.join("pyproject.toml")).unwrap_or_default();
221        let runner = if root.join("uv.lock").exists() {
222            "uv run "
223        } else {
224            "python3 -m "
225        };
226        if pyproject.contains("[tool.ruff") || root.join("ruff.toml").exists() {
227            steps.push(format!("{runner}ruff check ."));
228        }
229        if pyproject.contains("[tool.pytest") || root.join("tests").is_dir() {
230            steps.push(format!("{runner}pytest -q"));
231        }
232    }
233
234    // Node (package.json)
235    if root.join("package.json").exists() {
236        let runner = if root.join("pnpm-lock.yaml").exists() {
237            "pnpm"
238        } else if root.join("yarn.lock").exists() {
239            "yarn"
240        } else {
241            "npm"
242        };
243        if let Ok(content) = std::fs::read_to_string(root.join("package.json")) {
244            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
245                if let Some(scripts) = val.get("scripts").and_then(|s| s.as_object()) {
246                    for script in ["lint", "typecheck", "test"] {
247                        if scripts.contains_key(script) {
248                            let cmd = if script == "test" {
249                                format!("{runner} test")
250                            } else if runner == "yarn" {
251                                format!("yarn {script}")
252                            } else {
253                                format!("{runner} run {script}")
254                            };
255                            steps.push(cmd);
256                        }
257                    }
258                }
259            }
260        }
261    }
262
263    // Go (go.mod)
264    if root.join("go.mod").exists() {
265        steps.push(r#"test -z "$(gofmt -l .)""#.to_string());
266        steps.push("go vet ./...".to_string());
267        steps.push("go test ./...".to_string());
268    }
269
270    steps
271}
272
273pub fn render(gate: &[String]) -> String {
274    let mut gate_str = String::new();
275    for step in gate {
276        gate_str.push_str(step);
277        gate_str.push('\n');
278    }
279    format!(
280        r#"# blyte.toml: how this repository's work is checked, for `blyte dispatch`.
281[dispatch]
282gate = """
283{gate_str}"""
284# model = "gemini-3.8-flash-high"
285max_seconds = 3600
286max_turns = 300
287# max_cost = 8.0
288# network = "on"
289# fold_budget = 60000
290# setup = "uv sync"   # prepares each new worktree before the implementer starts
291# allow_read = ["~/.cache/some-tool"]   # extra paths the sandbox may read
292
293# [dispatch.env]
294# UV_FROZEN = "1"   # settings for every command and the gate; never credentials
295"#
296    )
297}
298
299/// The targets a `Makefile` (or `makefile`, `GNUmakefile`) at `root` defines: lines of the form
300/// `name:` at the start of a line, excluding variable assignments (`name := …`) and special
301/// targets (`.PHONY`).
302fn make_targets(root: &Path) -> Vec<String> {
303    let text = ["GNUmakefile", "makefile", "Makefile"]
304        .iter()
305        .find_map(|f| std::fs::read_to_string(root.join(f)).ok())
306        .unwrap_or_default();
307    text.lines()
308        .filter_map(|l| {
309            let (name, rest) = l.split_once(':')?;
310            if rest.starts_with('=')
311                || name.starts_with(['.', '\t', ' ', '#'])
312                || name.contains(['=', '$', ' '])
313            {
314                return None;
315            }
316            Some(name.trim().to_string())
317        })
318        .collect()
319}