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