safe-chains 0.243.6

Auto-allow safe bash commands in agentic coding tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::path::{Path, PathBuf};

use serde::Deserialize;
use serde_json::{Value, json};

use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target};
use crate::verdict::Verdict;

pub struct GrokTarget;

impl Target for GrokTarget {
    fn name(&self) -> &'static str {
        "grok"
    }

    fn display_name(&self) -> &'static str {
        "Grok CLI (xAI)"
    }

    fn shell_tool_name(&self) -> &'static str {
        GrokHookFormat::SHELL_TOOL
    }

    /// grok's envelope DOES name the tool, so it can be held to
    /// `no_target_decides_on_a_foreign_tool` rather than exempted from it.
    #[cfg(test)]
    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
        Some(format!(r#"{{"toolName":"{tool}","toolInput":{{"command":"{command}"}},"workspaceRoot":"/w"}}"#))
    }

    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
        vec![home.join(".grok")]
    }

    /// Grok discovers hooks from every `~/.grok/hooks/*.json` (globally trusted, no folder-trust
    /// needed), so we own a DEDICATED `safe-chains.json` rather than editing a shared file — no risk
    /// of clobbering the user's other hook files, and idempotency is trivial.
    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
        let dir = home.join(".grok");
        if !dir.exists() {
            return Ok(InstallOutcome::Skipped { reason: format!("~/.grok not found at {} (Grok CLI not installed)", dir.display()) });
        }

        let hooks_dir = dir.join("hooks");
        let path = hooks_dir.join("safe-chains.json");
        let binary = "safe-chains hook grok";

        if path.exists()
            && let Ok(contents) = std::fs::read_to_string(&path)
            && let Ok(value) = serde_json::from_str::<Value>(&contents)
            && has_safe_chains_hook(&value)
        {
            return Ok(InstallOutcome::AlreadyConfigured { path });
        }

        std::fs::create_dir_all(&hooks_dir).map_err(|e| format!("Could not create {}: {e}", hooks_dir.display()))?;
        let output = serde_json::to_string_pretty(&hook_file(binary)).expect("serializing valid JSON");
        std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
        Ok(InstallOutcome::Installed { path })
    }

    fn hook_format(&self) -> Option<&dyn HookFormat> {
        Some(&GrokHookFormat)
    }
}

struct GrokHookFormat;

impl GrokHookFormat {
    /// grok's real shell tool. The hook is CONFIGURED with `matcher: "Bash"` for Claude
    /// compatibility, but the payload names the tool itself — see HARNESS-BEHAVIORS.md.
    const SHELL_TOOL: &'static str = "run_terminal_command";
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GrokToolInput {
    command: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GrokHookEnvelope {
    tool_input: GrokToolInput,
    /// `toolName` — grok's shell tool is `run_terminal_command`.
    ///
    /// TODO.md listed grok as unable to self-filter, on the reading that its envelope carries no
    /// tool identifier. It does: the field is in HARNESS-BEHAVIORS.md's recorded payload and in this
    /// module's own `GROK_DOCS_SAMPLE`. It simply was not deserialized — the identical oversight
    /// that had antigravity on the same list.
    #[serde(default)]
    tool_name: Option<String>,
    #[serde(default)]
    cwd: Option<String>,
    #[serde(default)]
    workspace_root: Option<String>,
    /// `permissionMode`: `default`, `auto`, `plan` or `bypassPermissions`. Read as any JSON value so
    /// an unexpected type cannot fail the whole parse (which would abstain, and fail open).
    #[serde(default)]
    permission_mode: Option<Value>,
}

impl HookFormat for GrokHookFormat {
    /// Grok's PreToolUse envelope is camelCase (`toolInput.command`, `workspaceRoot`) — unlike
    /// Claude/Codex snake_case. Getting the casing wrong parses to nothing and fails OPEN, so it is
    /// pinned by `parse_input_rejects_snake_case_envelope` below.
    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
        let envelope: GrokHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
        // Self-filter on the tool, the same way antigravity does. An ABSENT name still passes: the
        // hook is configured with a matcher, and refusing an envelope that simply omits the field
        // would break every harness version that does not send it.
        if let Some(name) = envelope.tool_name.as_deref()
            && name != Self::SHELL_TOOL
        {
            return Err(ParseError { message: format!("not a shell tool: {name}") });
        }
        Ok(HookInput {
            command: envelope.tool_input.command,
            cwd: envelope.cwd,
            cwd_declared: false,
            // The project root arrives in the payload as `workspaceRoot`; grok also exports it as
            // `GROK_WORKSPACE_ROOT` and (for Claude compat) `CLAUDE_PROJECT_DIR`.
            root: envelope
                .workspace_root
                .or_else(|| super::env_root("GROK_WORKSPACE_ROOT"))
                .or_else(|| super::env_root("CLAUDE_PROJECT_DIR")),
            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
            session_id: None,
            permission_mode: envelope.permission_mode.as_ref().and_then(Value::as_str).map(str::to_string),
        })
    }

    fn decision_pointer(&self) -> &'static str {
        "/decision" // top level, camelCase envelope in
    }

