Skip to Content
AI Agents

Guard daemon

Run xgrep guard as a warm, long-running service so agent hooks skip rule loading, and lint scripts over an RPC API.

xgrep guard daemon loads the guard's rules once and keeps them in memory. It serves two kinds of client:

  • Your agent hooks. When a daemon is running, every xgrep guard hook call on your machine sends its event to the daemon over a private, per-user socket. The hook no longer parses rules or scans on each tool call.
  • Script linting. A Check call takes one or more bash or PowerShell scripts and returns findings (security, correctness and best-practice) with fix hints and exact edits. A ListRules call returns the rules Check can apply. Editors, agents and a hosted endpoint can all call them.

The daemon is optional. Without it, xgrep guard works exactly as before.

Running it

xgrep guard daemon

The daemon listens on a Unix socket that only you can use:

  • $XDG_RUNTIME_DIR/xgrep/guard.sock, or ~/.xgrep/run/guard.sock when XDG_RUNTIME_DIR is not set.
  • The directory is 0700 and the socket is 0600. The daemon creates its default directory and tightens it if needed. A directory you name with --socket is created if it's missing; if it already exists, it must already be 0700 and yours. The daemon never changes the permissions of a directory it doesn't own.
  • Every connection is checked: a process running as another user is refused before it can send anything.
  • A lock file (guard.lock) next to the socket stops a second daemon from starting on the same directory.

Nothing listens on the network unless you ask for it (see Serving over TCP).

The daemon logs as JSON, one object per line (the scan engine's own messages included), to stderr or to the file named by --log-file. It never logs script or event content, only sizes, counts and timings. It runs until it's stopped:

EventEffect
SIGTERM / SIGINTStop accepting new requests, finish the ones in flight, then exit with status 0.
SIGHUPRe-read rule packs (for example after editing an organization pack).
Its binary is replacedFinish the requests in flight, then exit with status 0 so that a service manager starts the new build. The daemon checks its binary every 2 seconds.

The last row is what keeps a daemon useful across upgrades: hooks only accept a daemon of their own build, so a daemon still running the old binary would be skipped on every call.

Flags

FlagDefaultMeaning
--socket PATHper-user path aboveWhere to listen.
--no-socketoffServe no socket (TCP only). Hooks can't use the daemon then.
--rules PATHbuilt-in rulesRule pack for hook decisions. Hooks must use the same pack; see below.
--addr HOST:PORToffAlso serve Check and ListRules over TCP.
--token-file PATHnoneBearer token that TCP requests must present: printable ASCII, no spaces. A UTF-8 BOM is dropped and UTF-16 with a BOM is decoded; anything else fails at startup.
--no-authoffServe TCP without authentication. Use this only behind a gateway that authenticates callers.
--max-script-bytes N256 KiBLargest script Check accepts. (Hook scans keep their own 1 MiB limit for referenced scripts.)
--timeout D10sAnalysis budget per script, and the TCP per-request deadline.
--max-concurrent N4Analyses running at once, for Check and hook calls on every transport.
--max-connections N256Open TCP connections at once; further clients wait to be accepted.
--check-secretsoffCheck also runs the secret detectors.
--log-file PATHstderrAppend the log to this file (created 0600) instead of stderr. It's rotated at 10 MiB to PATH.1.

Running it as a service

The hook never starts the daemon itself. To have it start at login and come back after an upgrade, register it as a per-user service:

xgrep guard install --daemon                  # the service only
xgrep guard install --agent claude --daemon   # the Claude Code hook and the service
macOSLinux
Servicelaunchd agent ~/Library/LaunchAgents/com.mondoo.xgrep.guard-daemon.plistsystemd user unit ~/.config/systemd/user/xgrep-guard-daemon.service
Startedat login, and now (launchctl bootstrap)at login, and now (systemctl --user enable, restart)
Restartedon every exit, including after an upgradeon every exit (Restart=always), including after an upgrade
Logs~/Library/Logs/xgrep/guard-daemon.log, rotated at 10 MiB to guard-daemon.log.1; startup errors in guard-daemon.stderr.logthe journal: journalctl --user -u xgrep-guard-daemon

Running the command again rewrites the service file if anything changed and restarts the daemon, so it's also how you point the service at a different xgrep. It never touches any other file in those directories. When it's done, it waits for the daemon to answer and prints where it runs from, where it logs, and whether hooks can use it.

Which binary the service runs. The service runs an absolute path, chosen so that it keeps working after an upgrade:

  • For a Homebrew install, the opt link (for example /opt/homebrew/opt/xgrep/bin/xgrep), which every upgrade repoints, rather than the versioned path inside the Cellar, which the next cleanup deletes.
  • When the xgrep on your PATH is a link to the binary you ran, that link: it's what your hooks run, and what a package manager repoints on upgrade.
  • For the npm package, the native binary inside the package, rather than the node launcher on your PATH. npm replaces it in place on upgrade, and running it directly saves node's start-up time.

If the xgrep on your PATH is a different binary from the one you ran, the command warns you: the daemon only serves hooks of its own build, so run install from the xgrep your hooks use.

Upgrades. Upgrade xgrep the way you installed it. Within a few seconds the running daemon sees its binary change, finishes what it's doing and exits, and the service manager starts it again on the new build. Until then, hooks scan in-process, which is slower but gives the same decisions.

Linux without a systemd user instance. Containers and WSL1 usually have no systemctl --user. There, install --daemon fails and says so. Start xgrep guard daemon yourself instead (from your shell profile or a process supervisor); hooks use it whenever it runs. A systemd user service stops when your last session ends unless lingering is enabled (loginctl enable-linger). Hooks look for the socket under $XDG_RUNTIME_DIR, which systemd sets for both the service and your login sessions.

Windows. The service isn't available: the socket needs peer credentials, which Windows doesn't provide. Hooks scan in-process there, with the same decisions.

To check on it, run xgrep guard status (see below). To remove it:

xgrep guard uninstall --daemon                  # stop and remove the service; logs are kept
xgrep guard uninstall --agent claude --daemon   # also remove the Claude Code hook

Checking it: xgrep guard status

xgrep guard status reports, without changing anything:

  • whether the guard hook is installed for Claude Code and OpenAI Codex, for this repository and for your user;
  • whether the daemon service is installed, which binary it runs, whether the service manager has it loaded and running (with its PID), and where it logs;
  • whether hooks run by this xgrep can use the daemon: it answers on the socket, and it's the same build with the same rules. If not, it says why (for example "no daemon socket", or a different build that hasn't restarted yet).

