Skip to main content

safe_chains/targets/
droid.rs

1use std::path::{Path, PathBuf};
2
3use serde::Deserialize;
4use serde_json::{Map, Value, json};
5
6use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target, allow_reason};
7use crate::verdict::Verdict;
8
9pub struct DroidTarget;
10
11impl Target for DroidTarget {
12    fn name(&self) -> &'static str {
13        "droid"
14    }
15
16    fn display_name(&self) -> &'static str {
17        "Factory Droid"
18    }
19
20    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
21        vec![home.join(".factory")]
22    }
23
24    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
25        let dir = home.join(".factory");
26        if !dir.exists() {
27            return Ok(InstallOutcome::Skipped {
28                reason: format!(
29                    "~/.factory not found at {} (Factory Droid not installed)",
30                    dir.display()
31                ),
32            });
33        }
34
35        let path = dir.join("settings.json");
36        // Droid docs require absolute paths for hook commands. We
37        // discover the absolute path of the running binary and embed
38        // it in the config; falls back to bare "safe-chains hook
39        // droid" if discovery fails (and the install message warns).
40        let resolved = std::env::current_exe()
41            .ok()
42            .and_then(|p| p.canonicalize().ok())
43            .map(|p| format!("{} hook droid", p.display()))
44            .unwrap_or_else(|| "safe-chains hook droid".to_string());
45        let binary = resolved.as_str();
46
47        if path.exists() {
48            let contents = std::fs::read_to_string(&path)
49                .map_err(|e| format!("Could not read {}: {e}", path.display()))?;
50            let mut settings: Value = serde_json::from_str(&contents)
51                .map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
52
53            if has_safe_chains_hook(&settings) {
54                return Ok(InstallOutcome::AlreadyConfigured { path });
55            }
56
57            add_hook(&mut settings, binary);
58            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
59            std::fs::write(&path, format!("{output}\n"))
60                .map_err(|e| format!("Could not write {}: {e}", path.display()))?;
61            Ok(InstallOutcome::Installed { path })
62        } else {
63            let mut settings = Value::Object(Map::new());
64            add_hook(&mut settings, binary);
65            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
66            std::fs::write(&path, format!("{output}\n"))
67                .map_err(|e| format!("Could not write {}: {e}", path.display()))?;
68            Ok(InstallOutcome::Installed { path })
69        }
70    }
71
72    fn hook_format(&self) -> Option<&dyn HookFormat> {
73        Some(&DroidHookFormat)
74    }
75}
76
77struct DroidHookFormat;
78
79#[derive(Deserialize)]
80struct ToolInput {
81    command: String,
82}
83
84#[derive(Deserialize)]
85struct DroidHookEnvelope {
86    tool_input: ToolInput,
87    #[serde(default)]
88    cwd: Option<String>,
89}
90
91impl HookFormat for DroidHookFormat {
92    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
93        let envelope: DroidHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError {
94            message: e.to_string(),
95        })?;
96        Ok(HookInput {
97            command: envelope.tool_input.command,
98            cwd: envelope.cwd,
99        })
100    }
101
102    fn render_response(&self, verdict: Verdict) -> HookResponse {
103        if verdict.is_allowed() {
104            let reason = allow_reason(verdict);
105            // Droid mirrors Claude Code's hookSpecificOutput envelope.
106            let body = json!({
107                "hookSpecificOutput": {
108                    "hookEventName": "PreToolUse",
109                    "permissionDecision": "allow",
110                    "permissionDecisionReason": reason,
111                }
112            });
113            HookResponse {
114                stdout: serde_json::to_string(&body).unwrap_or_default(),
115                exit_code: 0,
116            }
117        } else {
118            HookResponse {
119                stdout: String::new(),
120                exit_code: 0,
121            }
122        }
123    }
124
125    fn render_context(&self, context: &str) -> HookResponse {
126        // Droid mirrors Claude Code's hookSpecificOutput envelope, including
127        // additionalContext (injects model-visible text, no permission decision).
128        let body = json!({
129            "hookSpecificOutput": {
130                "hookEventName": "PreToolUse",
131                "additionalContext": context,
132            }
133        });
134        HookResponse {
135            stdout: serde_json::to_string(&body).unwrap_or_default(),
136            exit_code: 0,
137        }
138    }
139}
140
141fn hook_entry(binary: &str) -> Value {
142    // Droid's bash tool name is `Execute`, not `Bash`. timeout is in
143    // seconds (different from Qwen/Gemini ms).
144    json!({
145        "matcher": "Execute",
146        "hooks": [{
147            "type": "command",
148            "command": binary,
149            "timeout": 60,
150        }]
151    })
152}
153
154fn has_safe_chains_hook(settings: &Value) -> bool {
155    settings
156        .get("hooks")
157        .and_then(|h| h.get("PreToolUse"))
158        .and_then(|arr| arr.as_array())
159        .is_some_and(|entries| {
160            entries.iter().any(|entry| {
161                entry
162                    .get("hooks")
163                    .and_then(|h| h.as_array())
164                    .is_some_and(|hooks| {
165                        hooks.iter().any(|hook| {
166                            hook.get("command")
167                                .and_then(|c| c.as_str())
168                                .is_some_and(|cmd| cmd.contains("safe-chains"))
169                        })
170                    })
171            })
172        })
173}
174
175fn add_hook(settings: &mut Value, binary: &str) {
176    if !settings.is_object() {
177        *settings = json!({});
178    }
179    let Some(obj) = settings.as_object_mut() else {
180        unreachable!("settings was just set to an object");
181    };
182    let hooks = obj
183        .entry("hooks")
184        .or_insert_with(|| json!({}))
185        .as_object_mut()
186        .expect("hooks key was created above as an object");
187    let pre_tool_use = hooks
188        .entry("PreToolUse")
189        .or_insert_with(|| json!([]))
190        .as_array_mut()
191        .expect("PreToolUse was created above as an array");
192    pre_tool_use.push(hook_entry(binary));
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use crate::verdict::SafetyLevel;
199
200    fn target() -> DroidTarget {
201        DroidTarget
202    }
203
204    /// Verbatim shape from the Factory Droid hooks reference. Note
205    /// tool_name is "Execute", not "Bash".
206    const DROID_DOCS_SAMPLE: &str = r#"{
207        "session_id": "abc123",
208        "transcript_path": "/Users/me/.factory/projects/p/uuid.jsonl",
209        "cwd": "/Users/me/project",
210        "permission_mode": "off",
211        "hook_event_name": "PreToolUse",
212        "tool_name": "Execute",
213        "tool_input": {"command": "ls -la"}
214    }"#;
215
216    #[test]
217    fn install_no_factory_dir_skips() {
218        let dir = tempfile::tempdir().unwrap();
219        let outcome = target().install(dir.path()).unwrap();
220        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
221    }
222
223    #[test]
224    fn install_creates_settings_file() {
225        let dir = tempfile::tempdir().unwrap();
226        std::fs::create_dir(dir.path().join(".factory")).unwrap();
227        let outcome = target().install(dir.path()).unwrap();
228        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
229        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
230        let settings: Value = serde_json::from_str(&contents).unwrap();
231        assert!(has_safe_chains_hook(&settings));
232    }
233
234    #[test]
235    fn install_uses_execute_matcher_not_bash() {
236        // Droid's bash tool is `Execute` — wiring a `Bash` matcher
237        // wouldn't fire on shell calls.
238        let dir = tempfile::tempdir().unwrap();
239        std::fs::create_dir(dir.path().join(".factory")).unwrap();
240        target().install(dir.path()).unwrap();
241        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
242        assert!(contents.contains("\"matcher\": \"Execute\""));
243    }
244
245    #[test]
246    fn install_uses_absolute_path_to_binary() {
247        // Droid docs explicitly require absolute paths for hook
248        // commands. We resolve via env::current_exe.
249        let dir = tempfile::tempdir().unwrap();
250        std::fs::create_dir(dir.path().join(".factory")).unwrap();
251        target().install(dir.path()).unwrap();
252        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
253        let settings: Value = serde_json::from_str(&contents).unwrap();
254        let cmd = settings
255            .pointer("/hooks/PreToolUse/0/hooks/0/command")
256            .and_then(|s| s.as_str())
257            .unwrap_or("");
258        // Either an absolute path or the fallback bare invocation.
259        assert!(
260            cmd.starts_with('/') || cmd == "safe-chains hook droid",
261            "unexpected command: {cmd}",
262        );
263        assert!(cmd.ends_with(" hook droid") || cmd == "safe-chains hook droid");
264    }
265
266    #[test]
267    fn install_idempotent() {
268        let dir = tempfile::tempdir().unwrap();
269        std::fs::create_dir(dir.path().join(".factory")).unwrap();
270        target().install(dir.path()).unwrap();
271        let outcome = target().install(dir.path()).unwrap();
272        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
273    }
274
275    #[test]
276    fn parse_input_extracts_command() {
277        let parsed = DroidHookFormat.parse_input(DROID_DOCS_SAMPLE).unwrap();
278        assert_eq!(parsed.command, "ls -la");
279        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
280    }
281
282    #[test]
283    fn parse_input_rejects_garbage() {
284        assert!(DroidHookFormat.parse_input("not json").is_err());
285        assert!(DroidHookFormat.parse_input("{}").is_err());
286    }
287
288    #[test]
289    fn render_response_emits_claude_shaped_envelope() {
290        let r = DroidHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
291        let v: Value = serde_json::from_str(&r.stdout).unwrap();
292        assert_eq!(
293            v.pointer("/hookSpecificOutput/permissionDecision")
294                .and_then(|d| d.as_str()),
295            Some("allow"),
296        );
297    }
298
299    #[test]
300    fn render_response_deny_emits_empty_body() {
301        let r = DroidHookFormat.render_response(Verdict::Denied);
302        assert_eq!(r.stdout, "");
303    }
304}