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