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