blyte 0.80.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
//! `blyte.toml` repository configuration: gate detection, rendering, and loading.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Default value for `[dispatch] fix_round`: enabled (`true`) is the intended default.
fn default_fix_round() -> bool {
    true
}

#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DispatchConfig {
    pub gate: Option<String>,
    pub setup: Option<String>,
    pub base_check: Option<bool>,
    pub comments: Option<String>,
    /// Whether to run one fix round when the fresh review confirms fallbacks or raises concerns.
    /// Defaults to `true`.
    #[serde(default = "default_fix_round")]
    pub fix_round: bool,
    pub model: Option<String>,
    pub max_seconds: Option<u64>,
    pub max_turns: Option<u32>,
    pub max_cost: Option<f64>,
    pub fold_budget: Option<usize>,
    pub network: Option<String>,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub allow_read: Vec<String>,
}

impl Default for DispatchConfig {
    fn default() -> Self {
        Self {
            gate: None,
            setup: None,
            base_check: None,
            comments: None,
            fix_round: default_fix_round(),
            model: None,
            max_seconds: None,
            max_turns: None,
            max_cost: None,
            fold_budget: None,
            network: None,
            env: BTreeMap::new(),
            allow_read: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommentMode {
    Gate,
    Review,
    Off,
}

pub fn comment_mode(value: Option<&str>) -> Result<CommentMode, String> {
    match value {
        None | Some("gate") => Ok(CommentMode::Gate),
        Some("review") => Ok(CommentMode::Review),
        Some("off") => Ok(CommentMode::Off),
        Some(value) => Err(format!(
            "blyte.toml: [dispatch] comments must be \"gate\", \"review\" or \"off\", not \"{value}\""
        )),
    }
}

#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReviewConfig {
    #[serde(default)]
    pub risky: Vec<String>,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PublishApproval {
    #[default]
    Auto,
    Ask,
}

#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SurfaceConfig {
    #[serde(default)]
    pub publish: PublishApproval,
    #[serde(default)]
    pub land_check: Option<String>,
}

#[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RepoConfig {
    #[serde(default)]
    pub dispatch: DispatchConfig,
    #[serde(default)]
    pub review: ReviewConfig,
    #[serde(default)]
    pub surface: SurfaceConfig,
}

pub fn match_risky_paths(
    patterns: &[String],
    changed_files: &[String],
) -> Result<Vec<String>, String> {
    if patterns.is_empty() || changed_files.is_empty() {
        return Ok(Vec::new());
    }
    let set = build_risky_globset(patterns)?;
    let mut matched = Vec::new();
    for file in changed_files {
        if set.is_match(file) && !matched.contains(file) {
            matched.push(file.clone());
        }
    }
    Ok(matched)
}

fn build_risky_globset(patterns: &[String]) -> Result<globset::GlobSet, String> {
    let mut builder = globset::GlobSetBuilder::new();
    for raw in patterns {
        let pat = raw.trim();
        if pat.is_empty() {
            return Err("[review] risky contains an empty glob".to_string());
        }
        let glob = globset::GlobBuilder::new(pat)
            .literal_separator(true)
            .build()
            .map_err(|e| format!("[review] risky glob `{raw}` is invalid: {e}"))?;
        builder.add(glob);
    }
    builder
        .build()
        .map_err(|e| format!("[review] risky globs are invalid: {e}"))
}

pub fn load(root: &Path) -> Result<Option<RepoConfig>, String> {
    let path = root.join("blyte.toml");
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
    let config: RepoConfig =
        toml::from_str(&content).map_err(|e| format!("{}: {e}", path.display()))?;
    for (name, value) in &config.dispatch.env {
        if name.starts_with("BLYTE_") {
            return Err(format!(
                "{}: variable `{name}` starts with BLYTE_: blyte's own settings are not set from blyte.toml",
                path.display()
            ));
        }
        if blyte_agent::shell::credential_like(name, value) {
            return Err(format!(
                "{}: variable `{name}` looks like a credential; credentials are never set from blyte.toml",
                path.display()
            ));
        }
    }
    if !config.dispatch.allow_read.is_empty() {
        let home = std::env::var_os("HOME").map(PathBuf::from);
        let main = main_checkout(root).unwrap_or_else(|| root.to_path_buf());
        expand_allow_read(&config.dispatch.allow_read, home.as_deref(), &main)?;
    }
    if !config.review.risky.is_empty() {
        build_risky_globset(&config.review.risky)
            .map_err(|e| format!("{}: {e}", path.display()))?;
    }
    if let Some(land_check) = &config.surface.land_check {
        if land_check.trim().is_empty() {
            return Err(format!(
                "{}: [surface] land_check must not be blank",
                path.display()
            ));
        }
    }
    Ok(Some(config))
}

pub fn expand_allow_read(
    entries: &[String],
    home: Option<&Path>,
    main_checkout: &Path,
) -> Result<Vec<PathBuf>, String> {
    let mut expanded = Vec::with_capacity(entries.len());
    for entry in entries {
        if entry == "~" {
            let h = home
                .filter(|p| !p.as_os_str().is_empty())
                .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
            expanded.push(h.to_path_buf());
        } else if let Some(suffix) = entry.strip_prefix("~/") {
            let h = home
                .filter(|p| !p.as_os_str().is_empty())
                .ok_or_else(|| format!("blyte.toml: cannot expand `{entry}`: HOME is not set"))?;
            expanded.push(h.join(suffix));
        } else if entry == "$BLYTE_MAIN_CHECKOUT" {
            expanded.push(main_checkout.to_path_buf());
        } else if let Some(suffix) = entry.strip_prefix("$BLYTE_MAIN_CHECKOUT/") {
            expanded.push(main_checkout.join(suffix));
        } else if Path::new(entry).is_absolute() {
            expanded.push(PathBuf::from(entry));
        } else {
            return Err(format!(
                "blyte.toml: allow_read entry `{entry}` is a relative path; paths must be absolute, or start with ~/ or $BLYTE_MAIN_CHECKOUT"
            ));
        }
    }
    Ok(expanded)
}

pub fn main_checkout(root: &Path) -> Option<PathBuf> {
    let out = Command::new("git")
        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
        .current_dir(root)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
    if common.file_name()? != ".git" {
        return None;
    }
    let parent = common.parent()?;
    let parent_canon = parent.canonicalize().ok()?;
    let root_canon = root.canonicalize().ok()?;
    if parent_canon == root_canon {
        return None;
    }
    Some(parent.to_path_buf())
}

pub fn load_with_fallback(root: &Path) -> Result<Option<(RepoConfig, bool)>, String> {
    if let Some(cfg) = load(root)? {
        return Ok(Some((cfg, false)));
    }
    if let Some(main) = main_checkout(root) {
        if let Some(cfg) = load(&main)? {
            return Ok(Some((cfg, true)));
        }
    }
    Ok(None)
}

pub fn detect(root: &Path) -> Vec<String> {
    // A Makefile's own targets are how a repository says it is checked: blyte-eval's
    // `make lint` runs ruff and pyright, which per-language guessing would miss.
    let make = make_targets(root);
    if make.iter().any(|t| t == "check") {
        return vec!["make check".to_string()];
    }
    let from_make: Vec<String> = ["lint", "test"]
        .iter()
        .filter(|t| make.iter().any(|m| m == *t))
        .map(|t| format!("make {t}"))
        .collect();
    if !from_make.is_empty() {
        return from_make;
    }

    let mut steps = Vec::new();

    // Rust (Cargo.toml)
    if root.join("Cargo.toml").exists() {
        steps.push("cargo fmt --all --check".to_string());
        steps.push("cargo clippy --all-targets -- -D warnings".to_string());
        steps.push("cargo test --workspace --all-targets".to_string());
    }

    // Python (pyproject.toml)
    if root.join("pyproject.toml").exists() {
        let pyproject = std::fs::read_to_string(root.join("pyproject.toml")).unwrap_or_default();
        let runner = if root.join("uv.lock").exists() {
            "uv run "
        } else {
            "python3 -m "
        };
        if pyproject.contains("[tool.ruff") || root.join("ruff.toml").exists() {
            steps.push(format!("{runner}ruff check ."));
        }
        if pyproject.contains("[tool.pytest") || root.join("tests").is_dir() {
            steps.push(format!("{runner}pytest -q"));
        }
    }

    // Node (package.json)
    if root.join("package.json").exists() {
        let runner = if root.join("pnpm-lock.yaml").exists() {
            "pnpm"
        } else if root.join("yarn.lock").exists() {
            "yarn"
        } else {
            "npm"
        };
        if let Ok(content) = std::fs::read_to_string(root.join("package.json")) {
            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
                if let Some(scripts) = val.get("scripts").and_then(|s| s.as_object()) {
                    for script in ["lint", "typecheck", "test"] {
                        if scripts.contains_key(script) {
                            let cmd = if script == "test" {
                                format!("{runner} test")
                            } else if runner == "yarn" {
                                format!("yarn {script}")
                            } else {
                                format!("{runner} run {script}")
                            };
                            steps.push(cmd);
                        }
                    }
                }
            }
        }
    }

    // Go (go.mod)
    if root.join("go.mod").exists() {
        steps.push(r#"test -z "$(gofmt -l .)""#.to_string());
        steps.push("go vet ./...".to_string());
        steps.push("go test ./...".to_string());
    }

    steps
}

/// The targets a `Makefile` (or `makefile`, `GNUmakefile`) at `root` defines: lines of the form
/// `name:` at the start of a line, excluding variable assignments (`name := …`) and special
/// targets (`.PHONY`).
fn make_targets(root: &Path) -> Vec<String> {
    let text = ["GNUmakefile", "makefile", "Makefile"]
        .iter()
        .find_map(|f| std::fs::read_to_string(root.join(f)).ok())
        .unwrap_or_default();
    text.lines()
        .filter_map(|l| {
            let (name, rest) = l.split_once(':')?;
            if rest.starts_with('=')
                || name.starts_with(['.', '\t', ' ', '#'])
                || name.contains(['=', '$', ' '])
            {
                return None;
            }
            Some(name.trim().to_string())
        })
        .collect()
}