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            root: super::env_root("FACTORY_PROJECT_DIR"),
100        })
101    }
102
103    fn render_response(&self, verdict: Verdict) -> HookResponse {
104        if verdict.is_allowed() {
105            let reason = allow_reason(verdict);
106            // Droid mirrors Claude Code's hookSpecificOutput envelope.
107            let body = json!({
108                "hookSpecificOutput": {
109                    "hookEventName": "PreToolUse",
110                    "permissionDecision": "allow",
111                    "permissionDecisionReason": reason,
112                }
113            });
114            HookResponse {
115                stdout: serde_json::to_string(&body).unwrap_or_default(),
116                exit_code: 0,
117            }
118        } else {
119            HookResponse {
120                stdout: String::new(),
121                exit_code: 0,
122            }
123        }
124    }
125
126    fn render_context(&self, context: &str) -> HookResponse {
127        // Droid mirrors Claude Code's hookSpecificOutput envelope, including
128        // additionalContext (injects model-visible text, no permission decision).
129        let body = json!({
130            "hookSpecificOutput": {
131                "hookEventName": "PreToolUse",
132                "additionalContext": context,
133            }
134        });
135        HookResponse {
136            stdout: serde_json::to_string(&body).unwrap_or_default(),
137            exit_code: 0,
138        }
139    }
140}
141
142fn hook_entry(binary: &str) -> Value {
143    // Droid's bash tool name is `Execute`, not `Bash`. timeout is in
144    // seconds (different from Qwen/Gemini ms).
145    json!({
146        "matcher": "Execute",
147        "hooks": [{
148            "type": "command",
149            "command": binary,
150            "timeout": 60,
151        }]
152    })
153}
154
155fn has_safe_chains_hook(settings: &Value) -> bool {
156    settings
157        .get("hooks")
158        .and_then(|h| h.get("PreToolUse"))
159        .and_then(|arr| arr.as_array())
160        .is_some_and(|entries| {
161            entries.iter().any(|entry| {
162                entry
163                    .get("hooks")
164                    .and_then(|h| h.as_array())
165                    .is_some_and(|hooks| {
166                        hooks.iter().any(|hook| {
167                            hook.get("command")
168                                .and_then(|c| c.as_str())
169                                .is_some_and(|cmd| cmd.contains("safe-chains"))
170                        })
171                    })
172            })
173        })
174}
175
176fn add_hook(settings: &mut Value, binary: &str) {
177    if !settings.is_object() {
178        *settings = json!({});
179    }
180    let Some(obj) = settings.as_object_mut() else {
181        unreachable!("settings was just set to an object");
182    };
183    let hooks = obj
184        .entry("hooks")
185        .or_insert_with(|| json!({}))
186        .as_object_mut()
187        .expect("hooks key was created above as an object");
188    let pre_tool_use = hooks
189        .entry("PreToolUse")
190        .or_insert_with(|| json!([]))
191        .as_array_mut()
192        .expect("PreToolUse was created above as an array");
193    pre_tool_use.push(hook_entry(binary));
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::verdict::SafetyLevel;
200
201    fn target() -> DroidTarget {
202        DroidTarget
203    }
204
205    /// Verbatim shape from the Factory Droid hooks reference. Note
206    /// tool_name is "Execute", not "Bash".
207    const DROID_DOCS_SAMPLE: &str = r#"{
208        "session_id": "abc123",
209        "transcript_path": "/Users/me/.factory/projects/p/uuid.jsonl",
210        "cwd": "/Users/me/project",
211        "permission_mode": "off",
212        "hook_event_name": "PreToolUse",
213        "tool_name": "Execute",
214        "tool_input": {"command": "ls -la"}
215    }"#;
216
217    #[test]
218    fn install_no_factory_dir_skips() {
219        let dir = tempfile::tempdir().unwrap();
220        let outcome = target().install(dir.path()).unwrap();
221        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
222    }
223
224    #[test]
225    fn install_creates_settings_file() {
226        let dir = tempfile::tempdir().unwrap();
227        std::fs::create_dir(dir.path().join(".factory")).unwrap();
228        let outcome = target().install(dir.path()).unwrap();
229        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
230        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
231        let settings: Value = serde_json::from_str(&contents).unwrap();
232        assert!(has_safe_chains_hook(&settings));
233    }
234
235    #[test]
236    fn install_uses_execute_matcher_not_bash() {
237        // Droid's bash tool is `Execute` — wiring a `Bash` matcher
238        // wouldn't fire on shell calls.
239        let dir = tempfile::tempdir().unwrap();
240        std::fs::create_dir(dir.path().join(".factory")).unwrap();
241        target().install(dir.path()).unwrap();
242        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
243        assert!(contents.contains("\"matcher\": \"Execute\""));
244    }
245
246    #[test]
247    fn install_uses_absolute_path_to_binary() {
248        // Droid docs explicitly require absolute paths for hook
249        // commands. We resolve via env::current_exe.
250        let dir = tempfile::tempdir().unwrap();
251        std::fs::create_dir(dir.path().join(".factory")).unwrap();
252        target().install(dir.path()).unwrap();
253        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
254        let settings: Value = serde_json::from_str(&contents).unwrap();
255        let cmd = settings
256            .pointer("/hooks/PreToolUse/0/hooks/0/command")
257            .and_then(|s| s.as_str())
258            .unwrap_or("");
259        // Either an absolute path or the fallback bare invocation.
260        assert!(
261            cmd.starts_with('/') || cmd == "safe-chains hook droid",
262            "unexpected command: {cmd}",
263        );
264        assert!(cmd.ends_with(" hook droid") || cmd == "safe-chains hook droid");
265    }
266
267    #[test]
268    fn install_idempotent() {
269        let dir = tempfile::tempdir().unwrap();
270        std::fs::create_dir(dir.path().join(".factory")).unwrap();
271        target().install(dir.path()).unwrap();
272        let outcome = target().install(dir.path()).unwrap();
273        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
274    }
275
276    #[test]
277    fn parse_input_extracts_command() {
278        let parsed = DroidHookFormat.parse_input(DROID_DOCS_SAMPLE).unwrap();
279        assert_eq!(parsed.command, "ls -la");
280        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
281    }
282
283    #[test]
284    fn parse_input_rejects_garbage() {
285        assert!(DroidHookFormat.parse_input("not json").is_err());
286        assert!(DroidHookFormat.parse_input("{}").is_err());
287    }
288
289    #[test]
290    fn render_response_emits_claude_shaped_envelope() {
291        let r = DroidHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
292        let v: Value = serde_json::from_str(&r.stdout).unwrap();
293        assert_eq!(
294            v.pointer("/hookSpecificOutput/permissionDecision")
295                .and_then(|d| d.as_str()),
296            Some("allow"),
297        );
298    }
299
300    #[test]
301    fn render_response_deny_emits_empty_body() {
302        let r = DroidHookFormat.render_response(Verdict::Denied);
303        assert_eq!(r.stdout, "");
304    }
305}