Docs / Agent guard

Agent guard

Agent guard takes a locked snapshot before your coding agent runs a destructive command. safegrd guard backs up a surface, waits until the snapshot is uploaded and locked, and then runs the command. Add it as a hook in your coding agent, and it runs before every shell command that matches the destructive list. If the agent drops a table or resets a database, you have a snapshot from just before.

Run a command behind a snapshot

safegrd guard --surface app-primary -- psql "$DATABASE_URL" -c 'DROP TABLE sessions'
safegrd guard -- npx prisma migrate reset

Guard backs up the surface you name with --surface. Without it, guard uses the only surface in the config, or the database SAFEGRD_DATABASE_URL names if the config lists none. If the backup fails or the snapshot is not locked, the command does not run.

Undo what the command did

Guard prints the snapshot it took. To bring back a table the command dropped or emptied, restore that table from the snapshot. A dropped table is created again as the snapshot defined it, with its sequences, constraints and indexes. An emptied table has its rows loaded back in. The database's other tables are left as they are.

safegrd restore --snapshot snap-20261005-120428-524927 --table public.sessions --target env:DATABASE_URL

For a command that changed more than a few tables, restore the whole snapshot into an empty database instead (Databases).

Exit codeMeaning
the command's ownThe snapshot is locked and the command ran.
3Guard did not run the command: the backup failed or the snapshot is not locked.
1A usage or configuration error.

A snapshot counts as locked when it was written under Object Lock with a retention date in the future. Storage on the host's own disk and a bucket with worm_mode: NONE cannot lock, so guard refuses to run the command there unless you pass --allow-unlocked. Guard prints everything to stderr and leaves stdout to the command.

$ safegrd guard --surface shop -- psql "$DATABASE_URL" -c "DROP TABLE sessions"
Backing up shop before running 'psql postgres://postgres:xxxxx@db:5432/shop?sslmode=disable -c DROP TABLE sessions'
...
[shop] Epoch e202610-3f7f0041 opened (first backup). Every table is uploaded.
[shop] Read 1 table over 4 connections at once, in one snapshot.
[shop] 1 table, 2,000 rows, 93.2 KiB read, 49.2 KiB stored in 2 packs, 309ms.
[shop] Snapshot snap-20261031-182030-2c0a59 complete. Kept until 2026-11-14, not locked: this storage has no Object Lock.
Backed up surface shop
Error: not running 'psql postgres://postgres:xxxxx@db:5432/shop?sslmode=disable -c DROP TABLE sessions': snapshot snap-20261031-182030-2c0a59 was written but is not locked: it is in a directory on this host, which has no Object Lock. Point this host at a bucket with Object Lock, or pass --allow-unlocked
$ echo "exit=$?"
exit=3
$ psql "$DATABASE_URL" -Atc "select count(*) from sessions"
2000
Guard on a host whose storage is a directory on its own disk. It took the snapshot, refused to run the command because the snapshot is not locked, and exited 3. The table still has its 2,000 rows. Run on 31 October 2026 with the CLI released on 25 October, against PostgreSQL 17 in Docker. One warning about the test database's sslmode is cut.

Reuse a recent snapshot

An agent often runs several destructive commands in a row. Pass --max-age and guard reuses a locked snapshot of the surface younger than that, and tells you which one. If there is none, it backs up as usual. An unlocked snapshot is never reused, so with --allow-unlocked every command takes a new backup.

safegrd guard --max-age 30m -- psql "$DATABASE_URL" -c 'TRUNCATE sessions'

--check-only takes no backup. Guard refuses the command (exit 3) unless a locked snapshot younger than --max-age exists. Use it when the surface's daemon or SafeGrd backs it up, and the host the agent runs on should only check. A snapshot counts if it belongs to this surface, is complete and is still under Object Lock, as safegrd list --json reports it.

safegrd guard --max-age 1h --check-only -- terraform destroy

The destructive list

safegrd guard --list prints the rules. To test a command without taking a backup, run safegrd guard --matches "<command>". It exits 0 if the command matches and 1 if it does not. Guard matches the whole command line, so SQL inside quotes counts.

