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            cwd_declared: false,
120            root: super::env_root("FACTORY_PROJECT_DIR"),
121            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
122            session_id: None,
123            permission_mode: None,
124        })
125    }
126
127    fn decision_pointer(&self) -> &'static str {
128        "/hookSpecificOutput/permissionDecision" // mirrors Claude's nesting
129    }
130
131    fn render_response(&self, verdict: Verdict) -> HookResponse {
132        if verdict.is_allowed() {
133            let reason = allow_reason(verdict);
134            // Droid mirrors Claude Code's hookSpecificOutput envelope.
135            let body = json!({
136                "hookSpecificOutput": {
137                    "hookEventName": "PreToolUse",
138                    "permissionDecision": "allow",
139                    "permissionDecisionReason": reason,
140                }
141            });
142            HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
143        } else {
144            HookResponse { stdout: String::new(), exit_code: 0 }
145        }
146    }
147
148    fn render_context(&self, context: &str) -> HookResponse {
149        // Droid mirrors Claude Code's hookSpecificOutput envelope, including
150        // additionalContext (injects model-visible text, no permission decision).
151        let body = json!({
152            "hookSpecificOutput": {
153                "hookEventName": "PreToolUse",
154                "additionalContext": context,
155            }
156        });
157        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
158    }
159}
160
161fn hook_entry(binary: &str) -> Value {
162    // Droid's bash tool name is `Execute`, not `Bash`. timeout is in
163    // seconds (different from Qwen/Gemini ms).
164    json!({
165        "matcher": "Execute",
166        "hooks": [{
167            "type": "command",
168            "command": binary,
169            "timeout": 60,
170        }]
171    })
172}
173
174fn has_safe_chains_hook(settings: &Value, standalone: bool) -> bool {
175    let events = if standalone { Some(settings) } else { settings.get("hooks") };
176    events.and_then(|h| h.get("PreToolUse")).and_then(|arr| arr.as_array()).is_some_and(|entries| {
177        entries.iter().any(|entry| {
178            entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
179                hooks
180                    .iter()
181                    .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
182            })
183        })
184    })
185}
186
187fn add_hook(settings: &mut Value, binary: &str, standalone: bool) -> Result<(), String> {
188    if !standalone || !settings.is_object() {
189        return super::append_hook_entry(settings, "hooks", "PreToolUse", hook_entry(binary));
190    }
191    if let Some(slot) = settings.get("PreToolUse")
192        && !slot.is_array()
193    {
194        return Err(format!("`PreToolUse` is {}, expected an array. Leaving the file unchanged.", super::json_kind(slot)));
195    }
196    let mut wrapper = json!({ "hooks": std::mem::take(settings) });
197    super::append_hook_entry(&mut wrapper, "hooks", "PreToolUse", hook_entry(binary))?;
198    *settings = wrapper["hooks"].take();
199    Ok(())
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use crate::verdict::SafetyLevel;
206
207    fn target() -> DroidTarget {
208        DroidTarget
209    }
210
211    /// Fixed hook-binary path for the install tests, so they pass wherever the checkout lives:
212    /// under `cargo test` the running binary is `safe_chains-<hash>`, which `has_safe_chains_hook`
213    /// only recognizes when some directory in the checkout's path is literally named
214    /// "safe-chains".
215    const EXE: &str = "/opt/homebrew/bin/safe-chains";
216
217    /// Verbatim shape from the Factory Droid hooks reference. Note
218    /// tool_name is "Execute", not "Bash".
219    const DROID_DOCS_SAMPLE: &str = r#"{
220        "session_id": "abc123",
221        "transcript_path": "/Users/me/.factory/projects/p/uuid.jsonl",
222        "cwd": "/Users/me/project",
223        "permission_mode": "off",
224        "hook_event_name": "PreToolUse",
225        "tool_name": "Execute",
226        "tool_input": {"command": "ls -la"}
227    }"#;
228
229    #[test]
230    fn install_no_factory_dir_skips() {
231        let dir = tempfile::tempdir().unwrap();
232        let outcome = target().install(dir.path()).unwrap();
233        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
234    }
235
236    #[test]
237    fn install_creates_settings_file() {
238        let dir = tempfile::tempdir().unwrap();
239        std::fs::create_dir(dir.path().join(".factory")).unwrap();
240        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
241        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
242        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
243        let settings: Value = serde_json::from_str(&contents).unwrap();
244        assert!(has_safe_chains_hook(&settings, false));
245    }
246
247    #[test]
248    fn install_goes_into_hooks_json_when_that_file_exists() {
249        let dir = tempfile::tempdir().unwrap();
250        std::fs::create_dir(dir.path().join(".factory")).unwrap();
251        std::fs::write(dir.path().join(".factory/hooks.json"), "{}\n").unwrap();
252        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
253        assert!(matches!(outcome, InstallOutcome::Installed { ref path } if path.ends_with("hooks.json")));
254        let contents = std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap();
255        let file: Value = serde_json::from_str(&contents).unwrap();
256        assert_eq!(file.pointer("/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Execute"));
257        assert!(file.get("hooks").is_none());
258        assert!(!dir.path().join(".factory/settings.json").exists());
259    }
260
261    #[test]
262    fn install_is_idempotent_in_hooks_json() {
263        let dir = tempfile::tempdir().unwrap();
264        std::fs::create_dir(dir.path().join(".factory")).unwrap();
265        std::fs::write(dir.path().join(".factory/hooks.json"), "{}\n").unwrap();
266        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
267        let again = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
268        assert!(matches!(again, InstallOutcome::AlreadyConfigured { .. }));
269    }
270
271    #[test]
272    fn install_keeps_other_events_in_hooks_json() {
273        let dir = tempfile::tempdir().unwrap();
274        std::fs::create_dir(dir.path().join(".factory")).unwrap();
275        std::fs::write(dir.path().join(".factory/hooks.json"), r#"{"Stop":[{"hooks":[{"type":"command","command":"/bin/true"}]}]}"#)
276            .unwrap();
277        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
278        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
279        assert!(file.pointer("/Stop/0").is_some());
280        assert!(file.pointer("/PreToolUse/0").is_some());
281    }
282
283    #[test]
284    fn install_appends_after_existing_pre_tool_use_in_hooks_json() {
285        let dir = tempfile::tempdir().unwrap();
286        std::fs::create_dir(dir.path().join(".factory")).unwrap();
287        std::fs::write(
288            dir.path().join(".factory/hooks.json"),
289            r#"{"PreToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"/bin/true"}]}]}"#,
290        )
291        .unwrap();
292        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
293        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
294        assert_eq!(file.pointer("/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Edit"));
295        assert_eq!(file.pointer("/PreToolUse/1/matcher").and_then(|m| m.as_str()), Some("Execute"));
296        assert!(file.pointer("/PreToolUse/2").is_none());
297    }
298
299    #[test]
300    fn install_into_hooks_json_leaves_settings_json_alone() {
301        let dir = tempfile::tempdir().unwrap();
302        std::fs::create_dir(dir.path().join(".factory")).unwrap();
303        let settings = r#"{"model":"x","hooks":{"Stop":[]}}"#;
304        std::fs::write(dir.path().join(".factory/settings.json"), settings).unwrap();
305        std::fs::write(dir.path().join(".factory/hooks.json"), "{}").unwrap();
306        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
307        assert_eq!(std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap(), settings);
308        let file: Value = serde_json::from_str(&std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap()).unwrap();
309        assert!(file.pointer("/PreToolUse/0").is_some());
310    }
311
312    #[test]
313    fn install_refuses_unparseable_hooks_json_and_writes_nothing() {
314        for contents in ["", "{not json", "[1,2]", r#"{"PreToolUse":"x"}"#] {
315            let dir = tempfile::tempdir().unwrap();
316            std::fs::create_dir(dir.path().join(".factory")).unwrap();
317            std::fs::write(dir.path().join(".factory/hooks.json"), contents).unwrap();
318            let Err(err) = target().install_with(dir.path(), Some(Path::new(EXE))) else {
319                panic!("{contents:?} was accepted");
320            };
321            assert_eq!(std::fs::read_to_string(dir.path().join(".factory/hooks.json")).unwrap(), contents);
322            assert!(!dir.path().join(".factory/settings.json").exists(), "{contents:?}");
323            assert!(!err.contains("`hooks"), "{contents:?}: {err}");
324        }
325    }
326
327    #[test]
328    fn install_uses_execute_matcher_not_bash() {
329        // Droid's bash tool is `Execute` — wiring a `Bash` matcher
330        // wouldn't fire on shell calls.
331        let dir = tempfile::tempdir().unwrap();
332        std::fs::create_dir(dir.path().join(".factory")).unwrap();
333        target().install(dir.path()).unwrap();
334        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
335        assert!(contents.contains("\"matcher\": \"Execute\""));
336    }
337
338    #[test]
339    fn install_uses_absolute_path_to_binary() {
340        // Droid docs explicitly require absolute paths for hook
341        // commands. We resolve via env::current_exe.
342        let dir = tempfile::tempdir().unwrap();
343        std::fs::create_dir(dir.path().join(".factory")).unwrap();
344        target().install(dir.path()).unwrap();
345        let contents = std::fs::read_to_string(dir.path().join(".factory/settings.json")).unwrap();
346        let settings: Value = serde_json::from_str(&contents).unwrap();
347        let cmd = settings.pointer("/hooks/PreToolUse/0/hooks/0/command").and_then(|s| s.as_str()).unwrap_or("");
348        // Either an absolute path or the fallback bare invocation.
349        assert!(cmd.starts_with('/') || cmd == "safe-chains hook droid", "unexpected command: {cmd}",);
350        assert!(cmd.ends_with(" hook droid") || cmd == "safe-chains hook droid");
351    }
352
353    #[test]
354    fn install_idempotent() {
355        let dir = tempfile::tempdir().unwrap();
356        std::fs::create_dir(dir.path().join(".factory")).unwrap();
357        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
358        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
359        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
360    }
361
362    #[test]
363    fn install_idempotent_outside_a_safe_chains_directory() {
364        // The regression this file's fix is for: detection must survive a binary path in which no
365        // DIRECTORY is named "safe-chains" — the FILE name alone carries it. Under `cargo test`
366        // the running binary is `safe_chains-<hash>` (underscore), so the real install only
367        // round-tripped when the checkout itself sat inside a "safe-chains" directory.
368        let dir = tempfile::tempdir().unwrap();
369        std::fs::create_dir(dir.path().join(".factory")).unwrap();
370        let exe = Path::new("/usr/local/bin/safe-chains");
371        let first = target().install_with(dir.path(), Some(exe)).unwrap();
372        assert!(matches!(first, InstallOutcome::Installed { .. }));
373        let second = target().install_with(dir.path(), Some(exe)).unwrap();
374        assert!(matches!(second, InstallOutcome::AlreadyConfigured { .. }));
375    }
376
377    #[test]
378    fn parse_input_extracts_command() {
379        let parsed = DroidHookFormat.parse_input(DROID_DOCS_SAMPLE).unwrap();
380        assert_eq!(parsed.command, "ls -la");
381        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
382    }
383
384    #[test]
385    fn parse_input_rejects_garbage() {
386        assert!(DroidHookFormat.parse_input("not json").is_err());
387        assert!(DroidHookFormat.parse_input("{}").is_err());
388    }
389
390    #[test]
391    fn render_response_emits_claude_shaped_envelope() {
392        let r = DroidHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
393        let v: Value = serde_json::from_str(&r.stdout).unwrap();
394        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("allow"),);
395    }
396
397    #[test]
398    fn render_response_deny_emits_empty_body() {
399        let r = DroidHookFormat.render_response(Verdict::Denied);
400        assert_eq!(r.stdout, "");
401    }
402}