    fn render_response(&self, verdict: Verdict) -> HookResponse {
        // A safe command → `allow`. Grok treats a hook `allow` as "declines to deny", NOT a grant:
        // the command still runs grok's own permission gauntlet and may prompt (so safe-chains cannot
        // auto-approve on grok — same as Cursor/Codex). Emitting it is honest and harmless, and
        // becomes a real grant if grok ever promotes `allow`. `decision` is the top-level field grok
        // reads (NOT Claude's `hookSpecificOutput.permissionDecision`). render_response is only
        // called for ALLOWED verdicts; the Denied branch is defensive — it must stay empty (never
        // emit allow) so a stray call can't fail open.
        if verdict.is_allowed() {
            HookResponse { stdout: json!({ "decision": "allow" }).to_string(), exit_code: 0 }
        } else {
            HookResponse { stdout: String::new(), exit_code: 0 }
        }
    }

    /// Grok has no hook grant: its `allow` only "declines to deny". The baseline for a gated
    /// command is therefore a veto, which protects in every mode; see `gated_policy_for` for the one
    /// case that asks instead.
    fn gated_policy(&self) -> super::GatedPolicy {
        super::GatedPolicy::Deny
    }

    /// Grok does have a hook `ask` (1.0.62): it sends the call to the permission prompt, past
    /// always-approve, auto mode, saved grants and its safe-command list, and shows our reason. So a
    /// command safe-chains simply has not approved yet is put to the user, in the modes where a
    /// prompt is shown. A boundary is still refused. So is everything in `bypassPermissions`, a
    /// missing mode or one we do not know, since an `ask` there may be answered by nobody.
    /// `defer` is never used: it would let grok's own read-only list run `cat /etc/hosts` unasked.
    fn gated_policy_for(&self, kind: crate::explain_fix::gate::GateKind, permission_mode: Option<&str>) -> super::GatedPolicy {
        match (kind, permission_mode) {
            (
                crate::explain_fix::gate::GateKind::NotYet | crate::explain_fix::gate::GateKind::TooLarge,
                Some("default" | "auto" | "plan"),
            ) => super::GatedPolicy::Ask,
            _ => super::GatedPolicy::Deny,
        }
    }

    fn extra_decision_pointers(&self) -> &'static [&'static str] {
        &["/hookSpecificOutput/permissionDecision"]
    }

    fn splits_by_kind(&self) -> bool {
        true
    }

    fn render_deny(&self, reason: &str) -> HookResponse {
        // Both signals say deny: the top-level `decision` (honored regardless of exit code) and exit
        // 2 (grok's deny code; any OTHER non-zero fails OPEN, so it must be exactly 2).
        HookResponse { stdout: json!({ "decision": "deny", "reason": reason }).to_string(), exit_code: 2 }
    }

    /// The nested `permissionDecision` decides when present, so a grok that reads it asks. A grok
    /// that reads only the top-level `decision` sees a deny, so an older one fails closed. Exit 0,
    /// because exit 2 is a deny whatever the body says.
    fn render_ask(&self, reason: &str) -> HookResponse {
        let body = json!({
            "decision": "deny",
            "reason": reason,
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "ask",
                "permissionDecisionReason": reason,
            },
        });
        HookResponse { stdout: body.to_string(), exit_code: 0 }
    }
}

fn hook_file(binary: &str) -> Value {
    json!({
        "hooks": {
            "PreToolUse": [{
                "matcher": "Bash",
                "hooks": [{
                    "type": "command",
                    "command": binary,
                    "timeout": 10,
                }]
            }]
        }
    })
}