RuleMatches
SQL DROPDROP TABLE, DATABASE, SCHEMA, VIEW, INDEX, COLUMN and the other object types
SQL TRUNCATETRUNCATE users, TRUNCATE TABLE orders
SQL DELETE without WHEREDELETE FROM users;
dropdbdropdb app
terraform destroyterraform destroy, terraform apply -destroy, and tofu
prismaprisma migrate reset, prisma db push --force-reset
supabase db resetsupabase db reset
railsdb:drop, db:reset, db:schema:load, db:purge
djangomanage.py flush, manage.py reset_db

A command that only mentions one of these, such as grep "DROP TABLE" schema.sql, also matches. That costs you one extra snapshot.

Hooks

Install the CLI and enroll the host first. Then add the hook to the project, naming the surface the agent works on. The recipes for each tool are below.

With --hook, guard reads the hook's JSON on stdin and answers in the tool's own format. A command that does not match is let through at once, with no backup.

A command that matches goes through if the surface has a locked snapshot from the last 30 minutes (--max-age changes the window). Otherwise guard starts a backup and waits up to 20 seconds for it (--wait). If the backup finishes in time, the command runs. If not, guard blocks the command and tells the agent to run it again shortly. The backup keeps going in its own process, and the retry goes through once the snapshot is locked.

So a backup that finishes within 20 seconds costs the agent that wait, and a longer one costs it one retry. You use the same hook line whatever the size of the database.

What safegrd guard --hook decides for each shell command an agent runs. A command not on the destructive list runs at once with no backup. For one on the list, a locked snapshot of the surface from the last 30 minutes lets it run. Otherwise guard starts a backup and waits up to 20 seconds. Locked in time: the command runs. Still running: the command is denied with a message to run it again shortly, the backup keeps going, and the retry goes through once the snapshot is locked. Failed or not locked: the command is denied with the reason. Agent's shell command On the destructive list? safegrd guard --hook Runs at once no backup Locked snapshot from the last 30 minutes? Runs --max-age 30m Back up, wait up to 20s --wait 20s no yes yes no Locked command runs Still running denied: retry Failed denied, says why
What the hook answers for one shell command. A command it denies while the backup runs goes through on the agent's retry, once the snapshot is locked.

To let a command through, guard exits 0. For Claude Code, it also prints the snapshot that covers the command and the restore command, and the agent sees both. Codex gets no output, and Cursor gets {"permission":"allow"}. Letting a command through is not the same as approving it. The tool's own permission settings still decide.

To block a command, guard prints the tool's deny answer with the reason. If a backup fails or is not locked, the command is blocked and the agent is told why. With --check-only, guard takes no backup and blocks the command unless there is a recent locked snapshot.

If guard itself cannot run (the binary is missing from the agent's PATH, or a flag is wrong), the agent's tool would let the command through. Every recipe below ends with a fallback that blocks the command in that case.

Claude Code

Add this to .claude/settings.json. If you have the Claude Code plugin installed, ask Claude to set up the SafeGrd guard hook and it adds this for you.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "safegrd guard --hook claude-code --surface app-primary || exit 2",
            "timeout": 60
          }
        ]
      }
    ]
  }
}

Cursor

Add this to .cursor/hooks.json:

{
  "version": 1,
  "hooks": {
    "beforeShellExecution": [
      {
        "command": "safegrd guard --hook cursor --surface app-primary || echo '{\"permission\":\"deny\",\"agent_message\":\"safegrd guard could not run\"}'",
        "timeout": 60
      }
    ]
  }
}

Codex

Add this to .codex/hooks.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "safegrd guard --hook codex --surface app-primary || exit 2",
            "timeout": 60
          }
        ]
      }
    ]
  }
}

Check the setup

safegrd doctor --agent-proof

This checks what an agent on this host could reach, and prints the fix for each check that fails. Add --json for a result you can share.

CheckPasses when
Bucket in another accountThe bucket and the database are with different providers, or the bucket is SafeGrd's hosted storage. If both are with one provider, the config cannot tell the accounts apart, and the check says so.
Storage key cannot deleteThe bucket refuses to let this host's key delete. The check tries the delete on an object path that no snapshot uses.
Object Lock in compliance modeworm_mode is COMPLIANCE and the bucket has Object Lock enabled.
Drill passed in 7 daysSafeGrd has a passed Fire Drill for each surface from the last 7 days.
Agent uses a personal tokenThe agent configurations on this host give SafeGrd a personal access token (sg_pat_), or use the local safegrd mcp.