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    #[cfg(test)]
21    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
22        Some(format!(r#"{{"tool_name":"{tool}","tool_input":{{"command":"{command}"}}}}"#))
23    }
24
25    fn shell_tool_name(&self) -> &'static str {
26        "Execute" // droid's shell tool is not `Bash`
27    }
28
29    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
30        vec![home.join(".factory")]
31    }
32
33    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
34        let exe = std::env::current_exe().ok().and_then(|p| p.canonicalize().ok());
35        self.install_with(home, exe.as_deref())
36    }
37
38    fn hook_format(&self) -> Option<&dyn HookFormat> {
39        Some(&DroidHookFormat)
40    }
41}
42
43impl DroidTarget {
44    /// `install`'s body with the hook binary's path injected: the real install passes the
45    /// canonicalized `current_exe` (falling back to the bare invocation when discovery fails),
46    /// while the tests pass a fixed path — under `cargo test` the running binary is
47    /// `safe_chains-<hash>`, which `has_safe_chains_hook` only recognizes when some directory in
48    /// the checkout's path is literally named "safe-chains".
49    fn install_with(&self, home: &Path, exe: Option<&Path>) -> Result<InstallOutcome, String> {
50        let dir = home.join(".factory");
51        if !dir.exists() {
52            return Ok(InstallOutcome::Skipped {
53                reason: format!("~/.factory not found at {} (Factory Droid not installed)", dir.display()),
54            });
55        }
56
57        let hooks_path = dir.join("hooks.json");
58        let settings_path = dir.join("settings.json");
59        let standalone = hooks_path.exists();
60        let path = if standalone { hooks_path } else { settings_path };
61        let resolved = exe
62            .map(|p| format!("{} hook droid", p.display()))
63            .unwrap_or_else(|| "safe-chains hook droid".to_string());
64        let binary = resolved.as_str();
65
66        if path.exists() {
67            let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
68            let mut settings: Value = serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
69
70            if has_safe_chains_hook(&settings, standalone) {
71                return Ok(InstallOutcome::AlreadyConfigured { path });
72            }
73
74            add_hook(&mut settings, binary, standalone)?;
75            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
76            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
77            Ok(InstallOutcome::Installed { path })
78        } else {
79            let mut settings = Value::Object(Map::new());
80            add_hook(&mut settings, binary, false)?;
81            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
82            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
83            Ok(InstallOutcome::Installed { path })
84        }
85    }
86}
87
88struct DroidHookFormat;
89
90#[derive(Deserialize)]
91struct ToolInput {
92    command: String,
93}
94
95#[derive(Deserialize)]
96struct DroidHookEnvelope {
97    /// Optional so a harness that omits it still works; when present and naming another tool we
98    /// abstain (see parse_input).
99    #[serde(default)]
100    tool_name: Option<String>,
101    tool_input: ToolInput,
102    #[serde(default)]
103    cwd: Option<String>,
104}
105
106impl HookFormat for DroidHookFormat {
107    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
108        let envelope: DroidHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
109        // Self-filter on the tool: the hook can be delivered for a non-shell call by a
110        // hand-edited matcher, and deciding on one grants or vetoes a tool never analysed.
111        if let Some(name) = &envelope.tool_name
112            && name != "Execute"
113        {
114            return Err(ParseError { message: format!("not a shell tool: {name}") });
115        }
116        Ok(HookInput {
117            command: envelope.tool_input.command,
118            cwd: envelope.cwd,
119            root: super::env_root("FACTORY_PROJECT_DIR"),
120            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
121            session_id: None,
122            permission_mode: None,
123        })
124    }
125
126    fn decision_pointer(&self) -> &'static str {
127        "/hookSpecificOutput/permissionDecision" // mirrors Claude's nesting
128    }
129
130    fn render_response(&self, verdict: Verdict) -> HookResponse {
131        if verdict.is_allowed() {
132            let reason = allow_reason(verdict);
133            // Droid mirrors Claude Code's hookSpecificOutput envelope.
134            let body = json!({
135                "hookSpecificOutput": {
136                    "hookEventName": "PreToolUse",
137                    "permissionDecision": "allow",
138                    "permissionDecisionReason": reason,
139                }
140            });
141            HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
142        } else {
143            HookResponse { stdout: String::new(), exit_code: 0 }
144        }
145    }
146
147    fn render_context(&self, context: &str) -> HookResponse {
148        // Droid mirrors Claude Code's hookSpecificOutput envelope, including
149        // additionalContext (injects model-visible text, no permission decision).
150        let body = json!({
151            "hookSpecificOutput": {
152                "hookEventName": "PreToolUse",
153                "additionalContext": context,
154            }
155        });
156        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
157    }
158}
159
160fn hook_entry(binary: &str) -> Value {
161    // Droid's bash tool name is `Execute`, not `Bash`. timeout is in
162    // seconds (different from Qwen/Gemini ms).
163    json!({
164        "matcher": "Execute",
165        "hooks": [{
166            "type": "command",
167            "command": binary,
168            "timeout": 60,
169        }]
170    })
171}
172
173fn has_safe_chains_hook(settings: &Value, standalone: bool) -> bool {
174    let events = if standalone { Some(settings) } else { settings.get("hooks") };
175    events.and_then(|h| h.get("PreToolUse")).and_then(|arr| arr.as_array()).is_some_and(|entries| {
176        entries.iter().any(|entry| {
177            entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
178                hooks
179                    .iter()
180                    .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
181            })
182        })
183    })
184}
185
186fn add_hook(settings: &mut Value, binary: &str, standalone: bool) -> Result<(), String> {
187    if !standalone || !settings.is_object() {
188        return super::append_hook_entry(settings, "hooks", "PreToolUse", hook_entry(binary));
189    }
190    if let Some(slot) = settings.get("PreToolUse")
191        && !slot.is_array()
192    {
193        return Err(format!("`PreToolUse` is {}, expected an array. Leaving the file unchanged.", super::json_kind(slot)));
194    }
195    let mut wrapper = json!({ "hooks": std::mem::take(settings) });
196    super::append_hook_entry(&mut wrapper, "hooks", "PreToolUse", hook_entry(binary))?;
197    *settings = wrapper["hooks"].take();
198    Ok(())
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use crate::verdict::SafetyLevel;
205
206    fn target() -> DroidTarget {
207        DroidTarget
208    }
209
210    /// Fixed hook-binary path for the install tests, so they pass wherever the checkout lives:
211    /// under `cargo test` the running binary is `safe_chains-<hash>`, which `has_safe_chains_hook`
212    /// only recognizes when some directory in the checkout's path is literally named
213    /// "safe-chains".
214    const EXE: &str = "/opt/homebrew/bin/safe-chains";
215
216    /// Verbatim shape from the Factory Droid hooks reference. Note
217    /// tool_name is "Execute", not "Bash".
218    const DROID_DOCS_SAMPLE: &str = r#"{
219        "session_id": "abc123",
220        "transcript_path": "/Users/me/.factory/projects/p/uuid.jsonl",
221        "cwd": "/Users/me/project",
222        "permission_mode": "off",
223        "hook_event_name": "PreToolUse",
224        "tool_name": "Execute",
225        "tool_input": {"command": "ls -la"}
226    }"#;
227
228    #[test]
229    fn install_no_factory_dir_skips() {
230        let dir = tempfile::tempdir().unwrap();
231        let outcome = target().install(dir.path()).unwrap();
232        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
233    }
234
235    #[test]
236    fn install_creates_settings_file() {
237        let dir = tempfile::tempdir().unwrap();
238        std::fs::create_dir(dir.path().join(".factory")).unwrap();
239        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
240        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
241        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
242        let settings: Value = serde_json::from_str(&contents).unwrap();
243        assert!(has_safe_chains_hook(&settings, false));
244    }
245
246    #[test]
247    fn install_goes_into_hooks_json_when_that_file_exists() {
248        let dir = tempfile::tempdir().unwrap();
249        std::fs::create_dir(dir.path().join(".factory")).unwrap();
250        std::fs::write(dir.path().join(".factory/hooks.json"), "{}\n").unwrap();
251        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
252        assert!(matches!(outcome, InstallOutcome::Installed { ref path } if path.ends_with("hooks.json")));
253        let contents = std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap();
254        let file: Value = serde_json::from_str(&contents).unwrap();
255        assert_eq!(file.pointer("/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Execute"));
256        assert!(file.get("hooks").is_none());
257        assert!(!dir.path().join(".factory/settings.json").exists());
258    }
259
260    #[test]
261    fn install_is_idempotent_in_hooks_json() {
262        let dir = tempfile::tempdir().unwrap();
263        std::fs::create_dir(dir.path().join(".factory")).unwrap();
264        std::fs::write(dir.path().join(".factory/hooks.json"), "{}\n").unwrap();
265        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
266        let again = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
267        assert!(matches!(again, InstallOutcome::AlreadyConfigured { .. }));
268    }
269
270    #[test]
271    fn install_keeps_other_events_in_hooks_json() {
272        let dir = tempfile::tempdir().unwrap();
273        std::fs::create_dir(dir.path().join(".factory")).unwrap();
274        std::fs::write(dir.path().join(".factory/hooks.json"), r#"{"Stop":[{"hooks":[{"type":"command","command":"/bin/true"}]}]}"#)
275            .unwrap();
276        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
277        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
278        assert!(file.pointer("/Stop/0").is_some());
279        assert!(file.pointer("/PreToolUse/0").is_some());
280    }
281
282    #[test]
283    fn install_appends_after_existing_pre_tool_use_in_hooks_json() {
284        let dir = tempfile::tempdir().unwrap();
285        std::fs::create_dir(dir.path().join(".factory")).unwrap();
286        std::fs::write(
287            dir.path().join(".factory/hooks.json"),
288            r#"{"PreToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"/bin/true"}]}]}"#,
289        )
290        .unwrap();
291        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
292        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
293        assert_eq!(file.pointer("/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Edit"));
294        assert_eq!(file.pointer("/PreToolUse/1/matcher").and_then(|m| m.as_str()), Some("Execute"));
295        assert!(file.pointer("/PreToolUse/2").is_none());
296    }
297
298    #[test]
299    fn install_into_hooks_json_leaves_settings_json_alone() {
300        let dir = tempfile::tempdir().unwrap();
301        std::fs::create_dir(dir.path().join(".factory")).unwrap();
302        let settings = r#"{"model":"x","hooks":{"Stop":[]}}"#;
303        std::fs::write(dir.path().join(".factory/settings.json"), settings).unwrap();
304        std::fs::write(dir.path().join(".factory/hooks.json"), "{}").unwrap();
305        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
306        assert_eq!(std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap(), settings);
307        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
308        assert!(file.pointer("/PreToolUse/0").is_some());
309    }
310
311    #[test]
312    fn install_refuses_unparseable_hooks_json_and_writes_nothing() {
313        for contents in ["", "{not json", "[1,2]", r#"{"PreToolUse":"x"}"#] {
314            let dir = tempfile::tempdir().unwrap();
315            std::fs::create_dir(dir.path().join(".factory")).unwrap();
316            std::fs::write(dir.path().join(".factory/hooks.json"), contents).unwrap();
317            let Err(err) = target().install_with(dir.path(), Some(Path::new(EXE))) else {
318                panic!("{contents:?} was accepted");
319            };
320            assert_eq!(std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap(), contents);
321            assert!(!dir.path().join(".factory/settings.json").exists(), "{contents:?}");
322            assert!(!err.contains("`hooks"), "{contents:?}: {err}");
323        }
324    }
325
326    #[test]
327    fn install_uses_execute_matcher_not_bash() {
328        // Droid's bash tool is `Execute` — wiring a `Bash` matcher
329        // wouldn't fire on shell calls.
330        let dir = tempfile::tempdir().unwrap();
331        std::fs::create_dir(dir.path().join(".factory")).unwrap();
332        target().install(dir.path()).unwrap();
333        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
334        assert!(contents.contains("\"matcher\": \"Execute\""));
335    }
336
337    #[test]
338    fn install_uses_absolute_path_to_binary() {
339        // Droid docs explicitly require absolute paths for hook
340        // commands. We resolve via env::current_exe.
341        let dir = tempfile::tempdir().unwrap();
342        std::fs::create_dir(dir.path().join(".factory")).unwrap();
343        target().install(dir.path()).unwrap();
344        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
345        let settings: Value = serde_json::from_str(&contents).unwrap();
346        let cmd = settings.pointer("/hooks/PreToolUse/0/hooks/0/command").and_then(|s| s.as_str()).unwrap_or("");
347        // Either an absolute path or the fallback bare invocation.
348        assert!(cmd.starts_with('/') || cmd == "safe-chains hook droid", "unexpected command: {cmd}",);
349        assert!(cmd.ends_with(" hook droid") || cmd == "safe-chains hook droid");
350    }
351
352    #[test]
353    fn install_idempotent() {
354        let dir = tempfile::tempdir().unwrap();
355        std::fs::create_dir(dir.path().join(".factory")).unwrap();
356        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
357        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
358        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
359    }
360
361    #[test]
362    fn install_idempotent_outside_a_safe_chains_directory() {
363        // The regression this file's fix is for: detection must survive a binary path in which no
364        // DIRECTORY is named "safe-chains" — the FILE name alone carries it. Under `cargo test`
365        // the running binary is `safe_chains-<hash>` (underscore), so the real install only
366        // round-tripped when the checkout itself sat inside a "safe-chains" directory.
367        let dir = tempfile::tempdir().unwrap();
368        std::fs::create_dir(dir.path().join(".factory")).unwrap();
369        let exe = Path::new("/usr/local/bin/safe-chains");
370        let first = target().install_with(dir.path(), Some(exe)).unwrap();
371        assert!(matches!(first, InstallOutcome::Installed { .. }));
372        let second = target().install_with(dir.path(), Some(exe)).unwrap();
373        assert!(matches!(second, InstallOutcome::AlreadyConfigured { .. }));
374    }
375
376    #[test]
377    fn parse_input_extracts_command() {
378        let parsed = DroidHookFormat.parse_input(DROID_DOCS_SAMPLE).unwrap();
379        assert_eq!(parsed.command, "ls -la");
380        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
381    }
382
383    #[test]
384    fn parse_input_rejects_garbage() {
385        assert!(DroidHookFormat.parse_input("not json").is_err());
386        assert!(DroidHookFormat.parse_input("{}").is_err());
387    }
388
389    #[test]
390    fn render_response_emits_claude_shaped_envelope() {
391        let r = DroidHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
392        let v: Value = serde_json::from_str(&r.stdout).unwrap();
393        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("allow"),);
394    }
395
396    #[test]
397    fn render_response_deny_emits_empty_body() {
398        let r = DroidHookFormat.render_response(Verdict::Denied);
399        assert_eq!(r.stdout, "");
400    }
401}