Skip to main content

safe_chains/targets/
mod.rs

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