fn has_safe_chains_hook(settings: &Value) -> bool {
    settings
        .get("hooks")
        .and_then(|h| h.get("PreToolUse"))
        .and_then(|arr| arr.as_array())
        .is_some_and(|entries| {
            entries.iter().any(|entry| {
                entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
                    hooks
                        .iter()
                        .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
                })
            })
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::verdict::SafetyLevel;

    fn target() -> GrokTarget {
        GrokTarget
    }

    #[test]
    fn install_no_grok_dir_skips() {
        let dir = tempfile::tempdir().unwrap();
        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::Skipped { .. }));
    }

    #[test]
    fn install_creates_dedicated_hook_file() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".grok")).unwrap();
        let outcome = target().install(dir.path()).unwrap();
        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
        let path = dir.path().join(".grok/hooks/safe-chains.json");
        assert!(path.is_file(), "must write ~/.grok/hooks/safe-chains.json");
        let settings: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert!(has_safe_chains_hook(&settings));
        // Nested under a top-level `hooks` object with a `PreToolUse` array (grok/Codex shape), never
        // a flat top-level `PreToolUse` key.
        assert!(settings.pointer("/hooks/PreToolUse").and_then(|a| a.as_array()).is_some());
        assert!(settings.get("PreToolUse").is_none());
        assert_eq!(settings.pointer("/hooks/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Bash"));
    }

    #[test]
    fn install_uses_subcommand_invocation() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".grok")).unwrap();
        target().install(dir.path()).unwrap();
        let contents = std::fs::read_to_string(dir.path().join(".grok/hooks/safe-chains.json")).unwrap();
        assert!(contents.contains("safe-chains hook grok"));
    }

    #[test]
    fn install_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".grok")).unwrap();
        target().install(dir.path()).unwrap();
        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::AlreadyConfigured { .. }));
    }

    // The verbatim PreToolUse envelope from ~/.grok/docs/user-guide/10-hooks.md — camelCase, with the
    // command nested at toolInput.command and the project root at workspaceRoot.
    const GROK_DOCS_SAMPLE: &str = r#"{
        "hookEventName": "pre_tool_use",
        "sessionId": "abc-123",
        "cwd": "/Users/me/project/sub",
        "workspaceRoot": "/Users/me/project",
        "toolName": "run_terminal_command",
        "toolInput": {"command": "npm test"},
        "timestamp": "2026-07-22T00:00:00Z"
    }"#;

    #[test]
    fn parse_input_extracts_camelcase_command_and_root() {
        let parsed = GrokHookFormat.parse_input(GROK_DOCS_SAMPLE).unwrap();
        assert_eq!(parsed.command, "npm test");
        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project/sub"));
        assert_eq!(parsed.root.as_deref(), Some("/Users/me/project"));
    }

    #[test]
    fn parse_input_reads_the_permission_mode_and_never_fails_on_its_type() {
        let with = |mode: &str| GROK_DOCS_SAMPLE.replace(r#""toolName""#, &format!(r#""permissionMode": {mode}, "toolName""#));
        assert_eq!(GrokHookFormat.parse_input(&with(r#""auto""#)).unwrap().permission_mode.as_deref(), Some("auto"));
        assert_eq!(GrokHookFormat.parse_input(GROK_DOCS_SAMPLE).unwrap().permission_mode, None);
        for odd in ["7", "null", "{}", "[\"default\"]"] {
            let parsed = GrokHookFormat.parse_input(&with(odd)).expect("an odd mode must still parse");
            assert_eq!(parsed.permission_mode, None, "{odd}");
            assert_eq!(parsed.command, "npm test");
        }
    }

    #[test]
    fn parse_input_rejects_snake_case_envelope() {
        // The Claude/Codex snake_case shape must NOT parse — if it did, grok's camelCase payload would
        // silently fail to parse and fail OPEN. This is the casing tripwire.
        let snake = r#"{"tool_input": {"command": "ls"}, "workspace_root": "/p"}"#;
        assert!(GrokHookFormat.parse_input(snake).is_err());
    }

    #[test]
    fn parse_input_rejects_garbage() {
        assert!(GrokHookFormat.parse_input("not json").is_err());
        assert!(GrokHookFormat.parse_input("{}").is_err());
    }

    /// An exhausted work budget means the filesystem checks did not run. That is a boundary, so grok
    /// refuses it in every mode, including the ones where a not-yet command would be asked.
    #[test]
    fn a_spent_classification_budget_is_refused_in_every_mode() {
        use super::super::GatedPolicy;
        let project = crate::process_home::var().unwrap_or_else(|_| "/home/tester".into()) + "/projects/budgetprobe";
        let _ctx = crate::pathctx::enter(crate::pathctx::PathCtx { cwd: Some(project.clone()), root: Some(project), session_id: None });
        let cmd = "zzbudgettool sync";
        let explanation = crate::explain_with_coverage_at_level(cmd, None);
        let _outer = crate::enter_classify_budget(cmd);
        while crate::cst::check::charge_classify_work(1) {}
        let kind = crate::explain_fix::gate::gate_kind(cmd, &explanation, &|_| false, &|_| false);
        for mode in [None, Some("default"), Some("auto"), Some("plan"), Some("bypassPermissions"), Some("dontAsk")] {
            assert_eq!(GrokHookFormat.gated_policy_for(kind, mode), GatedPolicy::Deny, "{mode:?}");
        }
    }

    #[test]
    fn grok_denies_by_default_and_asks_only_for_a_not_yet_command_in_a_prompting_mode() {
        use super::super::GatedPolicy;
        use crate::explain_fix::gate::GateKind;
        assert_eq!(GrokHookFormat.gated_policy(), GatedPolicy::Deny);
        let modes =
            [None, Some("default"), Some("auto"), Some("plan"), Some("bypassPermissions"), Some("dontAsk"), Some(""), Some("Default")];
        for mode in modes {
            let asks = matches!(mode, Some("default" | "auto" | "plan"));
            let expected = if asks { GatedPolicy::Ask } else { GatedPolicy::Deny };
            assert_eq!(GrokHookFormat.gated_policy_for(GateKind::NotYet, mode), expected, "{mode:?}");
            assert_eq!(GrokHookFormat.gated_policy_for(GateKind::TooLarge, mode), expected, "{mode:?}");
            assert_eq!(GrokHookFormat.gated_policy_for(GateKind::Boundary, mode), GatedPolicy::Deny, "{mode:?}");
        }
    }

    #[test]
    fn render_ask_asks_in_the_nested_field_and_denies_in_the_top_level_one() {
        let r = GrokHookFormat.render_ask("not approved yet");
        let v: Value = serde_json::from_str(&r.stdout).unwrap();
        assert_eq!(v.pointer("/decision").and_then(Value::as_str), Some("deny"));
        assert_eq!(v.pointer("/reason").and_then(Value::as_str), Some("not approved yet"));
        assert_eq!(v.pointer("/hookSpecificOutput/hookEventName").and_then(Value::as_str), Some("PreToolUse"));
        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(Value::as_str), Some("ask"));
        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecisionReason").and_then(Value::as_str), Some("not approved yet"));
        // Exit 2 is a deny whatever the body says, so an ask must exit 0.
        assert_eq!(r.exit_code, 0);
    }

    #[test]
    fn render_response_uses_top_level_decision_allow() {
        // Grok reads a TOP-LEVEL `decision`, not Claude's `hookSpecificOutput.permissionDecision` nor
        // Cursor's `permission`. Wiring this wrong fails open — pinned here.
        let r = GrokHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
        let v: Value = serde_json::from_str(&r.stdout).unwrap();
        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("allow"));
        assert!(v.get("permissionDecision").is_none());
        assert!(v.get("permission").is_none());
        assert_eq!(r.exit_code, 0);
    }

    #[test]
    fn render_response_denied_is_empty_fail_safe() {
        // render_response is only called for ALLOWED verdicts; a defensive call with Denied must NOT
        // emit an allow (else a stray call fails open). Pinned by the cross-target contract test too.
        let r = GrokHookFormat.render_response(Verdict::Denied);
        assert_eq!(r.stdout, "");
    }

    #[test]
    fn render_deny_uses_decision_deny_and_exit_2() {
        let r = GrokHookFormat.render_deny("blocked: not on the allowlist");
        let v: Value = serde_json::from_str(&r.stdout).unwrap();
        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("deny"));
        assert_eq!(v.get("reason").and_then(|d| d.as_str()), Some("blocked: not on the allowlist"));
        assert!(v.get("permissionDecision").is_none());
        // Exit 2 is grok's deny code; any OTHER non-zero fails OPEN, so this must be exactly 2.
        assert_eq!(r.exit_code, 2);
    }

    #[test]
    fn render_context_defaults_to_abstain() {
        // Grok's PreToolUse output has no additionalContext channel, so context injection keeps the
        // safe default: emit nothing.
        let r = GrokHookFormat.render_context("anything");
        assert_eq!(r.stdout, "");
        assert_eq!(r.exit_code, 0);
    }
}