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            cwd_declared: false,
121            // The project root arrives in the payload as `workspaceRoot`; grok also exports it as
122            // `GROK_WORKSPACE_ROOT` and (for Claude compat) `CLAUDE_PROJECT_DIR`.
123            root: envelope
124                .workspace_root
125                .or_else(|| super::env_root("GROK_WORKSPACE_ROOT"))
126                .or_else(|| super::env_root("CLAUDE_PROJECT_DIR")),
127            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
128            session_id: None,
129            permission_mode: envelope.permission_mode.as_ref().and_then(Value::as_str).map(str::to_string),
130        })
131    }
132
133    fn decision_pointer(&self) -> &'static str {
134        "/decision" // top level, camelCase envelope in
135    }
136
137    fn render_response(&self, verdict: Verdict) -> HookResponse {
138        // A safe command → `allow`. Grok treats a hook `allow` as "declines to deny", NOT a grant:
139        // the command still runs grok's own permission gauntlet and may prompt (so safe-chains cannot
140        // auto-approve on grok — same as Cursor/Codex). Emitting it is honest and harmless, and
141        // becomes a real grant if grok ever promotes `allow`. `decision` is the top-level field grok
142        // reads (NOT Claude's `hookSpecificOutput.permissionDecision`). render_response is only
143        // called for ALLOWED verdicts; the Denied branch is defensive — it must stay empty (never
144        // emit allow) so a stray call can't fail open.
145        if verdict.is_allowed() {
146            HookResponse { stdout: json!({ "decision": "allow" }).to_string(), exit_code: 0 }
147        } else {
148            HookResponse { stdout: String::new(), exit_code: 0 }
149        }
150    }
151
152    /// Grok has no hook grant: its `allow` only "declines to deny". The baseline for a gated
153    /// command is therefore a veto, which protects in every mode; see `gated_policy_for` for the one
154    /// case that asks instead.
155    fn gated_policy(&self) -> super::GatedPolicy {
156        super::GatedPolicy::Deny
157    }
158
159    /// Grok does have a hook `ask` (1.0.62): it sends the call to the permission prompt, past
160    /// always-approve, auto mode, saved grants and its safe-command list, and shows our reason. So a
161    /// command safe-chains simply has not approved yet is put to the user, in the modes where a
162    /// prompt is shown. A boundary is still refused. So is everything in `bypassPermissions`, a
163    /// missing mode or one we do not know, since an `ask` there may be answered by nobody.
164    /// `defer` is never used: it would let grok's own read-only list run `cat /etc/hosts` unasked.
165    fn gated_policy_for(&self, kind: crate::explain_fix::gate::GateKind, permission_mode: Option<&str>) -> super::GatedPolicy {
166        match (kind, permission_mode) {
167            (
168                crate::explain_fix::gate::GateKind::NotYet | crate::explain_fix::gate::GateKind::TooLarge,
169                Some("default" | "auto" | "plan"),
170            ) => super::GatedPolicy::Ask,
171            _ => super::GatedPolicy::Deny,
172        }
173    }
174
175    fn extra_decision_pointers(&self) -> &'static [&'static str] {
176        &["/hookSpecificOutput/permissionDecision"]
177    }
178
179    fn splits_by_kind(&self) -> bool {
180        true
181    }
182
183    fn render_deny(&self, reason: &str) -> HookResponse {
184        // Both signals say deny: the top-level `decision` (honored regardless of exit code) and exit
185        // 2 (grok's deny code; any OTHER non-zero fails OPEN, so it must be exactly 2).
186        HookResponse { stdout: json!({ "decision": "deny", "reason": reason }).to_string(), exit_code: 2 }
187    }
188
189    /// The nested `permissionDecision` decides when present, so a grok that reads it asks. A grok
190    /// that reads only the top-level `decision` sees a deny, so an older one fails closed. Exit 0,
191    /// because exit 2 is a deny whatever the body says.
192    fn render_ask(&self, reason: &str) -> HookResponse {
193        let body = json!({
194            "decision": "deny",
195            "reason": reason,
196            "hookSpecificOutput": {
197                "hookEventName": "PreToolUse",
198                "permissionDecision": "ask",
199                "permissionDecisionReason": reason,
200            },
201        });
202        HookResponse { stdout: body.to_string(), exit_code: 0 }
203    }
204}
205
206fn hook_file(binary: &str) -> Value {
207    json!({
208        "hooks": {
209            "PreToolUse": [{
210                "matcher": "Bash",
211                "hooks": [{
212                    "type": "command",
213                    "command": binary,
214                    "timeout": 10,
215                }]
216            }]
217        }
218    })
219}
220
221fn has_safe_chains_hook(settings: &Value) -> bool {
222    settings
223        .get("hooks")
224        .and_then(|h| h.get("PreToolUse"))
225        .and_then(|arr| arr.as_array())
226        .is_some_and(|entries| {
227            entries.iter().any(|entry| {
228                entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
229                    hooks
230                        .iter()
231                        .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
232                })
233            })
234        })
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use crate::verdict::SafetyLevel;
241
242    fn target() -> GrokTarget {
243        GrokTarget
244    }
245
246    #[test]
247    fn install_no_grok_dir_skips() {
248        let dir = tempfile::tempdir().unwrap();
249        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::Skipped { .. }));
250    }
251
252    #[test]
253    fn install_creates_dedicated_hook_file() {
254        let dir = tempfile::tempdir().unwrap();
255        std::fs::create_dir(dir.path().join(".grok")).unwrap();
256        let outcome = target().install(dir.path()).unwrap();
257        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
258        let path = dir.path().join(".grok/hooks/safe-chains.json");
259        assert!(path.is_file(), "must write ~/.grok/hooks/safe-chains.json");
260        let settings: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
261        assert!(has_safe_chains_hook(&settings));
262        // Nested under a top-level `hooks` object with a `PreToolUse` array (grok/Codex shape), never
263        // a flat top-level `PreToolUse` key.
264        assert!(settings.pointer("/hooks/PreToolUse").and_then(|a| a.as_array()).is_some());
265        assert!(settings.get("PreToolUse").is_none());
266        assert_eq!(settings.pointer("/hooks/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Bash"));
267    }
268
269    #[test]
270    fn install_uses_subcommand_invocation() {
271        let dir = tempfile::tempdir().unwrap();
272        std::fs::create_dir(dir.path().join(".grok")).unwrap();
273        target().install(dir.path()).unwrap();
274        let contents = std::fs::read_to_string(dir.path().join(".grok/hooks/safe-chains.json")).unwrap();
275        assert!(contents.contains("safe-chains hook grok"));
276    }
277
278    #[test]
279    fn install_idempotent() {
280        let dir = tempfile::tempdir().unwrap();
281        std::fs::create_dir(dir.path().join(".grok")).unwrap();
282        target().install(dir.path()).unwrap();
283        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::AlreadyConfigured { .. }));
284    }
285
286    // The verbatim PreToolUse envelope from ~/.grok/docs/user-guide/10-hooks.md — camelCase, with the
287    // command nested at toolInput.command and the project root at workspaceRoot.
288    const GROK_DOCS_SAMPLE: &str = r#"{
289        "hookEventName": "pre_tool_use",
290        "sessionId": "abc-123",
291        "cwd": "/Users/me/project/sub",
292        "workspaceRoot": "/Users/me/project",
293        "toolName": "run_terminal_command",
294        "toolInput": {"command": "npm test"},
295        "timestamp": "2026-07-22T00:00:00Z"
296    }"#;
297
298    #[test]
299    fn parse_input_extracts_camelcase_command_and_root() {
300        let parsed = GrokHookFormat.parse_input(GROK_DOCS_SAMPLE).unwrap();
301        assert_eq!(parsed.command, "npm test");
302        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project/sub"));
303        assert_eq!(parsed.root.as_deref(), Some("/Users/me/project"));
304    }
305
306    #[test]
307    fn parse_input_reads_the_permission_mode_and_never_fails_on_its_type() {
308        let with = |mode: &str| GROK_DOCS_SAMPLE.replace(r#""toolName""#, &format!(r#""permissionMode": {mode}, "toolName""#));
309        assert_eq!(GrokHookFormat.parse_input(&with(r#""auto""#)).unwrap().permission_mode.as_deref(), Some("auto"));
310        assert_eq!(GrokHookFormat.parse_input(GROK_DOCS_SAMPLE).unwrap().permission_mode, None);
311        for odd in ["7", "null", "{}", "[\"default\"]"] {
312            let parsed = GrokHookFormat.parse_input(&with(odd)).expect("an odd mode must still parse");
313            assert_eq!(parsed.permission_mode, None, "{odd}");
314            assert_eq!(parsed.command, "npm test");
315        }
316    }
317
318    #[test]
319    fn parse_input_rejects_snake_case_envelope() {
320        // The Claude/Codex snake_case shape must NOT parse — if it did, grok's camelCase payload would
321        // silently fail to parse and fail OPEN. This is the casing tripwire.
322        let snake = r#"{"tool_input": {"command": "ls"}, "workspace_root": "/p"}"#;
323        assert!(GrokHookFormat.parse_input(snake).is_err());
324    }
325
326    #[test]
327    fn parse_input_rejects_garbage() {
328        assert!(GrokHookFormat.parse_input("not json").is_err());
329        assert!(GrokHookFormat.parse_input("{}").is_err());
330    }
331
332    /// An exhausted work budget means the filesystem checks did not run. That is a boundary, so grok
333    /// refuses it in every mode, including the ones where a not-yet command would be asked.
334    #[test]
335    fn a_spent_classification_budget_is_refused_in_every_mode() {
336        use super::super::GatedPolicy;
337        let project = crate::process_home::var().unwrap_or_else(|_| "/home/tester".into()) + "/projects/budgetprobe";
338        let _ctx = crate::pathctx::enter(crate::pathctx::PathCtx { cwd: Some(project.clone()), root: Some(project), session_id: None });
339        let cmd = "zzbudgettool sync";
340        let explanation = crate::explain_with_coverage_at_level(cmd, None);
341        let _outer = crate::enter_classify_budget(cmd);
342        while crate::cst::check::charge_classify_work(1) {}
343        let kind = crate::explain_fix::gate::gate_kind(cmd, &explanation, &|_| false, &|_| false);
344        for mode in [None, Some("default"), Some("auto"), Some("plan"), Some("bypassPermissions"), Some("dontAsk")] {
345            assert_eq!(GrokHookFormat.gated_policy_for(kind, mode), GatedPolicy::Deny, "{mode:?}");
346        }
347    }
348
349    #[test]
350    fn grok_denies_by_default_and_asks_only_for_a_not_yet_command_in_a_prompting_mode() {
351        use super::super::GatedPolicy;
352        use crate::explain_fix::gate::GateKind;
353        assert_eq!(GrokHookFormat.gated_policy(), GatedPolicy::Deny);
354        let modes =
355            [None, Some("default"), Some("auto"), Some("plan"), Some("bypassPermissions"), Some("dontAsk"), Some(""), Some("Default")];
356        for mode in modes {
357            let asks = matches!(mode, Some("default" | "auto" | "plan"));
358            let expected = if asks { GatedPolicy::Ask } else { GatedPolicy::Deny };
359            assert_eq!(GrokHookFormat.gated_policy_for(GateKind::NotYet, mode), expected, "{mode:?}");
360            assert_eq!(GrokHookFormat.gated_policy_for(GateKind::TooLarge, mode), expected, "{mode:?}");
361            assert_eq!(GrokHookFormat.gated_policy_for(GateKind::Boundary, mode), GatedPolicy::Deny, "{mode:?}");
362        }
363    }
364
365    #[test]
366    fn render_ask_asks_in_the_nested_field_and_denies_in_the_top_level_one() {
367        let r = GrokHookFormat.render_ask("not approved yet");
368        let v: Value = serde_json::from_str(&r.stdout).unwrap();
369        assert_eq!(v.pointer("/decision").and_then(Value::as_str), Some("deny"));
370        assert_eq!(v.pointer("/reason").and_then(Value::as_str), Some("not approved yet"));
371        assert_eq!(v.pointer("/hookSpecificOutput/hookEventName").and_then(Value::as_str), Some("PreToolUse"));
372        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(Value::as_str), Some("ask"));
373        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecisionReason").and_then(Value::as_str), Some("not approved yet"));
374        // Exit 2 is a deny whatever the body says, so an ask must exit 0.
375        assert_eq!(r.exit_code, 0);
376    }
377
378    #[test]
379    fn render_response_uses_top_level_decision_allow() {
380        // Grok reads a TOP-LEVEL `decision`, not Claude's `hookSpecificOutput.permissionDecision` nor
381        // Cursor's `permission`. Wiring this wrong fails open — pinned here.
382        let r = GrokHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
383        let v: Value = serde_json::from_str(&r.stdout).unwrap();
384        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("allow"));
385        assert!(v.get("permissionDecision").is_none());
386        assert!(v.get("permission").is_none());
387        assert_eq!(r.exit_code, 0);
388    }
389
390    #[test]
391    fn render_response_denied_is_empty_fail_safe() {
392        // render_response is only called for ALLOWED verdicts; a defensive call with Denied must NOT
393        // emit an allow (else a stray call fails open). Pinned by the cross-target contract test too.
394        let r = GrokHookFormat.render_response(Verdict::Denied);
395        assert_eq!(r.stdout, "");
396    }
397
398    #[test]
399    fn render_deny_uses_decision_deny_and_exit_2() {
400        let r = GrokHookFormat.render_deny("blocked: not on the allowlist");
401        let v: Value = serde_json::from_str(&r.stdout).unwrap();
402        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("deny"));
403        assert_eq!(v.get("reason").and_then(|d| d.as_str()), Some("blocked: not on the allowlist"));
404        assert!(v.get("permissionDecision").is_none());
405        // Exit 2 is grok's deny code; any OTHER non-zero fails OPEN, so this must be exactly 2.
406        assert_eq!(r.exit_code, 2);
407    }
408
409    #[test]
410    fn render_context_defaults_to_abstain() {
411        // Grok's PreToolUse output has no additionalContext channel, so context injection keeps the
412        // safe default: emit nothing.
413        let r = GrokHookFormat.render_context("anything");
414        assert_eq!(r.stdout, "");
415        assert_eq!(r.exit_code, 0);
416    }
417}