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