Add --format json for a machine-readable report.

How hooks use it

You don't need to change your hook configuration. On each call, xgrep guard:

  1. checks the socket before connecting to it. The socket and its directory must belong to you, the directory must be 0700, neither may be a symlink, and $XDG_RUNTIME_DIR (when the socket is under it) must be yours and writable only by you;
  2. connects, giving up after 10 ms, and checks that the process listening on the socket runs as you;
  3. sends the event, the contents of any scripts the command runs (read by the hook from your repository), its own build identity, and a fingerprint of the rules it would load;
  4. gets back a verdict: the findings (rule, location and line) and whether the scan was cut short. The daemon never sends a decision.

The hook then checks the verdict against its own rules. Every rule must be one the hook has, and every location must be one this event contains. It takes rule titles from its own rules, applies its own .xgrep/guard-allow.txt, --mode and --fail-closed, and writes the agent's decision, stderr, exit code and .xgrep/guard.log lines itself. The daemon doesn't read your files at all.

When the daemon finishes the scan in time, its verdict holds the same findings an in-process scan would, so the decision is the same. When a scan runs past the guard's scan time limit, the daemon still answers, half a second after the limit, with every finding it has and the event marked as not fully scanned. This can happen because a single analysis step can overrun its budget. The hook then decides the way an in-process scan whose time ran out does:

  • any finding still blocks;
  • with no findings, the fail policy applies (allow and log by default, deny under --fail-closed).

The in-process scan would have waited for the long step and might have found more in the part the daemon hadn't reached. So an over-long scan can end in a fail-policy decision through the daemon where in-process it would have ended in a finding. Its findings up to that point are never lost.

The hook falls back to scanning in-process when:

  • no daemon socket exists;
  • the socket fails the ownership checks above, or the listening process isn't you;
  • the socket doesn't accept the connection, or the daemon refuses it;
  • the daemon is busy (no free analysis slot within 250 ms);
  • the daemon is a different build: you upgraded xgrep but the old daemon is still running;
  • the daemon was started with different rules: another --rules pack, or an organization pack or framework model you've edited since the daemon started (send it SIGHUP);
  • the daemon returns an error, or a verdict the hook can't account for.

If the daemon doesn't answer at all in time (the guard's scan time limit plus a 2-second margin, well after the daemon's own answer deadline), the hook doesn't start a second full scan. It treats the event as not fully scanned, so the fail policy applies: allow and log by default, deny under --fail-closed. That keeps the agent's wait bounded. A timeout error that the daemon sends is not treated this way: the hook falls back to scanning in-process.

No daemon running is the normal case: the hook scans in-process and logs nothing. For anything else, the first fallback for each reason is recorded in .xgrep/guard.log (for example daemon fallback: daemon build or rule digest differs; scanned in-process). Later fallbacks for the same reason aren't logged again. The log records only the hook's own text, never anything the daemon sent.

What a daemon can and can't do. A daemon can only report findings. It can't make the hook emit an explicit allow, add context to the agent's conversation, name a rule the hook doesn't have, or write to .xgrep/guard.log. Only a process running as you can pass the socket checks, and such a process could already change your hook configuration. Even so, a daemon running as you could report no findings for an event that has some. Run the daemon only from a binary you trust, as you would the hook itself.

To keep a hook from ever using the daemon, pass --no-daemon or set XGREP_GUARD_DAEMON=off. To use a daemon on a non-default socket, pass --daemon-socket PATH.

