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