safe-chains 0.243.0

Auto-allow safe bash commands in agentic coding tools
Documentation
use std::path::{Path, PathBuf};

use serde::Deserialize;
use serde_json::{Map, Value, json};

use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target, allow_reason};
use crate::verdict::Verdict;

pub struct DroidTarget;

impl Target for DroidTarget {
    fn name(&self) -> &'static str {
        "droid"
    }

    fn display_name(&self) -> &'static str {
        "Factory Droid"
    }

    #[cfg(test)]
    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
        Some(format!(r#"{{"tool_name":"{tool}","tool_input":{{"command":"{command}"}}}}"#))
    }

    fn shell_tool_name(&self) -> &'static str {
        "Execute" // droid's shell tool is not `Bash`
    }

    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
        vec![home.join(".factory")]
    }

    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
        let exe = std::env::current_exe().ok().and_then(|p| p.canonicalize().ok());
        self.install_with(home, exe.as_deref())
    }

    fn hook_format(&self) -> Option<&dyn HookFormat> {
        Some(&DroidHookFormat)
    }
}

impl DroidTarget {
    /// `install`'s body with the hook binary's path injected: the real install passes the
    /// canonicalized `current_exe` (falling back to the bare invocation when discovery fails),
    /// while the tests pass a fixed path — under `cargo test` the running binary is
    /// `safe_chains-<hash>`, which `has_safe_chains_hook` only recognizes when some directory in
    /// the checkout's path is literally named "safe-chains".
    fn install_with(&self, home: &Path, exe: Option<&Path>) -> Result<InstallOutcome, String> {
        let dir = home.join(".factory");
        if !dir.exists() {
            return Ok(InstallOutcome::Skipped {
                reason: format!("~/.factory not found at {} (Factory Droid not installed)", dir.display()),
            });
        }

        let hooks_path = dir.join("hooks.json");
        let settings_path = dir.join("settings.json");
        let standalone = hooks_path.exists();
        let path = if standalone { hooks_path } else { settings_path };
        let resolved = exe
            .map(|p| format!("{} hook droid", p.display()))
            .unwrap_or_else(|| "safe-chains hook droid".to_string());
        let binary = resolved.as_str();

        if path.exists() {
            let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
            let mut settings: Value = serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?;

            if has_safe_chains_hook(&settings, standalone) {
                return Ok(InstallOutcome::AlreadyConfigured { path });
            }

            add_hook(&mut settings, binary, standalone)?;
            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
            Ok(InstallOutcome::Installed { path })
        } else {
            let mut settings = Value::Object(Map::new());
            add_hook(&mut settings, binary, false)?;
            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
            Ok(InstallOutcome::Installed { path })
        }
    }
}

struct DroidHookFormat;

#[derive(Deserialize)]
struct ToolInput {
    command: String,
}

#[derive(Deserialize)]
struct DroidHookEnvelope {
    /// Optional so a harness that omits it still works; when present and naming another tool we
    /// abstain (see parse_input).
    #[serde(default)]
    tool_name: Option<String>,
    tool_input: ToolInput,
    #[serde(default)]
    cwd: Option<String>,
}

impl HookFormat for DroidHookFormat {
    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
        let envelope: DroidHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
        // Self-filter on the tool: the hook can be delivered for a non-shell call by a
        // hand-edited matcher, and deciding on one grants or vetoes a tool never analysed.
        if let Some(name) = &envelope.tool_name
            && name != "Execute"
        {
            return Err(ParseError { message: format!("not a shell tool: {name}") });
        }
        Ok(HookInput {
            command: envelope.tool_input.command,
            cwd: envelope.cwd,
            root: super::env_root("FACTORY_PROJECT_DIR"),
            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
            session_id: None,
            permission_mode: None,
        })
    }

    fn decision_pointer(&self) -> &'static str {
        "/hookSpecificOutput/permissionDecision" // mirrors Claude's nesting
    }

    fn render_response(&self, verdict: Verdict) -> HookResponse {
        if verdict.is_allowed() {
            let reason = allow_reason(verdict);
            // Droid mirrors Claude Code's hookSpecificOutput envelope.
            let body = json!({
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "allow",
                    "permissionDecisionReason": reason,
                }
            });
            HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
        } else {
            HookResponse { stdout: String::new(), exit_code: 0 }
        }
    }

    fn render_context(&self, context: &str) -> HookResponse {
        // Droid mirrors Claude Code's hookSpecificOutput envelope, including
        // additionalContext (injects model-visible text, no permission decision).
        let body = json!({
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "additionalContext": context,
            }
        });
        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
    }
}

