Skip to main content

safe_chains/targets/
codex.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};
7use crate::verdict::Verdict;
8
9pub struct CodexTarget;
10
11const HOOK_COMMAND: &str = "safe-chains hook codex";
12
13/// The events `--setup` registers, both answered by `safe-chains hook codex`. `PreToolUse` vetoes
14/// gated commands before they run; `PermissionRequest` approves safe reads when Codex would
15/// otherwise prompt (a sandbox escalation, or an `untrusted` approval policy).
16const EVENTS: [&str; 2] = ["PreToolUse", "PermissionRequest"];
17
18impl Target for CodexTarget {
19    fn name(&self) -> &'static str {
20        "codex"
21    }
22
23    fn display_name(&self) -> &'static str {
24        "Codex (OpenAI)"
25    }
26
27    #[cfg(test)]
28    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
29        Some(format!(r#"{{"tool_name":"{tool}","tool_input":{{"command":"{command}"}}}}"#))
30    }
31
32    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
33        vec![home.join(".codex")]
34    }
35
36    /// Adds whichever of `EVENTS` is missing, so a user who installed the `PreToolUse` hook
37    /// before `PermissionRequest` support gets the second entry from a re-run of `--setup`.
38    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
39        let dir = home.join(".codex");
40        if !dir.exists() {
41            return Ok(InstallOutcome::Skipped { reason: format!("~/.codex not found at {} (Codex CLI not installed)", dir.display()) });
42        }
43
44        let path = dir.join("hooks.json");
45        let mut settings = if path.exists() {
46            let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
47            serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?
48        } else {
49            Value::Object(Map::new())
50        };
51
52        let missing: Vec<&str> = EVENTS.into_iter().filter(|event| !has_safe_chains_hook(&settings, event)).collect();
53        if missing.is_empty() {
54            return Ok(InstallOutcome::AlreadyConfigured { path });
55        }
56        for event in missing {
57            add_hook(&mut settings, event, HOOK_COMMAND).map_err(|e| format!("{}: {e}", path.display()))?;
58        }
59        let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
60        std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
61        Ok(InstallOutcome::Installed { path })
62    }
63
64    fn hook_format(&self) -> Option<&dyn HookFormat> {
65        Some(&CodexHookFormat)
66    }
67
68    /// Codex names the event in `hook_event_name`, which it sets itself (the agent cannot reach
69    /// it). Anything that is not a `PermissionRequest`, an envelope without the field included,
70    /// keeps the `PreToolUse` answer this target has always given.
71    fn hook_format_for(&self, stdin: &str) -> Option<&dyn HookFormat> {
72        if event_name(stdin).as_deref() == Some("PermissionRequest") { Some(&CodexPermissionRequestFormat) } else { Some(&CodexHookFormat) }
73    }
74
75    fn hook_formats(&self) -> Vec<&dyn HookFormat> {
76        vec![&CodexHookFormat, &CodexPermissionRequestFormat]
77    }
78}
79
80#[derive(Deserialize)]
81struct EventProbe {
82    #[serde(default)]
83    hook_event_name: Option<String>,
84}
85
86fn event_name(stdin: &str) -> Option<String> {
87    serde_json::from_str::<EventProbe>(stdin).ok().and_then(|probe| probe.hook_event_name)
88}
89
90struct CodexHookFormat;
91
92#[derive(Deserialize)]
93struct ToolInput {
94    command: String,
95}
96
97#[derive(Deserialize)]
98struct CodexHookEnvelope {
99    #[serde(default)]
100    hook_event_name: Option<String>,
101    /// Optional so a harness that omits it still works; when present and naming another tool we
102    /// abstain (see parse_input).
103    #[serde(default)]
104    tool_name: Option<String>,
105    tool_input: Option<ToolInput>,
106    #[serde(default)]
107    cwd: Option<String>,
108}
109
110impl HookFormat for CodexHookFormat {
111    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
112        let envelope: CodexHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
113        if let Some(event) = &envelope.hook_event_name
114            && event != "PreToolUse"
115        {
116            return Err(ParseError { message: format!("not a PreToolUse: {event}") });
117        }
118        let Some(tool_input) = envelope.tool_input else {
119            return Err(ParseError { message: "missing field `tool_input`".to_string() });
120        };
121        // Self-filter on the tool: the hook can be delivered for a non-shell call by a
122        // hand-edited matcher, and deciding on one grants or vetoes a tool never analysed.
123        if let Some(name) = &envelope.tool_name
124            && name != "Bash"
125        {
126            return Err(ParseError { message: format!("not a shell tool: {name}") });
127        }
128        Ok(HookInput {
129            command: tool_input.command,
130            cwd: envelope.cwd,
131            cwd_declared: false,
132            root: None, // codex sends cwd but no distinct project root (HARNESS-BEHAVIORS.md)
133            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
134            session_id: None,
135            permission_mode: None,
136        })
137    }
138
139    fn decision_pointer(&self) -> &'static str {
140        "/hookSpecificOutput/permissionDecision" // mirrors Claude's nesting
141    }
142
143    fn render_response(&self, _verdict: Verdict) -> HookResponse {
144        // SAFE command → emit nothing. A PreToolUse `permissionDecision:"allow"` is still rejected
145        // as unsupported (v0.144.3 through v0.160.1), and Codex "continues on unsupported output"
146        // anyway. Silence lets the safe command run through Codex's own flow; where that flow
147        // would prompt, the PermissionRequest format below approves it.
148        HookResponse { stdout: String::new(), exit_code: 0 }
149    }
150
151    // Codex has no human-review-on-silence (only sandbox-escape prompts) and no `ask`, but its
152    // sandbox permits BROAD READS (`cat /etc/shadow` runs), so a gated command must be denied by
153    // the hook. See docs/design/harness-capability-model.md. Verified against v0.144.3, 2026-07-13.
154    fn gated_policy(&self) -> super::GatedPolicy {
155        super::GatedPolicy::Deny
156    }
157
158    fn render_deny(&self, reason: &str) -> HookResponse {
159        let body = json!({
160            "hookSpecificOutput": {
161                "hookEventName": "PreToolUse",
162                "permissionDecision": "deny",
163                "permissionDecisionReason": reason,
164            }
165        });
166        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
167    }
168}
169
170/// Codex's `PermissionRequest` event (v0.122.0 and later): it fires only when Codex is about to
171/// ask for approval, and an `allow` answers that prompt. Anything short of a safe read emits
172/// nothing, which leaves Codex's normal approval in place, so `gated_policy` keeps the `Defer`
173/// default. Only `allow` is ever emitted: `updatedInput`, `updatedPermissions` and
174/// `interrupt:true` make Codex fail the hook.
175struct CodexPermissionRequestFormat;
176
177/// A host-level network approval arrives as the command with a `network-access <host>`
178/// description, and is classified like any other request: the classifier judges network commands
179/// for Codex as it does for Claude Code.
180#[derive(Deserialize)]
181struct PermissionRequestToolInput {
182    command: String,
183}
184
185#[derive(Deserialize)]
186struct PermissionRequestEnvelope {
187    hook_event_name: String,
188    tool_name: String,
189    tool_input: PermissionRequestToolInput,
190    cwd: String,
191}
192
193impl HookFormat for CodexPermissionRequestFormat {
194    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
195        let envelope: PermissionRequestEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
196        if envelope.hook_event_name != "PermissionRequest" {
197            return Err(ParseError { message: format!("not a PermissionRequest: {}", envelope.hook_event_name) });
198        }
199        // Required here, not optional: this event also carries `apply_patch`, whose
200        // `tool_input.command` is a patch, and MCP calls, `write_stdin` and `request_permissions`.
201        if envelope.tool_name != "Bash" {
202            return Err(ParseError { message: format!("not a shell tool: {}", envelope.tool_name) });
203        }
204        // The cwd is the workspace root here (see `cwd_is_the_commands`), so a root that is the
205        // whole filesystem, or one that is not a path at all, would put every write inside it.
206        if !bounds_a_workspace(&envelope.cwd) {
207            return Err(ParseError { message: format!("no usable workspace in cwd: {}", envelope.cwd) });
208        }
209        Ok(HookInput {
210            command: envelope.tool_input.command,
211            cwd: Some(envelope.cwd),
212            cwd_declared: false,
213            root: None,
214            session_id: None,
215            permission_mode: None,
216        })
217    }
218
219    /// Codex reports the turn's cwd, but `exec_command` runs in its own `workdir`, which this
220    /// payload leaves out. An approval here runs outside the sandbox, so a relative path must not be
221    /// trusted to land where the reported cwd says: the model could set `workdir` to `~` and have
222    /// `echo x >> .zshrc` approved as a worktree write.
223    fn cwd_is_the_commands(&self) -> bool {
224        false
225    }
226
227    fn decision_pointer(&self) -> &'static str {
228        "/hookSpecificOutput/decision/behavior"
229    }
230
231    fn render_response(&self, verdict: Verdict) -> HookResponse {
232        if !verdict.is_allowed() {
233            return HookResponse { stdout: String::new(), exit_code: 0 };
234        }
235        let body = json!({
236            "hookSpecificOutput": {
237                "hookEventName": "PermissionRequest",
238                "decision": { "behavior": "allow" },
239            }
240        });
241        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
242    }
243}
244
245/// An absolute path that still names a directory below `/` once `.` and `..` are folded away, so
246/// `/.`, `/Users/..` and `//` are refused like `/` itself.
247fn bounds_a_workspace(cwd: &str) -> bool {
248    if !cwd.starts_with('/') {
249        return false;
250    }
251    let mut depth = 0usize;
252    for part in cwd.split('/') {
253        match part {
254            "" | "." => {}
255            ".." => depth = depth.saturating_sub(1),
256            _ => depth += 1,
257        }
258    }
259    depth > 0
260}
261
262fn hook_entry(binary: &str) -> Value {
263    json!({
264        "matcher": "Bash",
265        "hooks": [{
266            "type": "command",
267            "command": binary,
268        }]
269    })
270}
271
272/// An entry counts only when it runs `safe-chains hook codex` on shell calls: one under an
273/// `apply_patch` matcher, or running another target's hook, leaves `Bash` uncovered on that event.
274fn has_safe_chains_hook(settings: &Value, event: &str) -> bool {
275    settings
276        .get("hooks")
277        .and_then(|h| h.get(event))
278        .and_then(|arr| arr.as_array())
279        .is_some_and(|entries| {
280            entries.iter().any(|entry| {
281                matcher_covers_bash(entry.get("matcher"))
282                    && entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
283                        hooks
284                            .iter()
285                            .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains(HOOK_COMMAND)))
286                    })
287            })
288        })
289}
290
291fn matcher_covers_bash(matcher: Option<&Value>) -> bool {
292    match matcher {
293        None | Some(Value::Null) => true,
294        Some(Value::String(m)) => m.is_empty() || m == "*" || m.contains("Bash"),
295        Some(_) => false,
296    }
297}
298
299/// Codex nests lifecycle events under a top-level `hooks` object (NOT Claude's flat `PreToolUse`
300/// key) — a flat key makes Codex reject the whole file. See developers.openai.com/codex/hooks.
301///
302/// This used to REPLACE a wrong-typed `hooks` or `PreToolUse` value with an empty one, destroying
303/// whatever the user had there without saying so. The shared helper refuses instead: an unreadable
304/// value is usually a hand-edit or a schema we don't know, and rewriting config we did not
305/// understand is not ours to do.
306fn add_hook(settings: &mut Value, event: &str, binary: &str) -> Result<(), String> {
307    super::append_hook_entry(settings, "hooks", event, hook_entry(binary))
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use crate::verdict::SafetyLevel;
314
315    fn target() -> CodexTarget {
316        CodexTarget
317    }
318
319    fn installed(home: &Path) -> Value {
320        let contents = std::fs::read_to_string(home.join(".codex/hooks.json")).unwrap();
321        serde_json::from_str(&contents).unwrap()
322    }
323
324    fn permission_request(tool: &str, command: &str) -> String {
325        json!({
326            "session_id": "s",
327            "turn_id": "t",
328            "transcript_path": null,
329            "cwd": "/w",
330            "hook_event_name": "PermissionRequest",
331            "model": "m",
332            "permission_mode": "default",
333            "tool_name": tool,
334            "tool_input": { "command": command, "description": "needs to write outside the sandbox" },
335        })
336        .to_string()
337    }
338
339    #[test]
340    fn install_no_codex_dir_skips() {
341        let dir = tempfile::tempdir().unwrap();
342        let outcome = target().install(dir.path()).unwrap();
343        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
344    }
345
346    #[test]
347    fn install_creates_hooks_file() {
348        let dir = tempfile::tempdir().unwrap();
349        std::fs::create_dir(dir.path().join(".codex")).unwrap();
350        let outcome = target().install(dir.path()).unwrap();
351        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
352        let settings = installed(dir.path());
353        for event in EVENTS {
354            assert!(has_safe_chains_hook(&settings, event), "{event} not installed");
355        }
356        // Codex nests events under a top-level `hooks` object; a flat top-level `PreToolUse`
357        // (Claude's shape) makes Codex reject the entire file (`unknown field PreToolUse`).
358        assert!(settings.get("PreToolUse").is_none(), "must not use Claude's flat PreToolUse key");
359        assert!(settings.get("PermissionRequest").is_none(), "must not use a flat PermissionRequest key");
360        assert_eq!(settings.as_object().map(|o| o.len()), Some(1), "only the `hooks` key: {settings}");
361    }
362
363    #[test]
364    fn install_idempotent() {
365        let dir = tempfile::tempdir().unwrap();
366        std::fs::create_dir(dir.path().join(".codex")).unwrap();
367        target().install(dir.path()).unwrap();
368        let first = installed(dir.path());
369        let outcome = target().install(dir.path()).unwrap();
370        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
371        assert_eq!(installed(dir.path()), first, "a second run must not add duplicate entries");
372    }
373
374    #[test]
375    fn install_adds_permission_request_beside_an_older_pre_tool_use_install() {
376        let dir = tempfile::tempdir().unwrap();
377        let codex_dir = dir.path().join(".codex");
378        std::fs::create_dir(&codex_dir).unwrap();
379        let older = json!({"hooks": {"PreToolUse": [hook_entry(HOOK_COMMAND)]}});
380        std::fs::write(codex_dir.join("hooks.json"), older.to_string()).unwrap();
381
382        let outcome = target().install(dir.path()).unwrap();
383        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
384        let settings = installed(dir.path());
385        assert!(has_safe_chains_hook(&settings, "PermissionRequest"));
386        assert_eq!(settings["hooks"]["PreToolUse"], older["hooks"]["PreToolUse"], "the existing entry must be left exactly as it was");
387    }
388
389    #[test]
390    fn install_uses_subcommand_invocation() {
391        // The binary entry must be `safe-chains hook codex`, not just
392        // `safe-chains`, so the runtime knows which envelope to emit.
393        let dir = tempfile::tempdir().unwrap();
394        std::fs::create_dir(dir.path().join(".codex")).unwrap();
395        target().install(dir.path()).unwrap();
396        let settings = installed(dir.path());
397        for event in EVENTS {
398            assert_eq!(settings["hooks"][event][0]["hooks"][0]["command"], HOOK_COMMAND);
399            assert_eq!(settings["hooks"][event][0]["matcher"], "Bash");
400        }
401    }
402
403    #[test]
404    fn install_preserves_existing_hooks() {
405        let dir = tempfile::tempdir().unwrap();
406        let codex_dir = dir.path().join(".codex");
407        std::fs::create_dir(&codex_dir).unwrap();
408        std::fs::write(
409            codex_dir.join("hooks.json"),
410            r#"{"hooks": {"PostToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "log-it"}]}], "PermissionRequest": [{"matcher": "apply_patch", "hooks": [{"type": "command", "command": "mine"}]}]}}"#,
411        )
412        .unwrap();
413        target().install(dir.path()).unwrap();
414        let settings = installed(dir.path());
415        assert!(has_safe_chains_hook(&settings, "PreToolUse"));
416        assert!(has_safe_chains_hook(&settings, "PermissionRequest"));
417        assert!(settings["hooks"].get("PostToolUse").is_some(), "existing PostToolUse must be preserved");
418        assert_eq!(settings["hooks"]["PermissionRequest"][0]["hooks"][0]["command"], "mine", "the user's own entry comes first, untouched");
419    }
420
421    #[test]
422    fn parse_input_extracts_command() {
423        let stdin = r#"{"tool_name": "Bash", "tool_input": {"command": "ls -la"}}"#;
424        let parsed = CodexHookFormat.parse_input(stdin).unwrap();
425        assert_eq!(parsed.command, "ls -la");
426    }
427
428    #[test]
429    fn parse_input_with_optional_cwd() {
430        let stdin = r#"{"tool_input": {"command": "pwd"}, "cwd": "/Users/me"}"#;
431        let parsed = CodexHookFormat.parse_input(stdin).unwrap();
432        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me"));
433    }
434
435    #[test]
436    fn parse_input_rejects_garbage() {
437        assert!(CodexHookFormat.parse_input("not json").is_err());
438        assert!(CodexHookFormat.parse_input("{}").is_err());
439    }
440
441    #[test]
442    fn render_response_safe_emits_empty_body() {
443        // A PreToolUse `permissionDecision:"allow"` is unsupported on Codex. A safe command emits
444        // nothing (Codex continues → runs it); it must NOT emit an allow envelope.
445        let r = CodexHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
446        assert_eq!(r.stdout, "");
447        let r = CodexHookFormat.render_response(Verdict::Denied);
448        assert_eq!(r.stdout, "");
449    }
450
451    #[test]
452    fn gated_command_is_denied_with_the_supported_shape() {
453        // Codex handles a gated command by DENYING (no interactive approval, sandbox permits reads).
454        assert_eq!(CodexHookFormat.gated_policy(), super::super::GatedPolicy::Deny);
455        let r = CodexHookFormat.render_deny("blocked: not on the allowlist");
456        let v: Value = serde_json::from_str(&r.stdout).unwrap();
457        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("deny"));
458        assert_eq!(v.pointer("/hookSpecificOutput/hookEventName").and_then(|d| d.as_str()), Some("PreToolUse"));
459        assert_eq!(
460            v.pointer("/hookSpecificOutput/permissionDecisionReason").and_then(|d| d.as_str()),
461            Some("blocked: not on the allowlist"),
462        );
463        assert_eq!(r.exit_code, 0);
464    }
465
466    #[test]
467    fn render_context_defaults_to_abstain() {
468        // Codex's hook schema isn't verified for context injection, so it keeps
469        // the safe default: emit nothing, leaving the normal flow untouched.
470        let r = CodexHookFormat.render_context("anything");
471        assert_eq!(r.stdout, "");
472        assert_eq!(r.exit_code, 0);
473    }
474
475    #[test]
476    fn routes_only_a_permission_request_to_the_permission_format() {
477        let t = target();
478        let pointer = |stdin: &str| t.hook_format_for(stdin).map(|f| f.decision_pointer());
479        let permission = CodexPermissionRequestFormat.decision_pointer();
480        let pre_tool_use = CodexHookFormat.decision_pointer();
481        assert_eq!(pointer(&permission_request("Bash", "ls")), Some(permission));
482        for other in [
483            r#"{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"ls"}}"#,
484            r#"{"tool_name":"Bash","tool_input":{"command":"ls"}}"#,
485            r#"{"hook_event_name":"permissionrequest","tool_name":"Bash","tool_input":{"command":"ls"}}"#,
486            r#"{"hook_event_name":7,"tool_name":"Bash","tool_input":{"command":"ls"}}"#,
487            "not json",
488            "",
489        ] {
490            assert_eq!(pointer(other), Some(pre_tool_use), "{other} must keep the PreToolUse answer");
491        }
492    }
493
494    #[test]
495    fn permission_request_passes_shell_syntax_and_network_approvals_to_the_classifier() {
496        for command in [
497            "echo $(cat x)", "echo `cat x`", "diff <(ls) b", "curl https://x/$HOME", "read l < f", "cat f | xargs curl",
498            "git status && ls", "ls; ls", "ls\nls", "cat *", "cat ~/x", "ls {a,b}", "git status", "bash -c 'ls -la'",
499        ] {
500            let parsed = CodexPermissionRequestFormat.parse_input(&permission_request("Bash", command)).unwrap();
501            assert_eq!(parsed.command, command);
502        }
503        let mut network: Value = serde_json::from_str(&permission_request("Bash", "curl https://example.com")).unwrap();
504        for description in [json!("network-access example.com"), json!(null), json!(7)] {
505            network["tool_input"]["description"] = description.clone();
506            let parsed = CodexPermissionRequestFormat.parse_input(&network.to_string());
507            assert_eq!(parsed.map(|p| p.command).ok().as_deref(), Some("curl https://example.com"), "{description}");
508        }
509    }
510
511    #[test]
512    fn permission_request_parses_a_bash_envelope() {
513        let parsed = CodexPermissionRequestFormat.parse_input(&permission_request("Bash", "git status")).unwrap();
514        assert_eq!(parsed.command, "git status");
515        assert_eq!(parsed.cwd.as_deref(), Some("/w"));
516    }
517
518    #[test]
519    fn permission_request_abstains_on_every_other_tool() {
520        for tool in ["apply_patch", "write_stdin", "request_permissions", "mcp__server__tool", "Edit", "bash"] {
521            assert!(
522                CodexPermissionRequestFormat.parse_input(&permission_request(tool, "ls")).is_err(),
523                "{tool} must not be classified as a shell command"
524            );
525        }
526        let no_tool = r#"{"hook_event_name":"PermissionRequest","tool_input":{"command":"ls"},"cwd":"/w"}"#;
527        assert!(CodexPermissionRequestFormat.parse_input(no_tool).is_err(), "tool_name is required on this event");
528        let pre_tool_use = r#"{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"ls"},"cwd":"/w"}"#;
529        assert!(CodexPermissionRequestFormat.parse_input(pre_tool_use).is_err());
530        let argv = r#"{"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":["ls"]},"cwd":"/w"}"#;
531        assert!(CodexPermissionRequestFormat.parse_input(argv).is_err(), "only a command string is classified");
532    }
533
534    #[test]
535    fn abstains_on_model_request_and_other_unhandled_events() {
536        let t = target();
537        let routed = |stdin: &str| t.hook_format_for(stdin).map(|f| f.parse_input(stdin));
538        let pre_model = json!({
539            "session_id": "s",
540            "turn_id": "t",
541            "cwd": "/w",
542            "transcript_path": null,
543            "model": "gpt-5",
544            "hook_event_name": "PreModelRequest",
545        })
546        .to_string();
547        let post_model = json!({
548            "session_id": "s",
549            "turn_id": "t",
550            "cwd": "/w",
551            "transcript_path": null,
552            "model": "gpt-5",
553            "hook_event_name": "PostModelRequest",
554            "status": "completed",
555            "error": null,
556            "token_usage": {
557                "cached_input_tokens": 0,
558                "input_tokens": 10,
559                "output_tokens": 5,
560                "reasoning_output_tokens": 0,
561                "total_tokens": 15,
562            },
563        })
564        .to_string();
565        for payload in [&pre_model, &post_model] {
566            let err = routed(payload).expect("format").err().expect("model-request must abstain");
567            assert!(err.message.contains("not a PreToolUse"), "{}", err.message);
568        }
569        for event in ["PreModelRequest", "PostModelRequest", "PostToolUse", "SessionStart", "SessionEnd", "UserPromptSubmit", "Stop"] {
570            let with_tool = json!({
571                "hook_event_name": event,
572                "tool_name": "Bash",
573                "tool_input": {"command": "rm -rf /"},
574                "cwd": "/w",
575            })
576            .to_string();
577            assert!(matches!(routed(&with_tool), Some(Err(_))), "{event} must abstain");
578        }
579        assert!(CodexHookFormat.parse_input(&permission_request("Bash", "ls")).is_err());
580    }
581
582    #[test]
583    fn permission_request_allows_exactly_the_documented_shape() {
584        for level in [SafetyLevel::Inert, SafetyLevel::SafeRead, SafetyLevel::SafeWrite] {
585            let r = CodexPermissionRequestFormat.render_response(Verdict::Allowed(level));
586            assert_eq!(r.exit_code, 0);
587            let v: Value = serde_json::from_str(&r.stdout).unwrap();
588            assert_eq!(v, json!({"hookSpecificOutput": {"hookEventName": "PermissionRequest", "decision": {"behavior": "allow"}}}));
589        }
590    }
591
592    #[test]
593    fn permission_request_emits_nothing_short_of_a_safe_verdict() {
594        assert_eq!(CodexPermissionRequestFormat.gated_policy(), super::super::GatedPolicy::Defer);
595        for r in [
596            CodexPermissionRequestFormat.render_response(Verdict::Denied),
597            CodexPermissionRequestFormat.render_deny("x"),
598            CodexPermissionRequestFormat.render_ask("x"),
599            CodexPermissionRequestFormat.render_context("x"),
600        ] {
601            assert_eq!(r.stdout, "");
602            assert_eq!(r.exit_code, 0);
603        }
604    }
605
606    #[test]
607    fn permission_request_needs_a_cwd_that_bounds_a_workspace() {
608        let with_cwd = |cwd: Value| {
609            json!({"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"ls"},"cwd":cwd}).to_string()
610        };
611        for unusable in [json!("/"), json!("//"), json!(""), json!("relative/dir"), json!(null), json!(7)] {
612            assert!(CodexPermissionRequestFormat.parse_input(&with_cwd(unusable.clone())).is_err(), "cwd {unusable} must abstain");
613        }
614        let missing = r#"{"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"ls"}}"#;
615        assert!(CodexPermissionRequestFormat.parse_input(missing).is_err());
616        assert!(CodexPermissionRequestFormat.parse_input(&with_cwd(json!("/w"))).is_ok());
617    }
618
619    #[test]
620    fn only_the_permission_request_cwd_is_not_the_commands() {
621        assert!(CodexHookFormat.cwd_is_the_commands());
622        assert!(!CodexPermissionRequestFormat.cwd_is_the_commands());
623        let input = CodexPermissionRequestFormat.parse_input(&permission_request("Bash", "ls")).unwrap();
624        let (cwd, root) = super::super::evaluation_dirs(&CodexPermissionRequestFormat, &input);
625        assert_eq!(cwd.as_deref(), Some(super::super::UNKNOWN_WORKDIR));
626        assert_eq!(root.as_deref(), Some(super::super::UNKNOWN_WORKDIR));
627        let (cwd, root) = crate::engine::resolve::regions::with_grants(&[("/w", true, true)], || {
628            super::super::evaluation_dirs(&CodexPermissionRequestFormat, &input)
629        });
630        assert_eq!(cwd.as_deref(), Some(super::super::UNKNOWN_WORKDIR));
631        assert_eq!(root.as_deref(), Some("/w"), "a granted cwd stays the workspace");
632    }
633
634    #[test]
635    fn install_ignores_an_entry_that_does_not_run_this_hook_on_shell_calls() {
636        let dir = tempfile::tempdir().unwrap();
637        let codex_dir = dir.path().join(".codex");
638        std::fs::create_dir(&codex_dir).unwrap();
639        let elsewhere = json!({"hooks": {
640            "PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "safe-chains hook claude"}]}],
641            "PermissionRequest": [{"matcher": "apply_patch", "hooks": [{"type": "command", "command": HOOK_COMMAND}]}],
642        }});
643        std::fs::write(codex_dir.join("hooks.json"), elsewhere.to_string()).unwrap();
644
645        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::Installed { .. }));
646        let settings = installed(dir.path());
647        for event in EVENTS {
648            let entries = settings["hooks"][event].as_array().unwrap();
649            assert_eq!(entries.len(), 2, "{event}: ours is added beside the other entry");
650            assert_eq!(entries[1], hook_entry(HOOK_COMMAND));
651        }
652    }
653
654    #[test]
655    fn matcher_coverage_of_shell_calls() {
656        for covers in [None, Some(json!(null)), Some(json!("")), Some(json!("*")), Some(json!("Bash")), Some(json!("Bash|apply_patch"))] {
657            assert!(matcher_covers_bash(covers.as_ref()), "{covers:?}");
658        }
659        for misses in [json!("apply_patch"), json!("mcp__x__y"), json!(["Bash"]), json!(1)] {
660            assert!(!matcher_covers_bash(Some(&misses)), "{misses}");
661        }
662    }
663
664    #[test]
665    fn install_refuses_a_wrong_typed_permission_request_slot_and_writes_nothing() {
666        let dir = tempfile::tempdir().unwrap();
667        let codex_dir = dir.path().join(".codex");
668        std::fs::create_dir(&codex_dir).unwrap();
669        let path = codex_dir.join("hooks.json");
670        std::fs::write(&path, r#"{"hooks": {"PermissionRequest": "corrupted"}}"#).unwrap();
671        let before = std::fs::read(&path).unwrap();
672
673        let Err(err) = target().install(dir.path()) else { panic!("a wrong-typed slot must be refused") };
674        assert!(err.contains("hooks.PermissionRequest"), "the error names the slot: {err}");
675        assert_eq!(std::fs::read(&path).unwrap(), before, "PreToolUse must not be written alone either");
676    }
677
678    #[test]
679    fn only_a_read_is_granted_where_the_workdir_is_unknown() {
680        use super::super::respond;
681        let grants = |format: &dyn HookFormat, level| respond(format, "x", Verdict::Allowed(level)).is_some_and(|r| !r.stdout.is_empty());
682        assert!(grants(&CodexPermissionRequestFormat, SafetyLevel::Inert));
683        assert!(grants(&CodexPermissionRequestFormat, SafetyLevel::SafeRead));
684        assert!(!grants(&CodexPermissionRequestFormat, SafetyLevel::SafeWrite), "a write could land anywhere");
685        assert!(
686            respond(&CodexHookFormat, "x", Verdict::Allowed(SafetyLevel::SafeWrite)).is_some(),
687            "where the cwd is the command's, the ceiling does not apply"
688        );
689    }
690
691    #[test]
692    fn a_cwd_that_folds_to_the_filesystem_root_bounds_nothing() {
693        for root in ["/", "//", "/.", "/./", "/Users/..", "/tmp/..", "/a/b/../..", "/../.."] {
694            assert!(!bounds_a_workspace(root), "{root}");
695        }
696        for dir in ["/w", "/Users/me/proj", "/a/b/..", "/./w", "/../w"] {
697            assert!(bounds_a_workspace(dir), "{dir}");
698        }
699    }
700
701    proptest::proptest! {
702        /// Folding `.` and `..` is the whole rule: a directory stays a workspace however many `.`
703        /// segments it carries, and climbing back out of every segment it named reaches `/`.
704        #[test]
705        fn bounds_a_workspace_follows_the_folded_depth(
706            names in proptest::collection::vec("[a-zA-Z0-9_-]{1,8}", 1..6),
707            dots in 0usize..4,
708        ) {
709            let dir = format!("/{}", names.join("/"));
710            proptest::prop_assert!(bounds_a_workspace(&dir));
711            let dotted = dir.clone() + &"/.".repeat(dots);
712            let climbed = dir.clone() + &"/..".repeat(names.len() + dots);
713            let relative = names.join("/");
714            proptest::prop_assert!(bounds_a_workspace(&dotted), "{}", dotted);
715            proptest::prop_assert!(!bounds_a_workspace(&climbed), "{}", climbed);
716            proptest::prop_assert!(!bounds_a_workspace(&relative), "a relative path is never a workspace: {}", relative);
717        }
718
719        /// Whatever the command says and whatever the model wrote as its justification, a Bash
720        /// request with a usable cwd reaches the classifier unchanged: the event adds no rule of its
721        /// own about the command's text, only the read ceiling on the verdict.
722        #[test]
723        fn every_bash_request_reaches_the_classifier_verbatim(command in "\\PC*", description in proptest::option::of("\\PC*")) {
724            let mut payload: Value = serde_json::from_str(&permission_request("Bash", &command)).unwrap();
725            payload["tool_input"]["description"] = description.map_or(Value::Null, Value::String);
726            let parsed = CodexPermissionRequestFormat.parse_input(&payload.to_string());
727            proptest::prop_assert_eq!(parsed.map(|p| p.command).ok(), Some(command));
728        }
729
730        #[test]
731        fn every_unhandled_event_abstains(event in "\\PC*", command in "\\PC*") {
732            proptest::prop_assume!(!EVENTS.contains(&event.as_str()));
733            let payload = json!({
734                "hook_event_name": event,
735                "tool_name": "Bash",
736                "tool_input": { "command": command },
737                "cwd": "/w",
738            })
739            .to_string();
740            let parsed = target().hook_format_for(&payload).map(|f| f.parse_input(&payload));
741            proptest::prop_assert!(matches!(parsed, Some(Err(_))));
742        }
743    }
744}