safe_chains/targets/mod.rs
1use std::path::{Path, PathBuf};
2
3use crate::verdict::{SafetyLevel, Verdict};
4
5pub mod agy;
6pub mod claude;
7pub mod codex;
8pub mod copilot;
9pub mod cursor;
10pub mod droid;
11pub mod gemini;
12pub mod grok;
13pub mod opencode;
14pub mod qwen;
15
16pub trait Target: Send + Sync {
17 fn name(&self) -> &'static str;
18
19 /// The harness's SHELL tool — the only tool this hook should decide about. Droid's is
20 /// `Execute`, Gemini's `run_shell_command`; most are `Bash`. Defaults to `Bash`, the common
21 /// case.
22 fn shell_tool_name(&self) -> &'static str {
23 "Bash"
24 }
25
26 /// A sample envelope this target's `parse_input` accepts, naming `tool`, or `None` when the
27 /// harness's envelope carries NO tool identifier.
28 ///
29 /// `None` is a researched claim, not a default: it says the envelope has no field naming the
30 /// tool, so the hook cannot tell a shell call from any other and must rely on its configured
31 /// matcher alone. `Some` obliges the target to abstain on a foreign tool —
32 /// `no_target_decides_on_a_foreign_tool` holds it to that in both directions.
33 ///
34 /// Test-only; each target knows its own envelope shape, and a generic one cannot stand in for
35 /// nine different schemas (Copilot nests `toolArgs` as a JSON STRING, Antigravity uses
36 /// `toolCall.args.commandLine`, Grok is camelCase).
37 #[cfg(test)]
38 fn sample_envelope(&self, _tool: &str, _command: &str) -> Option<String> {
39 None
40 }
41
42 fn display_name(&self) -> &'static str;
43
44 fn detect_paths(&self, home: &Path) -> Vec<PathBuf>;
45
46 fn install(&self, home: &Path) -> Result<InstallOutcome, String>;
47
48 fn hook_format(&self) -> Option<&dyn HookFormat> {
49 None
50 }
51
52 /// The format that answers THIS envelope. Most harnesses send one hook event, so it is
53 /// `hook_format`. Codex sends `PreToolUse` and `PermissionRequest` to the same command and
54 /// expects a different answer to each, so it picks by the event the envelope names.
55 fn hook_format_for(&self, _stdin: &str) -> Option<&dyn HookFormat> {
56 self.hook_format()
57 }
58
59 /// Every format `hook_format_for` can return, so the contract guards that need no envelope walk
60 /// all of them and a second event's format cannot ship unchecked. The foreign-tool guard is
61 /// driven by `sample_envelope` and reaches only the format that envelope routes to; Codex's
62 /// `PermissionRequest` tool filter has its own test in `codex.rs`.
63 fn hook_formats(&self) -> Vec<&dyn HookFormat> {
64 self.hook_format().into_iter().collect()
65 }
66}
67
68pub trait HookFormat: Send + Sync {
69 fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError>;
70
71 fn render_response(&self, verdict: Verdict) -> HookResponse;
72
73 /// The JSON pointer this harness reads its decision from.
74 ///
75 /// Deliberately has NO default: getting the field wrong fails SILENTLY — the harness ignores
76 /// the unknown key and falls back to its own permissions, so a mis-wired target still lets
77 /// commands run and looks like it works while never deciding anything. Requiring the
78 /// declaration means a new target cannot be added without stating its contract, and
79 /// `every_target_emits_its_decision_at_the_declared_field` checks every emission against it —
80 /// including that the decision does NOT appear at another harness's pointer, which is what a
81 /// copy-pasted target looks like.
82 ///
83 /// Note the leaf name alone is not the contract: Claude nests
84 /// `/hookSpecificOutput/permissionDecision` while Copilot uses a flat `/permissionDecision`.
85 fn decision_pointer(&self) -> &'static str;
86
87 /// Surface explanatory context to the model on a non-approval *without*
88 /// changing the permission decision (the command still flows through the
89 /// tool's normal approval path, and the user's own allowlist still applies).
90 ///
91 /// The default abstains silently — same as today's empty deny body. A target
92 /// overrides this only when its hook schema has a verified field for
93 /// injecting model-visible context without a permission decision.
94 fn render_context(&self, _context: &str) -> HookResponse {
95 HookResponse { stdout: String::new(), exit_code: 0 }
96 }
97
98 /// How this harness's hook must handle a GATED command (one safe-chains does not auto-approve),
99 /// derived from its capabilities (`docs/design/harness-capability-model.md`):
100 /// - `Defer` — stay silent; the harness's own per-command human review is the check (Claude).
101 /// - `Deny` — veto it; the harness has no human review and no escalate (Codex).
102 /// - `Ask` — escalate to an in-the-moment human prompt (Antigravity's `ask`).
103 fn gated_policy(&self) -> GatedPolicy {
104 GatedPolicy::Defer
105 }
106
107 /// The policy for one gated command, given its kind and the harness's permission mode. Only a
108 /// harness that can put a not-yet-approved command to a person, and still refuse a boundary,
109 /// answers differently from `gated_policy` (Grok).
110 fn gated_policy_for(&self, _kind: crate::explain_fix::gate::GateKind, _permission_mode: Option<&str>) -> GatedPolicy {
111 self.gated_policy()
112 }
113
114 /// Whether `gated_policy_for` depends on the kind. Only then is the kind worked out, so a harness
115 /// that does not split pays nothing for it and runs no new code ahead of its refusal.
116 fn splits_by_kind(&self) -> bool {
117 false
118 }
119
120 /// Pointers besides `decision_pointer` where this harness ALSO reads a decision. Grok reads
121 /// `hookSpecificOutput.permissionDecision` ahead of `decision` when both are present.
122 fn extra_decision_pointers(&self) -> &'static [&'static str] {
123 &[]
124 }
125
126 /// The hook output that VETOES a gated command, for a `Deny` harness. Default abstains (so a
127 /// stray call can't fail open). The shape must be exactly what the harness supports, or a
128 /// harness that "continues on malformed output" (e.g. Codex) fails open.
129 fn render_deny(&self, _reason: &str) -> HookResponse {
130 HookResponse { stdout: String::new(), exit_code: 0 }
131 }
132
133 /// The hook output that ESCALATES a gated command to a human prompt, for an `Ask` harness.
134 /// Default abstains. (Antigravity fails CLOSED on a malformed/absent decision, so an Ask target
135 /// must always emit a valid decision.)
136 fn render_ask(&self, _reason: &str) -> HookResponse {
137 HookResponse { stdout: String::new(), exit_code: 0 }
138 }
139
140 /// Whether the envelope's `cwd` is the directory the command runs in. `false` when the harness
141 /// can run the command somewhere else without saying where (Codex's `exec_command` takes a
142 /// `workdir` that its `PermissionRequest` payload leaves out), so `evaluation_dirs` refuses to
143 /// resolve a relative path against it.
144 fn cwd_is_the_commands(&self) -> bool {
145 true
146 }
147}
148
149/// The working directory nothing can be inside: a relative path resolved against it lands outside
150/// every workspace, so a command whose safety rests on where its relative paths point is not
151/// approved, while one that names no such path classifies as it would anywhere.
152pub const UNKNOWN_WORKDIR: &str = "/nonexistent/safe-chains-unknown-workdir";
153
154/// The (cwd, root) a command is classified under. Most harnesses send no distinct project root, so
155/// the root defaults to the cwd, which engages the workspace boundary with the one directory known.
156/// Where the cwd is not the command's own (`HookFormat::cwd_is_the_commands`), the reported cwd
157/// stays the workspace root and the command is placed at `UNKNOWN_WORKDIR`.
158pub fn evaluation_dirs(format: &dyn HookFormat, input: &HookInput) -> (Option<String>, Option<String>) {
159 let root = input.root.clone().or_else(|| input.cwd.clone());
160 if format.cwd_is_the_commands() { (input.cwd.clone(), root) } else { (Some(UNKNOWN_WORKDIR.to_string()), root) }
161}
162
163/// How a harness's hook handles a gated command — see `HookFormat::gated_policy`.
164#[derive(Clone, Copy, PartialEq, Eq, Debug)]
165pub enum GatedPolicy {
166 Defer,
167 Deny,
168 Ask,
169}
170
171#[derive(Debug)]
172pub struct ParseError {
173 pub message: String,
174}
175
176impl std::fmt::Display for ParseError {
177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178 f.write_str(&self.message)
179 }
180}
181
182impl std::error::Error for ParseError {}
183
184pub struct HookInput {
185 pub command: String,
186 pub cwd: Option<String>,
187 /// The project root, when the harness supplies one (HP-19) — a `*_PROJECT_DIR` env var
188 /// for most, `workspace_roots` in the payload for cursor. Absent for codex/copilot.
189 pub root: Option<String>,
190 /// The harness's session/conversation id, when it supplies one (`session_id` for
191 /// Claude/Gemini/Qwen/Droid, `sessionId` for grok, `conversation_id` for cursor). It comes from
192 /// the harness's own envelope, so the agent cannot forge it — which is what makes it usable as
193 /// the anchor for recognizing the session's scratchpad (see `pathctx::session_scratchpad`).
194 pub session_id: Option<String>,
195 /// The harness's permission mode as its envelope names it (Grok's `permissionMode`). Only a
196 /// target whose `gated_policy_for` depends on it reads it; the rest leave it `None`.
197 pub permission_mode: Option<String>,
198}
199
200/// May a GRANT be emitted for this command?
201///
202/// A blank command classifies as `Allowed(Inert)` — an empty script really is inert — but rendering
203/// that as `permissionDecision: "allow"` asserts "every command in this chain is safe" about ZERO
204/// commands, and on the harnesses whose allow is authoritative it replaces the user's prompt.
205///
206/// The check lives HERE, next to the decision contract, rather than in the binary. It was in
207/// `main.rs` first: the shipped hook was safe, but `render_response` is public and knew nothing
208/// about blankness, so any second caller reintroduced the bug — and the integration guard passed
209/// only because it drives the binary. The `hook_envelope` fuzz target found exactly that by calling
210/// the format directly.
211pub fn may_grant(command: &str, verdict: crate::Verdict) -> bool {
212 verdict.is_allowed() && !command.trim().is_empty()
213}
214
215/// The decision for one parsed envelope: the response to emit, or `None` to abstain.
216///
217/// The single seam every caller goes through, so the blank-command rule cannot be bypassed by
218/// reaching for `render_response` directly.
219pub fn respond(format: &dyn HookFormat, command: &str, verdict: crate::Verdict) -> Option<HookResponse> {
220 (may_grant(command, verdict) && within_unknown_workdir_ceiling(format, verdict)).then(|| format.render_response(verdict))
221}
222
223/// Where the command may run in a directory the hook was not told (`cwd_is_the_commands` is
224/// false), a write is granted only when the unknown-folder mode judged it.
225///
226/// `UNKNOWN_WORKDIR` alone catches a write that NAMES a relative path, but `git commit -am x`,
227/// `cargo fmt` or `cargo build` write into whatever directory they run in without naming one, and
228/// classify the same wherever that is. At a folder level above `reads` (`pathctx::folder`), each
229/// relative path was placed or left out by its anchor value and each such write was refused unless
230/// it is accounted for, so the verdict already says what the level allows. Without that, only a
231/// read is granted, which is the `reads` level.
232fn within_unknown_workdir_ceiling(format: &dyn HookFormat, verdict: crate::Verdict) -> bool {
233 format.cwd_is_the_commands()
234 || crate::pathctx::folder::judges_writes()
235 || matches!(verdict, Verdict::Allowed(level) if level <= SafetyLevel::SafeRead)
236}
237
238/// The folder level a hook judges writes at when `format` does not report the command's folder:
239/// the `--unknown-folder` flag, else the user config, else `developer`. `None` when the folder is
240/// known, where the dial does not apply.
241pub fn unknown_folder_level(
242 format: &dyn HookFormat,
243 flag: Option<crate::pathctx::anchor::FolderLevel>,
244) -> Option<crate::pathctx::anchor::FolderLevel> {
245 (!format.cwd_is_the_commands()).then(|| flag.unwrap_or_else(|| crate::registry::folder_config::user_setting().level()))
246}
247
248/// Append `entry` to `settings[outer][event]`, creating the path when absent.
249///
250/// Refuses — rather than overwriting — when an existing key has the wrong TYPE. Four targets wrote
251/// this by hand as `entry(k).or_insert_with(…).as_object_mut().expect("created above as an
252/// object")`, and the message says why it looked safe: it reads as if the key had just been
253/// created. `or_insert_with` returns the EXISTING value, so a settings file carrying
254/// `"hooks": "something"` made `--setup` PANIC — and under `--auto-detect` that aborts the whole
255/// run, so every target after it goes uninstalled.
256///
257/// Erroring beats replacing. The value is the user's, an unreadable one usually means a
258/// hand-edit or a schema we don't know, and silently rewriting config we did not understand is
259/// not ours to do. `install` writes only on `Ok`, so the file is left untouched either way.
260pub(crate) fn append_hook_entry(
261 settings: &mut serde_json::Value,
262 outer: &str,
263 event: &str,
264 entry: serde_json::Value,
265) -> Result<(), String> {
266 use serde_json::json;
267 // Refuse a non-object ROOT rather than replace it, for the same reason a wrong-typed inner key
268 // is refused below: an unreadable value is usually a hand-edit or a schema we do not know, and
269 // rewriting config we did not understand is not ours to do.
270 //
271 // This only ever fires on a file that EXISTS and parses to something that is not an object
272 // (`[1,2,3]`, `"a string"`, `42`). Every caller turns a MISSING file into an empty object
273 // before reaching here, so refusing cannot break a first-time `--setup`.
274 if !settings.is_object() {
275 return Err(format!("the settings file is {}, expected an object. Leaving the file unchanged.", json_kind(settings)));
276 }
277 let Some(obj) = settings.as_object_mut() else {
278 unreachable!("just checked it is an object");
279 };
280 let hooks = obj.entry(outer).or_insert_with(|| json!({}));
281 let Some(hooks) = hooks.as_object_mut() else {
282 return Err(format!("`{outer}` is {}, expected an object. Leaving the file unchanged.", json_kind(&obj[outer])));
283 };
284 let slot = hooks.entry(event).or_insert_with(|| json!([]));
285 if !slot.is_array() {
286 return Err(format!("`{outer}.{event}` is {}, expected an array. Leaving the file unchanged.", json_kind(slot)));
287 }
288 let Some(arr) = slot.as_array_mut() else {
289 unreachable!("just checked it is an array");
290 };
291 arr.push(entry);
292 Ok(())
293}
294
295fn json_kind(v: &serde_json::Value) -> &'static str {
296 match v {
297 serde_json::Value::Null => "null",
298 serde_json::Value::Bool(_) => "a boolean",
299 serde_json::Value::Number(_) => "a number",
300 serde_json::Value::String(_) => "a string",
301 serde_json::Value::Array(_) => "an array",
302 serde_json::Value::Object(_) => "an object",
303 }
304}
305
306/// Read a harness project-root env var from the hook process environment (set by the
307/// harness, not the agent's shell — see HARNESS-BEHAVIORS.md). Empty → `None`.
308pub(crate) fn env_root(var: &str) -> Option<String> {
309 std::env::var(var).ok().filter(|s| !s.is_empty())
310}
311
312pub struct HookResponse {
313 pub stdout: String,
314 pub exit_code: i32,
315}
316
317pub enum InstallOutcome {
318 Installed { path: PathBuf },
319 AlreadyConfigured { path: PathBuf },
320 Skipped { reason: String },
321}
322
323impl InstallOutcome {
324 pub fn message(&self, target_display: &str) -> String {
325 match self {
326 InstallOutcome::Installed { path } => {
327 format!("{target_display}: installed → {}", path.display())
328 }
329 InstallOutcome::AlreadyConfigured { path } => {
330 format!("{target_display}: already configured at {}", path.display())
331 }
332 InstallOutcome::Skipped { reason } => {
333 format!("{target_display}: skipped, {reason}")
334 }
335 }
336 }
337}
338
339pub fn registry() -> Vec<Box<dyn Target>> {
340 vec![
341 Box::new(claude::ClaudeTarget),
342 Box::new(codex::CodexTarget),
343 Box::new(agy::AntigravityTarget),
344 Box::new(cursor::CursorTarget),
345 Box::new(gemini::GeminiTarget),
346 Box::new(grok::GrokTarget),
347 Box::new(copilot::CopilotTarget),
348 Box::new(qwen::QwenTarget),
349 Box::new(droid::DroidTarget),
350 Box::new(opencode::OpenCodeTarget),
351 ]
352}
353
354pub fn find(name: &str) -> Option<Box<dyn Target>> {
355 registry().into_iter().find(|t| t.name() == name)
356}
357
358pub fn detect_installed(home: &Path) -> Vec<Box<dyn Target>> {
359 registry().into_iter().filter(|t| t.detect_paths(home).iter().any(|p| p.exists())).collect()
360}
361
362pub fn allow_reason(verdict: Verdict) -> &'static str {
363 match verdict {
364 Verdict::Allowed(SafetyLevel::SafeWrite) => "All commands in chain are safe utilities (includes file writes)",
365 Verdict::Allowed(SafetyLevel::SafeRead) => "All commands in chain are safe utilities (includes code execution)",
366 _ => "All commands in chain are safe utilities",
367 }
368}
369
370#[cfg(test)]
371mod append_hook_entry_tests {
372 use super::*;
373 use serde_json::json;
374
375 #[test]
376 fn creates_the_path_when_absent() {
377 let mut s = json!({});
378 append_hook_entry(&mut s, "hooks", "PreToolUse", json!({"matcher": "Bash"})).unwrap();
379 assert_eq!(s["hooks"]["PreToolUse"][0]["matcher"], "Bash");
380 }
381
382 #[test]
383 fn appends_beside_an_existing_entry() {
384 let mut s = json!({"hooks": {"PreToolUse": [{"matcher": "Other"}]}});
385 append_hook_entry(&mut s, "hooks", "PreToolUse", json!({"matcher": "Bash"})).unwrap();
386 let arr = s["hooks"]["PreToolUse"].as_array().unwrap();
387 assert_eq!(arr.len(), 2, "the user's existing hook must survive");
388 assert_eq!(arr[0]["matcher"], "Other");
389 }
390
391 /// The panic this replaced: `entry(k).or_insert_with(…).as_object_mut().expect(…)` reads as if
392 /// the key was just created, but `or_insert_with` returns the EXISTING value. A settings file
393 /// with `"hooks": "x"` crashed `--setup` — and under `--auto-detect` that aborted the whole run.
394 #[test]
395 fn refuses_a_wrong_typed_outer_key_without_panicking() {
396 for wrong in [json!("a string"), json!([1, 2]), json!(7), json!(null)] {
397 let mut s = json!({ "hooks": wrong });
398 let before = s.clone();
399 let err = append_hook_entry(&mut s, "hooks", "PreToolUse", json!({})).unwrap_err();
400 assert!(err.contains("expected an object"), "unhelpful error: {err}");
401 assert_eq!(s, before, "the user's value must be left alone, not replaced");
402 }
403 }
404
405 #[test]
406 fn refuses_a_wrong_typed_event_key_without_panicking() {
407 let mut s = json!({"hooks": {"PreToolUse": "a string"}});
408 let before = s.clone();
409 let err = append_hook_entry(&mut s, "hooks", "PreToolUse", json!({})).unwrap_err();
410 assert!(err.contains("expected an array"), "unhelpful error: {err}");
411 assert_eq!(s, before, "the user's value must be left alone, not replaced");
412 }
413
414 /// A non-object ROOT is refused, not replaced.
415 ///
416 /// This test previously asserted the opposite, on the reasoning that "a file whose ROOT is not
417 /// an object carries nothing to preserve". That is the same argument this module already
418 /// rejected one level in, where a wrong-typed `hooks` value is refused because an unreadable
419 /// value usually means a hand-edit or a schema we do not know. A root we cannot read is not
420 /// more disposable than a key we cannot read — it is less, since it is the whole file.
421 ///
422 /// Refusing is safe for a first-time `--setup`: every caller turns a MISSING file into an empty
423 /// object before reaching here, so this fires only for a file that exists and parses to a
424 /// non-object.
425 #[test]
426 fn refuses_a_non_object_root_without_replacing_it() {
427 for root in [json!("garbage"), json!([1, 2, 3]), json!(42), json!(null)] {
428 let mut s = root.clone();
429 let err = append_hook_entry(&mut s, "hooks", "PreToolUse", json!({"matcher": "Bash"}))
430 .expect_err("a non-object root must be refused");
431 assert!(err.contains("expected an object"), "unhelpful error: {err}");
432 assert_eq!(s, root, "the user's file must be left alone, not replaced");
433 }
434
435 // An object root is still the ordinary path.
436 let mut s = json!({"unrelated": true});
437 append_hook_entry(&mut s, "hooks", "PreToolUse", json!({"matcher": "Bash"})).unwrap();
438 assert_eq!(s["hooks"]["PreToolUse"][0]["matcher"], "Bash");
439 assert_eq!(s["unrelated"], true, "unrelated keys survive");
440 }
441}
442
443#[cfg(test)]
444mod tool_filter_tests {
445 use super::*;
446
447 /// No target decides on a tool that is not its shell tool.
448 ///
449 /// The hook is wired with a matcher (`Bash`, `Execute`, `run_shell_command`), so normally only
450 /// shell calls arrive. But a matcher is configuration: it can be hand-edited, and grok is
451 /// documented to auto-load `~/.claude/settings.json`, which hands Claude's hook a foreign
452 /// envelope. Deciding on a `Read`/`Write`/`Edit` call grants or vetoes a tool whose semantics
453 /// were never analysed — and for the ALLOW-capable targets that is a grant, issued on the
454 /// strength of a `command` field the tool does not even have. Four targets did exactly that.
455 ///
456 /// Driven by each target's OWN `sample_envelope`, because nine harnesses have nine schemas and
457 /// a generic probe silently fails to parse (which looks like a pass). A target whose envelope
458 /// carries no tool identifier returns `None` and is exempt — a researched claim, recorded per
459 /// target, not a default.
460 #[test]
461 fn no_target_decides_on_a_foreign_tool() {
462 let mut failures = Vec::new();
463 let mut checked = 0usize;
464 for target in registry() {
465 if target.hook_format().is_none() {
466 continue;
467 }
468 let Some(shell) = target.sample_envelope(target.shell_tool_name(), "ls") else {
469 continue; // envelope carries no tool identifier — cannot self-filter
470 };
471 let name = target.name();
472 let routed = |env: &str| target.hook_format_for(env).map(|fmt| fmt.parse_input(env));
473 // The shell tool must still parse, or "reject everything" would satisfy the negative
474 // half and look like a working filter.
475 match routed(&shell) {
476 Some(Ok(_)) => {}
477 Some(Err(e)) => failures.push(format!("{name}: rejected its own shell tool `{}`: {}", target.shell_tool_name(), e.message)),
478 None => failures.push(format!("{name}: hook_format_for found no format for its own shell envelope")),
479 }
480 for foreign in ["Read", "Write", "Edit", "WebFetch"] {
481 let Some(env) = target.sample_envelope(foreign, "rm -rf /") else { continue };
482 checked += 1;
483 if matches!(routed(&env), Some(Ok(_))) {
484 failures.push(format!("{name}: parsed a `{foreign}` envelope instead of abstaining"));
485 }
486 }
487 }
488 assert!(checked > 0, "no target was probed — the guard is vacuous");
489 assert!(failures.is_empty(), "foreign-tool decisions:\n{}", failures.join("\n"));
490 }
491}