1use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7fn 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 #[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 let home = std::env::var_os("HOME").map(PathBuf::from);
146 let main = main_checkout(root).unwrap_or_else(|| root.to_path_buf());
147 expand_allow_read(&config.dispatch.allow_read, home.as_deref(), &main)?;
148 if !config.review.risky.is_empty() {
149 build_risky_globset(&config.review.risky)
150 .map_err(|e| format!("{}: {e}", path.display()))?;
151 }
152 Ok(Some(config))
153}
154
155pub fn expand_allow_read(
156 entries: &[String],
157 home: Option<&Path>,
158 main_checkout: &Path,
159) -> Result<Vec<PathBuf>, String> {
160 let mut expanded = Vec::with_capacity(entries.len());
161 for entry in entries {
162 if entry == "~" {
163 let h = home
164 .filter(|p| !p.as_os_str().is_empty())
165 .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
166 expanded.push(h.to_path_buf());
167 } else if let Some(suffix) = entry.strip_prefix("~/") {
168 let h = home
169 .filter(|p| !p.as_os_str().is_empty())
170 .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
171 expanded.push(h.join(suffix));
172 } else if entry == "$BLYTE_MAIN_CHECKOUT" {
173 expanded.push(main_checkout.to_path_buf());
174 } else if let Some(suffix) = entry.strip_prefix("$BLYTE_MAIN_CHECKOUT/") {
175 expanded.push(main_checkout.join(suffix));
176 } else if Path::new(entry).is_absolute() {
177 expanded.push(PathBuf::from(entry));
178 } else {
179 return Err(format!(
180 "blyte.toml: allow_read entry `{entry}` is a relative path; paths must be absolute, or start with ~/ or $BLYTE_MAIN_CHECKOUT"
181 ));
182 }
183 }
184 Ok(expanded)
185}
186
187pub fn main_checkout(root: &Path) -> Option<PathBuf> {
188 let out = Command::new("git")
189 .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
190 .current_dir(root)
191 .output()
192 .ok()?;
193 if !out.status.success() {
194 return None;
195 }
196 let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
197 if common.file_name()? != ".git" {
198 return None;
199 }
200 let parent = common.parent()?;
201 let parent_canon = parent.canonicalize().ok()?;
202 let root_canon = root.canonicalize().ok()?;
203 if parent_canon == root_canon {
204 return None;
205 }
206 Some(parent.to_path_buf())
207}
208
209pub fn load_with_fallback(root: &Path) -> Result<Option<(RepoConfig, bool)>, String> {
210 if let Some(cfg) = load(root)? {
211 return Ok(Some((cfg, false)));
212 }
213 if let Some(main) = main_checkout(root) {
214 if let Some(cfg) = load(&main)? {
215 return Ok(Some((cfg, true)));
216 }
217 }
218 Ok(None)
219}
220
221pub fn detect(root: &Path) -> Vec<String> {
222 let make = make_targets(root);
225 if make.iter().any(|t| t == "check") {
226 return vec!["make check".to_string()];
227 }
228 let from_make: Vec<String> = ["lint", "test"]
229 .iter()
230 .filter(|t| make.iter().any(|m| m == *t))
231 .map(|t| format!("make {t}"))
232 .collect();
233 if !from_make.is_empty() {
234 return from_make;
235 }
236
237 let mut steps = Vec::new();
238
239 if root.join("Cargo.toml").exists() {
241 steps.push("cargo fmt --all --check".to_string());
242 steps.push("cargo clippy --all-targets -- -D warnings".to_string());
243 steps.push("cargo test --workspace --all-targets".to_string());
244 }
245
246 if root.join("pyproject.toml").exists() {
248 let pyproject = std::fs::read_to_string(root.join("pyproject.toml")).unwrap_or_default();
249 let runner = if root.join("uv.lock").exists() {
250 "uv run "
251 } else {
252 "python3 -m "
253 };
254 if pyproject.contains("[tool.ruff") || root.join("ruff.toml").exists() {
255 steps.push(format!("{runner}ruff check ."));
256 }
257 if pyproject.contains("[tool.pytest") || root.join("tests").is_dir() {
258 steps.push(format!("{runner}pytest -q"));
259 }
260 }
261
262 if root.join("package.json").exists() {
264 let runner = if root.join("pnpm-lock.yaml").exists() {
265 "pnpm"
266 } else if root.join("yarn.lock").exists() {
267 "yarn"
268 } else {
269 "npm"
270 };
271 if let Ok(content) = std::fs::read_to_string(root.join("package.json")) {
272 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
273 if let Some(scripts) = val.get("scripts").and_then(|s| s.as_object()) {
274 for script in ["lint", "typecheck", "test"] {
275 if scripts.contains_key(script) {
276 let cmd = if script == "test" {
277 format!("{runner} test")
278 } else if runner == "yarn" {
279 format!("yarn {script}")
280 } else {
281 format!("{runner} run {script}")
282 };
283 steps.push(cmd);
284 }
285 }
286 }
287 }
288 }
289 }
290
291 if root.join("go.mod").exists() {
293 steps.push(r#"test -z "$(gofmt -l .)""#.to_string());
294 steps.push("go vet ./...".to_string());
295 steps.push("go test ./...".to_string());
296 }
297
298 steps
299}
300
301pub fn render(gate: &[String]) -> String {
302 let mut gate_str = String::new();
303 for step in gate {
304 gate_str.push_str(step);
305 gate_str.push('\n');
306 }
307 format!(
308 r#"# blyte.toml: how this repository's work is checked, for `blyte dispatch`.
309[dispatch]
310gate = """
311{gate_str}"""
312# model = "gemini-3.8-flash-high"
313max_seconds = 3600
314max_turns = 300
315# max_cost = 8.0
316# network = "on"
317# fold_budget = 60000
318# fix_round = true
319# setup = "uv sync" # prepares each new worktree before the implementer starts
320# allow_read = ["~/.cache/some-tool"] # extra paths the sandbox may read
321
322# [dispatch.env]
323# UV_FROZEN = "1" # settings for every command and the gate; never credentials
324"#
325 )
326}
327
328fn make_targets(root: &Path) -> Vec<String> {
332 let text = ["GNUmakefile", "makefile", "Makefile"]
333 .iter()
334 .find_map(|f| std::fs::read_to_string(root.join(f)).ok())
335 .unwrap_or_default();
336 text.lines()
337 .filter_map(|l| {
338 let (name, rest) = l.split_once(':')?;
339 if rest.starts_with('=')
340 || name.starts_with(['.', '\t', ' ', '#'])
341 || name.contains(['=', '$', ' '])
342 {
343 return None;
344 }
345 Some(name.trim().to_string())
346 })
347 .collect()
348}