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