agengo 0.5.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Claude Code in print mode, with the permissions each role needs.

use super::{Driver, Prepared};
use crate::config::Pick;
use crate::contract::string_or_empty;
use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::{env, ffi::OsStr, process::Command};

/// Commands and files the Builder and Reviewer may not touch. Passed with
/// `--settings`, so it applies to this run only and leaves the user's own
/// Claude Code settings alone. This narrows what a mistaken or manipulated
/// agent can do by accident; it is not a sandbox, because prefix rules can be
/// bypassed (for example through `bash -c` or a script the agent writes).
const DENIED_TOOLS: [&str; 22] = [
    "Bash(curl:*)",
    "Bash(wget:*)",
    "Bash(ssh:*)",
    "Bash(scp:*)",
    "Bash(nc:*)",
    "Bash(sudo:*)",
    "Bash(su:*)",
    "Bash(git push:*)",
    "Bash(git config:*)",
    "Bash(git remote:*)",
    "Bash(git worktree:*)",
    "Bash(git update-ref:*)",
    "Bash(git branch -D:*)",
    "Bash(rm -rf /:*)",
    "Bash(rm -rf ~:*)",
    "Read(~/.ssh/**)",
    "Read(~/.aws/**)",
    "Read(~/.config/gh/**)",
    "Read(~/.gnupg/**)",
    "Read(~/.netrc)",
    "Read(**/.env)",
    "Read(**/.env.*)",
];

#[cfg(test)]
pub fn guard_settings() -> String {
    settings(false)
}

/// The `--settings` value: the deny rules and, when `sandbox` is set, Claude
/// Code's own sandbox for shell commands. It may write in the working
/// directory (the worktree) and the temporary directory, and reach no host:
/// `allowedDomains` is empty. The sandbox covers Bash only, so the `Read`
/// deny rules stay. `failIfUnavailable` makes a sandbox that cannot start stop
/// the attempt, and `allowUnsandboxedCommands: false` removes the retry
/// without the sandbox.
fn settings(sandbox: bool) -> String {
    let mut value = serde_json::json!({"permissions": {"deny": DENIED_TOOLS}});
    if sandbox {
        value["sandbox"] = serde_json::json!({
            "enabled": true,
            "failIfUnavailable": true,
            "allowUnsandboxedCommands": false,
            "network": {"allowedDomains": []},
        });
    }
    value.to_string()
}

pub struct Claude {
    /// The program to run; `None` finds `claude` on PATH. Tests give a script.
    pub program: Option<std::ffi::OsString>,
}

/// The program that runs Claude Code. On Windows `claude` is usually
/// `claude.cmd` (npm) or `claude.exe`, which `Command` does not find by name.
fn program() -> std::ffi::OsString {
    env::current_dir()
        .ok()
        .and_then(|cwd| crate::process::resolve(OsStr::new("claude"), &cwd))
        .map_or_else(|| "claude".into(), |path| path.into_os_string())
}

impl Driver for Claude {
    fn name(&self) -> String {
        "claude".into()
    }

    fn sandbox_support(&self) -> crate::sandbox::Support {
        crate::sandbox::claude_support(&env::current_dir().unwrap_or_default())
    }

    fn prepare(&self, request: &Value, profile: &Value, pick: &Pick) -> Result<Prepared> {
        let role = string_or_empty(&request["role"]);
        let config = &profile["roles"][role];
        // Print mode has nobody to approve prompts, so any tool that would ask
        // is refused. Pre-approve what each role's instructions require:
        // the builder edits files and runs tests, the reviewer runs checks.
        let (tools, mode, allowed) = match role {
            "plan" | "specify" => ("Read,Grep,Glob", "default", None),
            "build" => (
                "Read,Grep,Glob,Edit,Write,Bash",
                "acceptEdits",
                Some("Bash"),
            ),
            "review" | "verify" => ("Read,Grep,Glob,Bash", "default", Some("Bash")),
            _ => bail!("unknown role: {role}"),
        };
        // One line: Windows refuses line breaks in arguments to a batch file
        // such as claude.cmd.
        let schema = serde_json::from_str::<Value>(string_or_empty(&config["schema"]))
            .context("role schema is not valid JSON")?
            .to_string();
        let mut command = Command::new(self.program.clone().unwrap_or_else(program));
        command.args([
            "-p",
            "--output-format",
            "json",
            "--json-schema",
            &schema,
            "--tools",
            tools,
            "--permission-mode",
            mode,
            "--strict-mcp-config",
        ]);
        if let Some(model) = &pick.model {
            command.args(["--model", model]);
        }
        if let Some(effort) = pick.effort {
            command.args(["--effort", effort.as_str()]);
        }
        if let Some(allowed) = allowed {
            command.args(["--allowedTools", allowed]);
            // Deny rules win over the allow rule above, so Bash stays usable
            // for building and checking while the riskiest commands are refused.
            let sandboxed =
                pick.sandbox != crate::config::Sandbox::Off && self.sandbox_support().is_enforced();
            command.args(["--settings", &settings(sandboxed)]);
        }
        let prompt = super::role_prompt(request, profile);
        Ok(Prepared {
            command,
            stdin: format!("{prompt}\n\n{request}"),
        })
    }

    fn usage(&self, output: &mut Value) -> Option<Value> {
        crate::usage::from_claude(output)
    }

    fn reported_error(&self, output: &Value) -> Option<String> {
        (output["is_error"] == true).then(|| {
            output["result"]
                .as_str()
                .unwrap_or("Claude Code reported an error")
                .to_owned()
        })
    }

    fn reply(&self, mut output: Value) -> Value {
        output["structured_output"].take()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;
    use serde_json::Value;

    #[test]
    fn guard_settings_deny_network_push_and_secret_reads() -> Result<()> {
        let settings: Value = serde_json::from_str(&guard_settings())?;
        let deny: Vec<&str> = settings["permissions"]["deny"]
            .as_array()
            .map(|rules| rules.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default();
        assert_eq!(deny.len(), DENIED_TOOLS.len());
        for rule in ["Bash(curl:*)", "Bash(git push:*)", "Read(~/.ssh/**)"] {
            assert!(deny.contains(&rule), "{rule} is not denied");
        }
        // Building and checking still need Bash itself.
        assert!(!deny.contains(&"Bash"));
        assert!(settings["sandbox"].is_null(), "no sandbox unless asked");
        Ok(())
    }

    #[test]
    fn sandbox_settings_confine_writes_and_close_the_network() -> Result<()> {
        let settings: Value = serde_json::from_str(&settings(true))?;
        let sandbox = &settings["sandbox"];
        assert_eq!(sandbox["enabled"], true);
        assert_eq!(sandbox["failIfUnavailable"], true);
        assert_eq!(sandbox["allowUnsandboxedCommands"], false);
        assert_eq!(sandbox["network"]["allowedDomains"], serde_json::json!([]));
        // The deny rules are still there.
        assert!(settings["permissions"]["deny"]
            .as_array()
            .is_some_and(|d| !d.is_empty()));
        Ok(())
    }
}