fn hook_entry(binary: &str) -> Value {
    // Droid's bash tool name is `Execute`, not `Bash`. timeout is in
    // seconds (different from Qwen/Gemini ms).
    json!({
        "matcher": "Execute",
        "hooks": [{
            "type": "command",
            "command": binary,
            "timeout": 60,
        }]
    })
}

fn has_safe_chains_hook(settings: &Value, standalone: bool) -> bool {
    let events = if standalone { Some(settings) } else { settings.get("hooks") };
    events.and_then(|h| h.get("PreToolUse")).and_then(|arr| arr.as_array()).is_some_and(|entries| {
        entries.iter().any(|entry| {
            entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
                hooks
                    .iter()
                    .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
            })
        })
    })
}

fn add_hook(settings: &mut Value, binary: &str, standalone: bool) -> Result<(), String> {
    if !standalone || !settings.is_object() {
        return super::append_hook_entry(settings, "hooks", "PreToolUse", hook_entry(binary));
    }
    if let Some(slot) = settings.get("PreToolUse")
        && !slot.is_array()
    {
        return Err(format!("`PreToolUse` is {}, expected an array. Leaving the file unchanged.", super::json_kind(slot)));
    }
    let mut wrapper = json!({ "hooks": std::mem::take(settings) });
    super::append_hook_entry(&mut wrapper, "hooks", "PreToolUse", hook_entry(binary))?;
    *settings = wrapper["hooks"].take();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::verdict::SafetyLevel;

    fn target() -> DroidTarget {
        DroidTarget
    }

    /// Fixed hook-binary path for the install tests, so they pass wherever the checkout lives:
    /// under `cargo test` the running binary is `safe_chains-<hash>`, which `has_safe_chains_hook`
    /// only recognizes when some directory in the checkout's path is literally named
    /// "safe-chains".
    const EXE: &str = "/opt/homebrew/bin/safe-chains";

    /// Verbatim shape from the Factory Droid hooks reference. Note
    /// tool_name is "Execute", not "Bash".
    const DROID_DOCS_SAMPLE: &str = r#"{
        "session_id": "abc123",
        "transcript_path": "/Users/me/.factory/projects/p/uuid.jsonl",
        "cwd": "/Users/me/project",
        "permission_mode": "off",
        "hook_event_name": "PreToolUse",
        "tool_name": "Execute",
        "tool_input": {"command": "ls -la"}
    }"#;

    #[test]
    fn install_no_factory_dir_skips() {
        let dir = tempfile::tempdir().unwrap();
        let outcome = target().install(dir.path()).unwrap();
        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
    }

    #[test]
    fn install_creates_settings_file() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
        let settings: Value = serde_json::from_str(&contents).unwrap();
        assert!(has_safe_chains_hook(&settings, false));
    }

    #[test]
    fn install_goes_into_hooks_json_when_that_file_exists() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        std::fs::write(dir.path().join(".factory/hooks.json"), "{}\n").unwrap();
        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        assert!(matches!(outcome, InstallOutcome::Installed { ref path } if path.ends_with("hooks.json")));
        let contents = std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap();
        let file: Value = serde_json::from_str(&contents).unwrap();
        assert_eq!(file.pointer("/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Execute"));
        assert!(file.get("hooks").is_none());
        assert!(!dir.path().join(".factory/settings.json").exists());
    }

    #[test]
    fn install_is_idempotent_in_hooks_json() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        std::fs::write(dir.path().join(".factory/hooks.json"), "{}\n").unwrap();
        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        let again = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        assert!(matches!(again, InstallOutcome::AlreadyConfigured { .. }));
    }

    #[test]
    fn install_keeps_other_events_in_hooks_json() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        std::fs::write(dir.path().join(".factory/hooks.json"), r#"{"Stop":[{"hooks":[{"type":"command","command":"/bin/true"}]}]}"#)
            .unwrap();
        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
        assert!(file.pointer("/Stop/0").is_some());
        assert!(file.pointer("/PreToolUse/0").is_some());
    }

    #[test]
    fn install_appends_after_existing_pre_tool_use_in_hooks_json() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        std::fs::write(
            dir.path().join(".factory/hooks.json"),
            r#"{"PreToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"/bin/true"}]}]}"#,
        )
        .unwrap();
        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
        assert_eq!(file.pointer("/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Edit"));
        assert_eq!(file.pointer("/PreToolUse/1/matcher").and_then(|m| m.as_str()), Some("Execute"));
        assert!(file.pointer("/PreToolUse/2").is_none());
    }

    #[test]
    fn install_into_hooks_json_leaves_settings_json_alone() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        let settings = r#"{"model":"x","hooks":{"Stop":[]}}"#;
        std::fs::write(dir.path().join(".factory/settings.json"), settings).unwrap();
        std::fs::write(dir.path().join(".factory/hooks.json"), "{}").unwrap();
        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        assert_eq!(std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap(), settings);
        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
        assert!(file.pointer("/PreToolUse/0").is_some());
    }

    #[test]
    fn install_refuses_unparseable_hooks_json_and_writes_nothing() {
        for contents in ["", "{not json", "[1,2]", r#"{"PreToolUse":"x"}"#] {
            let dir = tempfile::tempdir().unwrap();
            std::fs::create_dir(dir.path().join(".factory")).unwrap();
            std::fs::write(dir.path().join(".factory/hooks.json"), contents).unwrap();
            let Err(err) = target().install_with(dir.path(), Some(Path::new(EXE))) else {
                panic!("{contents:?} was accepted");
            };
            assert_eq!(std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap(), contents);
            assert!(!dir.path().join(".factory/settings.json").exists(), "{contents:?}");
            assert!(!err.contains("`hooks"), "{contents:?}: {err}");
        }
    }

    #[test]
    fn install_uses_execute_matcher_not_bash() {
        // Droid's bash tool is `Execute` — wiring a `Bash` matcher
        // wouldn't fire on shell calls.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        target().install(dir.path()).unwrap();
        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
        assert!(contents.contains("\"matcher\": \"Execute\""));
    }

    #[test]
    fn install_uses_absolute_path_to_binary() {
        // Droid docs explicitly require absolute paths for hook
        // commands. We resolve via env::current_exe.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        target().install(dir.path()).unwrap();
        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
        let settings: Value = serde_json::from_str(&contents).unwrap();
        let cmd = settings.pointer("/hooks/PreToolUse/0/hooks/0/command").and_then(|s| s.as_str()).unwrap_or("");
        // Either an absolute path or the fallback bare invocation.
        assert!(cmd.starts_with('/') || cmd == "safe-chains hook droid", "unexpected command: {cmd}",);
        assert!(cmd.ends_with(" hook droid") || cmd == "safe-chains hook droid");
    }

    #[test]
    fn install_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
    }

    #[test]
    fn install_idempotent_outside_a_safe_chains_directory() {
        // The regression this file's fix is for: detection must survive a binary path in which no
        // DIRECTORY is named "safe-chains" — the FILE name alone carries it. Under `cargo test`
        // the running binary is `safe_chains-<hash>` (underscore), so the real install only
        // round-tripped when the checkout itself sat inside a "safe-chains" directory.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".factory")).unwrap();
        let exe = Path::new("/usr/local/bin/safe-chains");
        let first = target().install_with(dir.path(), Some(exe)).unwrap();
        assert!(matches!(first, InstallOutcome::Installed { .. }));
        let second = target().install_with(dir.path(), Some(exe)).unwrap();
        assert!(matches!(second, InstallOutcome::AlreadyConfigured { .. }));
    }

    #[test]
    fn parse_input_extracts_command() {
        let parsed = DroidHookFormat.parse_input(DROID_DOCS_SAMPLE).unwrap();
        assert_eq!(parsed.command, "ls -la");
        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
    }

    #[test]
    fn parse_input_rejects_garbage() {
        assert!(DroidHookFormat.parse_input("not json").is_err());
        assert!(DroidHookFormat.parse_input("{}").is_err());
    }

    #[test]
    fn render_response_emits_claude_shaped_envelope() {
        let r = DroidHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
        let v: Value = serde_json::from_str(&r.stdout).unwrap();
        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("allow"),);
    }

    #[test]
    fn render_response_deny_emits_empty_body() {
        let r = DroidHookFormat.render_response(Verdict::Denied);
        assert_eq!(r.stdout, "");
    }
}