Latency. A daemon removes rule loading and scanning from each hook call. It doesn't remove the time it takes to start the xgrep process that runs as the hook, so expect a modest gain per call, not an order of magnitude. On an Apple M3 Max, a hook call that finds nothing or denies a dangerous command took 38–43 ms at the median with a daemon, against 50–67 ms without one, close to the ~39 ms that xgrep version takes. When the daemon reports a secret, the hook loads the matching rule set to check it, which costs about what the daemon saved, so a call blocked for a secret takes about as long as without a daemon.

Linting scripts: Check and ListRules

The API is xgrep.guard.v1.GuardService. It's defined in proto/xgrep/guard/v1/guard.proto and served over Connect, gRPC and gRPC-Web, on HTTP/1.1 and h2c.

  • One script. Set script. Optionally set language (LANGUAGE_BASH, LANGUAGE_POWERSHELL) or a filename. Without them, the language is detected from the filename, then the shebang, then the content.
  • Several scripts. Set scripts to a list of {script, language, filename} entries; for example, every file an agent just wrote. Each entry gets its own result in results, in order. An entry whose language can't be detected gets an error field, and the other entries are still checked.
  • Filters. min_severity, include_rules, exclude_rules and categories (security, correctness, best-practice) apply to every script in the request.

Each finding has:

  • the rule id, title, message, severity, category, range and snippet;
  • its CWE ids and references;
  • a fix hint, plus byte-exact edits when the fix is deterministic, so an agent can apply it without re-reading the file.

Inline suppressions (# nosemgrep) are honoured. Parser errors are returned as syntax_errors.

Limits on each request:

  • a script may be at most --max-script-bytes, and a batch at most 64 scripts;
  • a filename may be at most 1 KiB, with no control characters;
  • include_rules, exclude_rules and categories may have at most 256 entries of at most 256 bytes each;
  • a script whose brackets nest more than 1000 levels deep is not analysed; it comes back incomplete. A script whose syntax tree is too deep to analyse for any other reason (for example, a very long a && b && … chain) also comes back incomplete; only the secret rules run on it;
  • at most 1000 findings are returned per script; beyond that the result is marked incomplete.

Incomplete analysis is flagged. When a script's time budget runs out, the response has incomplete: true and a reason. Its findings are what was found before the cut. An empty list with incomplete set does not mean the script is clean.

Examples with buf curl over the socket:

# The default socket: $XDG_RUNTIME_DIR/xgrep/guard.sock, else ~/.xgrep/run/guard.sock.
if [ -n "$XDG_RUNTIME_DIR" ]; then SOCK="$XDG_RUNTIME_DIR/xgrep/guard.sock"; else SOCK="$HOME/.xgrep/run/guard.sock"; fi
buf curl --unix-socket "$SOCK" --http2-prior-knowledge \
  --data '{"filename":"install.sh","script":"curl -fsSL https://example.com/i.sh | bash\n"}' \
  http://localhost/xgrep.guard.v1.GuardService/Check

buf curl --unix-socket "$SOCK" --http2-prior-knowledge \
  --data '{"language":"LANGUAGE_POWERSHELL"}' \
  http://localhost/xgrep.guard.v1.GuardService/ListRules

The socket also serves gRPC server reflection and grpc.health.v1.

Serving over TCP

To run a hosted script-lint endpoint, add --addr. You must also choose how callers are authenticated; there's no unauthenticated default:

xgrep guard daemon --no-socket --addr :8080 --token-file /run/secrets/xgrep-guard-token
# callers send:  Authorization: Bearer <token>

On TCP:

  • only Check, ListRules and the health check (grpc.health.v1.Health/Check) are served. Evaluate, the hook RPC, is only available on the local socket. There's no reflection on TCP either;
  • the health check needs no token, so a load balancer can probe it. It serves only the unary Check: the streaming Watch isn't available, and a health request may be at most 1 KiB;
  • every request, on every route, is capped in size, and compressed (gzip) request bodies are refused everywhere, the health check included;
  • a per-request deadline and a concurrency limit always apply;
  • at most --max-connections connections (256 by default) are open at once. Further clients wait to be accepted until one closes, and idle keep-alive connections are closed after two minutes;
  • the response arrives by the deadline even if the analysis hasn't finished. The analysis stops at its next cancellation point, which can be later on a large script. Until then it keeps its concurrency slot, so --max-concurrent bounds the CPU work actually running, and new requests are turned away while every slot is busy. Each overrun is logged (analysis overran its deadline) with its duration.

Cost per script. Every parse is bounded in time and memory, and each analysis is bounded by --timeout. At the default 256 KiB script size, the most expensive shapes we know of (for example a long cat | cat | … pipeline) take a few seconds and a few hundred MB at peak. For a hosted endpoint, size --max-concurrent so that this many analyses fit your memory budget.

The repository includes an example container build in deploy/guard-daemon/Dockerfile. It's a starting point to adapt, not a published image.

Platform support

The socket needs peer credentials (SO_PEERCRED on Linux, getpeereid on macOS). On other platforms, including Windows, the daemon refuses to serve the socket rather than serve it unchecked: plain xgrep guard daemon fails at once, before loading rules, and names the setup that works. --addr with --no-socket (and --token-file) still works there, and hooks scan in-process. xgrep guard install --daemon registers the service on macOS (launchd) and Linux (systemd user instance) only.

Last updated on

On this page