Skip to main content

safe_chains/targets/
grok.rs

1use std::path::{Path, PathBuf};
2
3use serde::Deserialize;
4use serde_json::{Value, json};
5
6use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target};
7use crate::verdict::Verdict;
8
9pub struct GrokTarget;
10
11impl Target for GrokTarget {
12    fn name(&self) -> &'static str {
13        "grok"
14    }
15
16    fn display_name(&self) -> &'static str {
17        "Grok CLI (xAI)"
18    }
19
20    fn shell_tool_name(&self) -> &'static str {
21        GrokHookFormat::SHELL_TOOL
22    }
23
24    /// grok's envelope DOES name the tool, so it can be held to
25    /// `no_target_decides_on_a_foreign_tool` rather than exempted from it.
26    #[cfg(test)]
27    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
28        Some(format!(r#"{{"toolName":"{tool}","toolInput":{{"command":"{command}"}},"workspaceRoot":"/w"}}"#))
29    }
30
31    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
32        vec![home.join(".grok")]
33    }
34
35    /// Grok discovers hooks from every `~/.grok/hooks/*.json` (globally trusted, no folder-trust
36    /// needed), so we own a DEDICATED `safe-chains.json` rather than editing a shared file — no risk
37    /// of clobbering the user's other hook files, and idempotency is trivial.
38    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
39        let dir = home.join(".grok");
40        if !dir.exists() {
41            return Ok(InstallOutcome::Skipped { reason: format!("~/.grok not found at {} (Grok CLI not installed)", dir.display()) });
42        }
43
44        let hooks_dir = dir.join("hooks");
45        let path = hooks_dir.join("safe-chains.json");
46        let binary = "safe-chains hook grok";
47
48        if path.exists()
49            && let Ok(contents) = std::fs::read_to_string(&path)
50            && let Ok(value) = serde_json::from_str::<Value>(&contents)
51            && has_safe_chains_hook(&value)
52        {
53            return Ok(InstallOutcome::AlreadyConfigured { path });
54        }
55
56        std::fs::create_dir_all(&hooks_dir).map_err(|e| format!("Could not create {}: {e}", hooks_dir.display()))?;
57        let output = serde_json::to_string_pretty(&hook_file(binary)).expect("serializing valid JSON");
58        std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
59        Ok(InstallOutcome::Installed { path })
60    }
61
62    fn hook_format(&self) -> Option<&dyn HookFormat> {
63        Some(&GrokHookFormat)
64    }
65}
66
67struct GrokHookFormat;
68
69impl GrokHookFormat {
70    /// grok's real shell tool. The hook is CONFIGURED with `matcher: "Bash"` for Claude
71    /// compatibility, but the payload names the tool itself — see HARNESS-BEHAVIORS.md.
72    const SHELL_TOOL: &'static str = "run_terminal_command";
73}
74
75#[derive(Deserialize)]
76#[serde(rename_all = "camelCase")]
77struct GrokToolInput {
78    command: String,
79}
80
81#[derive(Deserialize)]
82#[serde(rename_all = "camelCase")]
83struct GrokHookEnvelope {
84    tool_input: GrokToolInput,
85    /// `toolName` — grok's shell tool is `run_terminal_command`.
86    ///
87    /// TODO.md listed grok as unable to self-filter, on the reading that its envelope carries no
88    /// tool identifier. It does: the field is in HARNESS-BEHAVIORS.md's recorded payload and in this
89    /// module's own `GROK_DOCS_SAMPLE`. It simply was not deserialized — the identical oversight
90    /// that had antigravity on the same list.
91    #[serde(default)]
92    tool_name: Option<String>,
93    #[serde(default)]
94    cwd: Option<String>,
95    #[serde(default)]
96    workspace_root: Option<String>,
97    /// `permissionMode`: `default`, `auto`, `plan` or `bypassPermissions`. Read as any JSON value so
98    /// an unexpected type cannot fail the whole parse (which would abstain, and fail open).
99    #[serde(default)]
100    permission_mode: Option<Value>,
101}
102
103impl HookFormat for GrokHookFormat {
104    /// Grok's PreToolUse envelope is camelCase (`toolInput.command`, `workspaceRoot`) — unlike
105    /// Claude/Codex snake_case. Getting the casing wrong parses to nothing and fails OPEN, so it is
106    /// pinned by `parse_input_rejects_snake_case_envelope` below.
107    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
108        let envelope: GrokHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
109        // Self-filter on the tool, the same way antigravity does. An ABSENT name still passes: the
110        // hook is configured with a matcher, and refusing an envelope that simply omits the field
111        // would break every harness version that does not send it.
112        if let Some(name) = envelope.tool_name.as_deref()
113            && name != Self::SHELL_TOOL
114        {
115            return Err(ParseError { message: format!("not a shell tool: {name}") });
116        }
117        Ok(HookInput {
118            command: envelope.tool_input.command,
119            cwd: envelope.cwd,
120            // The project root arrives in the payload as `workspaceRoot`; grok also exports it as
121            // `GROK_WORKSPACE_ROOT` and (for Claude compat) `CLAUDE_PROJECT_DIR`.
122            root: envelope
123                .workspace_root
124                .or_else(|| super::env_root("GROK_WORKSPACE_ROOT"))
125                .or_else(|| super::env_root("CLAUDE_PROJECT_DIR")),
126            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
127            session_id: None,
128            permission_mode: envelope.permission_mode.as_ref().and_then(Value::as_str).map(str::to_string),
129        })
130    }
131
132    fn decision_pointer(&self) -> &'static str {
133        "/decision" // top level, camelCase envelope in
134    }
135
136    fn render_response(&self, verdict: Verdict) -> HookResponse {
137        // A safe command → `allow`. Grok treats a hook `allow` as "declines to deny", NOT a grant:
138        // the command still runs grok's own permission gauntlet and may prompt (so safe-chains cannot
139        // auto-approve on grok — same as Cursor/Codex). Emitting it is honest and harmless, and
140        // becomes a real grant if grok ever promotes `allow`. `decision` is the top-level field grok
141        // reads (NOT Claude's `hookSpecificOutput.permissionDecision`). render_response is only
142        // called for ALLOWED verdicts; the Denied branch is defensive — it must stay empty (never
143        // emit allow) so a stray call can't fail open.
144        if verdict.is_allowed() {
145            HookResponse { stdout: json!({ "decision": "allow" }).to_string(), exit_code: 0 }
146        } else {
147            HookResponse { stdout: String::new(), exit_code: 0 }
148        }
149    }
150
151    /// Grok has no hook grant: its `allow` only "declines to deny". The baseline for a gated
152    /// command is therefore a veto, which protects in every mode; see `gated_policy_for` for the one
153    /// case that asks instead.
154    fn gated_policy(&self) -> super::GatedPolicy {
155        super::GatedPolicy::Deny
156    }
157
158    /// Grok does have a hook `ask` (1.0.62): it sends the call to the permission prompt, past
159    /// always-approve, auto mode, saved grants and its safe-command list, and shows our reason. So a
160    /// command safe-chains simply has not approved yet is put to the user, in the modes where a
161    /// prompt is shown. A boundary is still refused. So is everything in `bypassPermissions`, a
162    /// missing mode or one we do not know, since an `ask` there may be answered by nobody.
163    /// `defer` is never used: it would let grok's own read-only list run `cat /etc/hosts` unasked.
164    fn gated_policy_for(&self, kind: crate::explain_fix::gate::GateKind, permission_mode: Option<&str>) -> super::GatedPolicy {
165        match (kind, permission_mode) {
166            (crate::explain_fix::gate::GateKind::NotYet, Some("default" | "auto" | "plan")) => super::GatedPolicy::Ask,
167            _ => super::GatedPolicy::Deny,
168        }
169    }
170
171    fn extra_decision_pointers(&self) -> &'static [&'static str] {
172        &["/hookSpecificOutput/permissionDecision"]
173    }
174
175    fn splits_by_kind(&self) -> bool {
176        true
177    }
178
179    fn render_deny(&self, reason: &str) -> HookResponse {
180        // Both signals say deny: the top-level `decision` (honored regardless of exit code) and exit
181        // 2 (grok's deny code; any OTHER non-zero fails OPEN, so it must be exactly 2).
182        HookResponse { stdout: json!({ "decision": "deny", "reason": reason }).to_string(), exit_code: 2 }
183    }
184
185    /// The nested `permissionDecision` decides when present, so a grok that reads it asks. A grok
186    /// that reads only the top-level `decision` sees a deny, so an older one fails closed. Exit 0,
187    /// because exit 2 is a deny whatever the body says.
188    fn render_ask(&self, reason: &str) -> HookResponse {
189        let body = json!({
190            "decision": "deny",
191            "reason": reason,
192            "hookSpecificOutput": {
193                "hookEventName": "PreToolUse",
194                "permissionDecision": "ask",
195                "permissionDecisionReason": reason,
196            },
197        });
198        HookResponse { stdout: body.to_string(), exit_code: 0 }
199    }
200}
201
202fn hook_file(binary: &str) -> Value {
203    json!({
204        "hooks": {
205            "PreToolUse": [{
206                "matcher": "Bash",
207                "hooks": [{
208                    "type": "command",
209                    "command": binary,
210                    "timeout": 10,
211                }]
212            }]
213        }
214    })
215}
216
217fn has_safe_chains_hook(settings: &Value) -> bool {
218    settings
219        .get("hooks")
220        .and_then(|h| h.get("PreToolUse"))
221        .and_then(|arr| arr.as_array())
222        .is_some_and(|entries| {
223            entries.iter().any(|entry| {
224                entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
225                    hooks
226                        .iter()
227                        .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
228                })
229            })
230        })
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236    use crate::verdict::SafetyLevel;
237
238    fn target() -> GrokTarget {
239        GrokTarget
240    }
241
242    #[test]
243    fn install_no_grok_dir_skips() {
244        let dir = tempfile::tempdir().unwrap();
245        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::Skipped { .. }));
246    }
247
248    #[test]
249    fn install_creates_dedicated_hook_file() {
250        let dir = tempfile::tempdir().unwrap();
251        std::fs::create_dir(dir.path().join(".grok")).unwrap();
252        let outcome = target().install(dir.path()).unwrap();
253        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
254        let path = dir.path().join(".grok/hooks/safe-chains.json");
255        assert!(path.is_file(), "must write ~/.grok/hooks/safe-chains.json");
256        let settings: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
257        assert!(has_safe_chains_hook(&settings));
258        // Nested under a top-level `hooks` object with a `PreToolUse` array (grok/Codex shape), never
259        // a flat top-level `PreToolUse` key.
260        assert!(settings.pointer("/hooks/PreToolUse").and_then(|a| a.as_array()).is_some());
261        assert!(settings.get("PreToolUse").is_none());
262        assert_eq!(settings.pointer("/hooks/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Bash"));
263    }
264
265    #[test]
266    fn install_uses_subcommand_invocation() {
267        let dir = tempfile::tempdir().unwrap();
268        std::fs::create_dir(dir.path().join(".grok")).unwrap();
269        target().install(dir.path()).unwrap();
270        let contents = std::fs::read_to_string(dir.path().join(".grok/hooks/safe-chains.json")).unwrap();
271        assert!(contents.contains("safe-chains hook grok"));
272    }
273
274    #[test]
275    fn install_idempotent() {
276        let dir = tempfile::tempdir().unwrap();
277        std::fs::create_dir(dir.path().join(".grok")).unwrap();
278        target().install(dir.path()).unwrap();
279        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::AlreadyConfigured { .. }));
280    }
281
282    // The verbatim PreToolUse envelope from ~/.grok/docs/user-guide/10-hooks.md — camelCase, with the
283    // command nested at toolInput.command and the project root at workspaceRoot.
284    const GROK_DOCS_SAMPLE: &str = r#"{
285        "hookEventName": "pre_tool_use",
286        "sessionId": "abc-123",
287        "cwd": "/Users/me/project/sub",
288        "workspaceRoot": "/Users/me/project",
289        "toolName": "run_terminal_command",
290        "toolInput": {"command": "npm test"},
291        "timestamp": "2026-07-22T00:00:00Z"
292    }"#;
293
294    #[test]
295    fn parse_input_extracts_camelcase_command_and_root() {
296        let parsed = GrokHookFormat.parse_input(GROK_DOCS_SAMPLE).unwrap();
297        assert_eq!(parsed.command, "npm test");
298        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project/sub"));
299        assert_eq!(parsed.root.as_deref(), Some("/Users/me/project"));
300    }
301
302    #[test]
303    fn parse_input_reads_the_permission_mode_and_never_fails_on_its_type() {
304        let with = |mode: &str| GROK_DOCS_SAMPLE.replace(r#""toolName""#, &format!(r#""permissionMode": {mode}, "toolName""#));
305        assert_eq!(GrokHookFormat.parse_input(&with(r#""auto""#)).unwrap().permission_mode.as_deref(), Some("auto"));
306        assert_eq!(GrokHookFormat.parse_input(GROK_DOCS_SAMPLE).unwrap().permission_mode, None);
307        for odd in ["7", "null", "{}", "[\"default\"]"] {
308            let parsed = GrokHookFormat.parse_input(&with(odd)).expect("an odd mode must still parse");
309            assert_eq!(parsed.permission_mode, None, "{odd}");
310            assert_eq!(parsed.command, "npm test");
311        }
312    }
313
314    #[test]
315    fn parse_input_rejects_snake_case_envelope() {
316        // The Claude/Codex snake_case shape must NOT parse — if it did, grok's camelCase payload would
317        // silently fail to parse and fail OPEN. This is the casing tripwire.
318        let snake = r#"{"tool_input": {"command": "ls"}, "workspace_root": "/p"}"#;
319        assert!(GrokHookFormat.parse_input(snake).is_err());
320    }
321
322    #[test]
323    fn parse_input_rejects_garbage() {
324        assert!(GrokHookFormat.parse_input("not json").is_err());
325        assert!(GrokHookFormat.parse_input("{}").is_err());
326    }
327
328    #[test]
329    fn grok_denies_by_default_and_asks_only_for_a_not_yet_command_in_a_prompting_mode() {
330        use super::super::GatedPolicy;
331        use crate::explain_fix::gate::GateKind;
332        assert_eq!(GrokHookFormat.gated_policy(), GatedPolicy::Deny);
333        let modes =
334            [None, Some("default"), Some("auto"), Some("plan"), Some("bypassPermissions"), Some("dontAsk"), Some(""), Some("Default")];
335        for mode in modes {
336            let asks = matches!(mode, Some("default" | "auto" | "plan"));
337            let expected = if asks { GatedPolicy::Ask } else { GatedPolicy::Deny };
338            assert_eq!(GrokHookFormat.gated_policy_for(GateKind::NotYet, mode), expected, "{mode:?}");
339            assert_eq!(GrokHookFormat.gated_policy_for(GateKind::Boundary, mode), GatedPolicy::Deny, "{mode:?}");
340        }
341    }
342
343    #[test]
344    fn render_ask_asks_in_the_nested_field_and_denies_in_the_top_level_one() {
345        let r = GrokHookFormat.render_ask("not approved yet");
346        let v: Value = serde_json::from_str(&r.stdout).unwrap();
347        assert_eq!(v.pointer("/decision").and_then(Value::as_str), Some("deny"));
348        assert_eq!(v.pointer("/reason").and_then(Value::as_str), Some("not approved yet"));
349        assert_eq!(v.pointer("/hookSpecificOutput/hookEventName").and_then(Value::as_str), Some("PreToolUse"));
350        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(Value::as_str), Some("ask"));
351        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecisionReason").and_then(Value::as_str), Some("not approved yet"));
352        // Exit 2 is a deny whatever the body says, so an ask must exit 0.
353        assert_eq!(r.exit_code, 0);
354    }
355
356    #[test]
357    fn render_response_uses_top_level_decision_allow() {
358        // Grok reads a TOP-LEVEL `decision`, not Claude's `hookSpecificOutput.permissionDecision` nor
359        // Cursor's `permission`. Wiring this wrong fails open — pinned here.
360        let r = GrokHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
361        let v: Value = serde_json::from_str(&r.stdout).unwrap();
362        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("allow"));
363        assert!(v.get("permissionDecision").is_none());
364        assert!(v.get("permission").is_none());
365        assert_eq!(r.exit_code, 0);
366    }
367
368    #[test]
369    fn render_response_denied_is_empty_fail_safe() {
370        // render_response is only called for ALLOWED verdicts; a defensive call with Denied must NOT
371        // emit an allow (else a stray call fails open). Pinned by the cross-target contract test too.
372        let r = GrokHookFormat.render_response(Verdict::Denied);
373        assert_eq!(r.stdout, "");
374    }
375
376    #[test]
377    fn render_deny_uses_decision_deny_and_exit_2() {
378        let r = GrokHookFormat.render_deny("blocked: not on the allowlist");
379        let v: Value = serde_json::from_str(&r.stdout).unwrap();
380        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("deny"));
381        assert_eq!(v.get("reason").and_then(|d| d.as_str()), Some("blocked: not on the allowlist"));
382        assert!(v.get("permissionDecision").is_none());
383        // Exit 2 is grok's deny code; any OTHER non-zero fails OPEN, so this must be exactly 2.
384        assert_eq!(r.exit_code, 2);
385    }
386
387    #[test]
388    fn render_context_defaults_to_abstain() {
389        // Grok's PreToolUse output has no additionalContext channel, so context injection keeps the
390        // safe default: emit nothing.
391        let r = GrokHookFormat.render_context("anything");
392        assert_eq!(r.stdout, "");
393        assert_eq!(r.exit_code, 0);
394    }
395}