A guard for AI coding agentsRelease 0.17.2
Stop the commands you can’t undo.
dcg is a hook that runs before every shell command your coding agent sends. It reads each command the way your shell will and blocks the few that destroy work, such as git reset --hard, git push --force and rm -rf ./src. The agent gets a reason and a safer command to try. Everything else runs as if dcg weren’t there.
Works with Claude Code, Codex CLI, Gemini CLI, GitHub Copilot, Cursor and twelve more agents.
3 ran1 stopped
Inspect a recorded verdict
git reset --hard HEAD~3core.git:reset-hardCritical
git reset --hard destroys uncommitted changes. Use 'git stash' first.
dcg test --dialect posix 'git reset --hard HEAD~3'Every verdict on this page was recorded from dcg 0.17.2 with no config file. Pick a command above, or click one in the stream. dcg test only evaluates a command; it never runs it.
- 104packsThree are on from the start. The other 101, for databases, Kubernetes, cloud CLIs and other tools, are one line of config away.
- 1,196blocking rulesEach with a stable ID, a severity, and a reason written for the agent.
- 17coding agentsEach answered in the hook format it actually enforces.
- 1,000 msdeadlineIf evaluation runs out of time, the command waits for review. It is never waved through.
01The risk
One command can erase a day of work.
Coding agents run hundreds of shell commands in a session, and almost all of them are harmless. The dangerous ones look just as ordinary. An agent cleaning up after a failed pull types git checkout -- ., and every uncommitted change in the repository is gone. Git never stored those changes, so nothing can bring them back.
Seven ordinary tasks
Reasonable tasks, irreversible commands.
None of these needs a malicious agent. Each command is the shortest path to the goal the agent was given, and each destroys something that has no backup.
Pick a task. See the command an agent reaches for, what it would destroy, and what dcg does.
Recorded outputThe agent runs
git checkout -- .
What it destroys
Every uncommitted edit in the repository. Git never stored them, so there is nothing to recover.
core.git:checkout-discardHighgit checkout -- discards uncommitted changes permanently. Use 'git stash' first.
What dcg suggests instead
git stashSave changes temporarily, restore later with 'git stash pop'git diff <path>Review what would be lost before discarding
The agent runs
git reset --hard origin/main
What it destroys
Uncommitted work, plus any local commits that were never pushed.
core.git:reset-hardCriticalgit reset --hard destroys uncommitted changes. Use 'git stash' first.
What dcg suggests instead
git reset --soft <ref>Move HEAD but keep all changes stagedgit reset --mixed <ref>Move HEAD, unstage changes, keep working dir (default)git stashSave changes before resetting
The agent runs
git push --force origin main
What it destroys
The commits teammates pushed since the agent last fetched. They vanish from the remote branch.
core.git:push-force-longCriticalForce push can destroy remote history. Use --force-with-lease if necessary.
What dcg suggests instead
git push --force-with-leaseOnly forces if remote matches your last fetch
The agent runs
git clean -fdx
What it destroys
Every untracked file: new source files not yet added, local .env files, notes, test fixtures.
core.git:clean-forceCriticalgit clean -f/--force removes untracked files permanently. Review with 'git clean -n' first.
What dcg suggests instead
git clean -nDry-run, shows what would be deletedgit clean -iInteractive mode, choose what to delete
The agent runs
rm -rf "$BUILD_DIR/"*With BUILD_DIR unset, the shell runs rm -rf /*
What it destroys
If BUILD_DIR is empty in the agent's shell, everything under / that the user can write to.
core.filesystem:rm-rf-generalHighrm -rf is destructive and requires human approval. Explain what you want to delete and why, then ask the user to run the command manually.
The agent runs
psql -c "DROP TABLE users"
What it destroys
The table and its rows, in whatever database the connection string points at.
database.postgresql:drop-tableHighwith database.postgresql onDROP TABLE permanently deletes the table (even with IF EXISTS). Verify and back up first.
The agent runs
git stash clear
What it destroys
Every stash entry, including the work set aside hours ago.
core.git:stash-clearCriticalgit stash clear permanently deletes ALL stashed changes.
What dcg suggests instead
git stash drop stash@{n}Remove one specific stash at a timegit stash listReview what would be lost firstgit stash show stash@{n}Inspect each stash before deciding
What the agent sees
A block the agent can act on.
A bare refusal leaves an agent guessing, and a guessing agent may try the same thing another way. dcg’s answer names the rule, explains what the command would destroy, offers a safer command, and tells the agent not to reword the command to get it past the guard. The agent can then reach its goal another way, such as stashing instead of discarding.
Step through a session. The right side shows exactly what dcg sent back to the agent.
Interactive-
git pull --rebase origin mainRanerror: cannot pull with rebase: You have unstaged changes. error: Please commit or stash them.
AgentThe working tree is dirty. Discard the changes and pull again.
-
git checkout -- .Blocked by dcgcore.git:checkout-discard: git checkout -- discards uncommitted changes permanently. Use 'git stash' first.
AgentBlocked. The reason says to stash first, so stash instead.
-
git stash push -m "wip: retry backoff"RanSaved working directory and index state On main: wip: retry backoff
-
git pull --rebase origin mainRanSuccessfully rebased and updated refs/heads/main.
-
git stash popRanOn branch main Changes not staged for commit: modified: src/retry.rs
-
cargo test --workspaceRantest result: ok. 214 passed; 0 failed; 0 ignored
What dcg sent back
Three ways to run an agent
Ask about the few commands that matter.
Approval prompts ask about every command. After the fiftieth git status, people stop reading them or switch them off. dcg lets routine commands run and stops only the ones that destroy work, which is when a person should be looking.
Compare where your attention goes under each setup.
| Question | Approve every command | Skip all approvals | With dcg |
|---|---|---|---|
| Who reads each command | You, every time | Nobody | dcg, before it runs |
git status | Waits for your click | Runs | Runs |
git reset --hard | Looks like the 200 approvals before it | Runs, and the work is gone | Stops with a reason; you can approve it once |
| What it asks of you | Attention on every command | Nothing, until something is lost | Attention only when something would be destroyed |
| Runs unattended | No | Yes | Yes |
--dangerously-skip-permissions and Gemini CLI’s --yolo, for example.02Precision
It reads commands the way the shell does.
A list of forbidden strings fails in both directions. It misses rm -r'f' ~, which the shell runs as rm -rf ~, and it blocks grep "rm -rf" notes.md, which deletes nothing. dcg parses the command line first: quoting, wrappers, pipes, nested shells, heredocs and inline scripts. Then it judges only what will execute.
A substring filter against dcg
Try to write a better filter.
A homemade guard is usually a list of dangerous strings. The left column runs one in your browser. The right column is what dcg did with the same commands. Edit the expression and see how many rows you can get right without breaking others.
Edit your filter and try to get every row right.
Interactive| Command | Your filter | dcg |
|---|---|---|
git reset --hard HEAD~3 | Blockedcorrect | Blockedcorrectcore.git:reset-hard |
sudo env git reset --hardWrappers are stripped first | Blockedcorrect | Blockedcorrectcore.git:reset-hard |
/usr/bin/git reset --hard | Blockedcorrect | Blockedcorrectcore.git:reset-hard |
git -C ./app reset --hardOptions before the subcommand | Allowedwrong | Blockedcorrectcore.git:reset-hard |
bash -c 'git reset --hard'A nested shell is read too | Blockedcorrect | Blockedcorrectcore.git:reset-hard |
git status && git reset --hard | Blockedcorrect | Blockedcorrectcore.git:reset-hard |
rm -r'f' ~The shell joins r and 'f' into -rf | Allowedwrong | Blockedcorrectcore.filesystem:rm-rf-root-home |
RM -rf ~On macOS and Windows, RM finds the rm binary | Allowedwrong | Blockedcorrectcore.filesystem:rm-rf-root-home |
{rm,-rf,~}Brace expansion produces rm -rf ~ | Allowedwrong | Blockedcorrectcore.filesystem:rm-rf-root-home |
rm${IFS}-rf${IFS}~$IFS expands to a space | Allowedwrong | Blockedcorrectcore.filesystem:rm-rf-root-home |
echo 'rm -rf ~' | bash | Blockedcorrect | Blockedcorrectcore.filesystem:rm-rf-root-home |
find ~ -exec rm -rf {} + | Blockedcorrect | Blockedcorrectcore.filesystem:rm-rf-general |
git push origin +mainA leading + forces the push | Allowedwrong | Blockedcorrectcore.git:push-force-refspec |
alias x='rm -rf ~'; x | Blockedcorrect | Blockedcorrectcore.filesystem:rm-rf-root-home |
cat <<'EOF' | bash
git reset --hard origin/main
EOF | Blockedcorrect | Blockedcorrectcore.git:reset-hard |
python3 -c "import shutil; shutil.rmtree('/home/me/project')" | Allowedwrong | Blockedcorrectheredoc.python:shutil_rmtree |
python3 -c "import os; os.system('git reset --hard')" | Blockedcorrect | Blockedcorrectheredoc.python:os_system.git_reset_hard |
python3 - <<'PY'
import shutil
shutil.rmtree("/srv/app")
PY | Allowedwrong | Blockedcorrectheredoc.python:shutil_rmtree |
node -e "require('fs').rmSync('/Users/me/app', {recursive: true, force: true})" | Allowedwrong | Blockedcorrectheredoc.javascript:fs_rmsync.non_temp |
node -e "require('child_process').spawnSync('rm',['-rf','/tmp/x','/'])"The harmless first target is a decoy; the second is / | Allowedwrong | Blockedcorrectheredoc.javascript:exec_sink.rm_rf_catastrophic |
ruby -e "require 'fileutils'; FileUtils.rm_rf(Dir.home)" | Allowedwrong | Blockedcorrectheredoc.ruby:fileutils_rm_rf.catastrophic |
perl -e 'use File::Path; rmtree("/home/me")' | Allowedwrong | Blockedcorrectheredoc.perl:file_path.rmtree |
grep -rn "rm -rf" docs/ | Blockedwrong | Allowedcorrect |
rg "git reset --hard" README.md | Blockedwrong | Allowedcorrect |
git commit -m "Stop running rm -rf in the cleanup script" | Blockedwrong | Allowedcorrect |
echo "never run git reset --hard on a dirty tree" | Blockedwrong | Allowedcorrect |
git log --grep="force push" | Allowedcorrect | Allowedcorrect |
cat > NOTES.md <<'EOF'
Never run: git clean -fdx
EOFWriting text to a file runs nothing | Blockedwrong | Allowedcorrect |
man git-reset | Allowedcorrect | Allowedcorrect |
git checkout -b fix/retry | Allowedcorrect | Allowedcorrect |
rm -rf /tmp/build | Blockedwrong | Allowedcorrect |
git push --force-with-lease origin feature | Blockedwrong | Allowedcorrect |
git restore --staged src/main.rs | Allowedcorrect | Allowedcorrect |
git clean -n | Allowedcorrect | Allowedcorrect |
git reset --soft HEAD~1 | Allowedcorrect | Allowedcorrect |
python3 -c "import shutil; shutil.rmtree('/tmp/build')" | Allowedcorrect | Allowedcorrect |
Heredocs and inline scripts
Code inside a command gets parsed too.
When a command hands code to an interpreter, through python3 -c, node -e, a heredoc or a pipe, dcg pulls the code out and parses it with a real grammar for that language. A call that deletes a directory or runs git reset --hard is caught where a text search would see only a string.
Follow one command through the three stages that handle embedded code.
Recorded output- 1
Notice
A fast first pass over the whole command sees an interpreter reading a heredoc. Commands without one skip the next two steps.
python3 - <<'PY' import shutil shutil.rmtree("/srv/app") PY - 2
Extract
The body between the markers is pulled out, with limits on its size and on the time spent.
import shutil shutil.rmtree("/srv/app") - 3
Parse
A Python grammar turns the body into a syntax tree. The rules look for calls such as
shutil.rmtree,os.remove,os.systemandsubprocess.run, then check what they are pointed at.import shutil shutil.rmtree("/srv/app")
heredoc.python:shutil_rmtreeCriticalEmbedded python code blocked: shutil.rmtree() recursively deletes directories (rule heredoc.python:shutil_rmtree, line 2, matched: shutil.rmtree("/srv/app"))Languages it parses
- Python
- JavaScript
- TypeScript
- Ruby
- PHP
- Go
- Bash and other shells
- Perl, by pattern
More one-liners, recorded
python3 -c "import os; os.system('git reset --hard')"Blockedheredoc.python:os_system.git_reset_hardnode -e "require('child_process').spawnSync('rm',['-rf','/tmp/x','/'])"Blockedheredoc.javascript:exec_sink.rm_rf_catastrophicThe harmless first target is a decoy; the second is /ruby -e "require 'fileutils'; FileUtils.rm_rf(Dir.home)"Blockedheredoc.ruby:fileutils_rm_rf.catastrophicperl -e 'use File::Path; rmtree("/home/me")'Blockedheredoc.perl:file_path.rmtree
PowerShell and cmd.exe
Windows shells are covered too.
dcg ships a native Windows binary and reads PowerShell and cmd.exe syntax as well as POSIX shells. On Windows, and for any request that arrives from a PowerShell or cmd.exe tool, it also turns on the windows.filesystem and windows.system packs.
Recorded verdicts for Windows shell commands, sent through each agent’s PowerShell or shell tool.
Recorded output- PowerShell
Remove-Item -Recurse -Force C:\srcBlockedcore.filesystem:powershell-remove-item-recursive - PowerShell
Get-ChildItem C:\srcAllowed - PowerShell
Format-Volume -DriveLetter DBlockedcore.filesystem:format-volume - PowerShell
vssadmin delete shadows /all /quietBlockedcore.filesystem:vssadmin-delete-shadows - cmd.exe
rd /s /q C:\Users\me\projectBlockedwindows.filesystem:rd-recursiveSent through a Bash tool; the hook recognizes cmd.exe syntax
03Agents
One guard for every agent you run.
Each coding agent has its own hook format, and they disagree about what a refusal looks like. Codex rejects fields it doesn’t know. Reasonix reads only the exit code. Hermes never blocks on an exit code at all. A hook that answers in the wrong shape gets ignored, and the command runs anyway. dcg works out which agent called it and answers in that agent’s format.
17 agents, one binary
The same block, in each agent’s format.
A hook that prints the wrong shape fails silently: the agent sees no refusal and runs the command. dcg’s release-blocking suite sends eleven agent request formats to the real binary and checks what comes back. The panel below shows recordings for all seventeen.
Pick an agent. See the request it sends and the exact answer dcg gives it.
InteractiveClaude Code
A PreToolUse hook covering the Bash, PowerShell and Monitor tools. The denial carries the rule, the reason and a one-time approval code.
dcg install~/.claude/settings.json
Claude Code sends
dcg
{
"tool_name": "Bash",
"tool_input": {
"command": "git reset --hard HEAD~3"
}
}dcg answers exit 0
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "BLOCKED by dcg\n\nTip: dcg explain -- \"git reset --hard HEAD~3\"\n\nReason: git reset --hard destroys uncommitted changes. Use 'git stash' first.\n\nExplanation: git reset --hard discards ALL uncommitted changes in your working directory AND staging area. This is one of the most dangerous git commands because changes that were never committed cannot be recovered by any means.\n \n What gets destroyed:\n - All modified files revert to the target commit\n - All staged changes are lost\n - Untracked files remain (use git clean to remove those)\n \n Safer alternatives:\n - git reset --soft <ref>: Move HEAD but keep all changes staged\n - git reset --mixed <ref>: Move HEAD, unstage changes, keep working dir (default)\n - git stash: Save changes before resetting\n \n Preview what would be lost:\n git status && git diff\n\nRule: core.git:reset-hard\n\nIf a safer alternative reaches the same goal, use it instead. Do not reword, wrap, or split this command to get it past the guard. If no safer path reaches the goal, ask the user to approve this command.\n\nTo permit this single command once, the user can approve it with: dcg allow-once 239045",
"allowOnceCode": "239045",
"allowOnceFullHash": "a5cb18337d2faea2448f5e8c4e58a6bd3604cd0879f0b4222ee583ffccd0d8c5",
"ruleId": "core.git:reset-hard",
"packId": "core.git",
"severity": "critical",
"confidence": 1,
"remediation": {
"safeAlternative": "Consider using 'git stash' first to save your changes.",
"explanation": "git reset --hard discards ALL uncommitted changes in your working directory AND staging area. This is one of the most dangerous git commands because changes that were never committed cannot be recovered by any means.\n\nWhat gets destroyed:\n- All modified files revert to the target commit\n- All staged changes are lost\n- Untracked files remain (use git clean to remove those)\n\nSafer alternatives:\n- git reset --soft <ref>: Move HEAD but keep all changes staged\n- git reset --mixed <ref>: Move HEAD, unstage changes, keep working dir (default)\n- git stash: Save changes before resetting\n\nPreview what would be lost:\n git status && git diff",
"allowOnceCommand": "dcg allow-once 239045"
}
}
}git reset --hard HEAD~3 and the allowed command git status, unedited. Long answers scroll inside their box.Setup
Installed once, found by every agent.
You don’t configure agents one by one. The installer finds the ones on your machine and registers dcg with each. Agents released later can be added with dcg install and a flag.
What happens when you install, in order.
- 1
Install
The installer downloads the binary for your platform and verifies its signature.
dcg_install --easy-mode - 2
Detect
It looks for each supported agent’s config directory or binary on the machine.
~/.claude ~/.codex ~/.gemini ~/.cursor … - 3
Register
It adds dcg to each agent’s hook settings, keeps every other hook in place, and leaves malformed files untouched.
dcg install --grok # or add one later - 4
Check
Doctor verifies every registration.
dcg setupcan also add a shell startup check that warns if Claude Code’s hook ever disappears.dcg doctor
04Packs
Start with git and files. Add your stack.
A fresh install turns on three packs: core.git, core.filesystem and system.disk. The other 101 cover databases, Kubernetes, cloud CLIs, Terraform, secrets managers, CI systems and more than a dozen other kinds of tool. Each stays off until you list it in config.toml, so dcg only judges the tools you actually use.
104 packs, 1,196 blocking rules
Turn on the packs for your tools.
Every pack lists the commands it blocks and the safe forms it lets through, such as terraform plan next to terraform destroy. Read commands stay allowed. Only operations that delete, overwrite or tear down are stopped. Browse every pack and rule.
Tick the packs for the tools you use, and the config file updates as you go.
Interactive104 packs
Core2
- Always on
- Always on
System4
- On by default
Databases9
Kubernetes3
Containers3
Cloud providers3
Infrastructure as code4
Object storage4
Secrets managers5
Secret disclosure1
CI/CD4
Platforms6
CDN and edge3
DNS3
API gateways3
Load balancers4
Messaging4
Search engines4
Monitoring5
Backup4
Email4
Payments3
Feature flags4
Remote copy3
Package managers1
Strict git1
Windows4
Careful company (Windows preset)6
Databases
PostgreSQL
database.postgresql
Protects against destructive PostgreSQL operations like DROP DATABASE, TRUNCATE, and dropdb
10 blocking rules2 safe patterns
drop-databasecriticalDROP DATABASE permanently deletes the entire database (even with IF EXISTS). Verify and back up first.
drop-schemacriticalDROP SCHEMA permanently deletes the schema and all its objects (even with IF EXISTS).
dropdb-clicriticaldropdb permanently deletes the entire database. Verify the database name carefully.
delete-without-wherehighDELETE without WHERE clause deletes ALL rows. Add a WHERE clause or use TRUNCATE intentionally.
# ~/.config/dcg/config.toml
[packs]
enabled = [] # core.git, core.filesystem and system.disk are on alreadyenabled = ["database"] turns on all 9 database packs. Pack descriptions and rules are from release 0.17.2.With the packs on
Each pack knows the safe forms too.
Rows below that share a tool show both sides: the query, the plan and the listing go through, while the drop, the destroy and the prune stop.
Commands for the tools those packs cover, each judged with its pack switched on.
Recorded output| Command | Pack | Verdict |
|---|---|---|
psql -c "DROP TABLE users" | database.postgresql | Blockeddrop-table |
dropdb production | database.postgresql | Blockeddropdb-cli |
psql -c "SELECT count(*) FROM users" | database.postgresql | Allowed |
kubectl delete namespace production | kubernetes.kubectl | Blockeddelete-namespace |
kubectl get pods -n production | kubernetes.kubectl | Allowed |
terraform destroy -auto-approve | infrastructure.terraform | Blockeddestroy |
terraform plan | infrastructure.terraform | Allowed |
docker system prune -af --volumes | containers.docker | Blockedsystem-prune |
docker ps -a | containers.docker | Allowed |
docker compose down -v | containers.compose | Blockeddown-volumes |
aws s3 rb s3://prod-backups --force | cloud.aws | Blockeds3-rb |
aws ec2 terminate-instances --instance-ids i-0abc123 | cloud.aws | Blockedec2-terminate |
redis-cli FLUSHALL | database.redis | Blockedflushall |
mongosh --eval "db.dropDatabase()" | database.mongodb | Blockeddrop-database |
sqlite3 app.db "DELETE FROM orders" | database.sqlite | Blockeddelete-without-where |
gh repo delete acme/api --yes | platform.github | Blockedgh-repo-delete |
wrangler d1 delete prod-db | cdn.cloudflare_workers | Blockedwrangler-d1-delete |
git rebase -i HEAD~5 | strict_git | Blockedrebase |
Custom packs
Write rules for your own tools.
Internal deploy scripts and admin CLIs can do as much damage as rm. A pack is a short YAML file: keywords that wake it up, patterns to block with a reason, and patterns that are always safe. dcg pack validate checks it before you rely on it.
A pack for an in-house deploy tool, checked by dcg before you rely on it.
Recorded outputschema_version: 1
id: acme.deploy
name: Acme deploy tool
version: 1.0.0
description: Stops agents from tearing down shared environments with deployctl.
keywords:
- deployctl
destructive_patterns:
- name: teardown-shared
pattern: 'deployctl\s+teardown\b[^;&|]*?--env[= ](?:staging|production)\b'
severity: critical
description: deployctl teardown deletes a shared environment and its data.
explanation: |
Tear down a preview environment instead, or ask the on-call engineer.
safe_patterns:
- name: teardown-preview
pattern: 'deployctl\s+teardown\b[^;&|]*?--env[= ]preview-[a-z0-9-]+$'
description: Preview environments are disposable.
[packs]
custom_paths = ["~/.config/dcg/packs/*.yaml"]Pack Validation Report
File: acme-deploy.yaml
✓ Pack ID: acme.deploy
✓ Name: Acme deploy tool
✓ Version: 1.0.0
Patterns:
1 destructive patterns
1 safe patterns
Engine Analysis:
2 linear (O(n)), 0 backtracking (100% linear)
✓ Pack is valid and ready to use.deployctl teardown --env productionBlockedacme.deploy:teardown-shareddeployctl teardown --env preview-pr-482AllowedThe safe pattern matches first
05Control
You decide the exceptions.
You can always let a blocked command through. Every denial carries a six-digit code that lets that exact command run once, in that directory, within 24 hours. Rules you trip on purpose go in an allowlist with a reason, an optional expiry and a path scope. Each rule has a stable ID, so the policy can be written down, reviewed and versioned.
Anatomy of a block
Every block says why, and what to do.
The panel goes to the terminal; a plain-text version goes to the agent. Both carry the same facts: the matched text, the rule ID, an explanation, safer commands, and the ways a person can let the command through.
Hover a note to find it in the panel. This is what a person sees on the terminal when dcg blocks.
Recorded output+----------------------------------------------------------------------------+
| ! BLOCKED: Destructive Command Detected |
+----------------------------------------------------------------------------+
| git reset --hard HEAD~3 |
1| ^^^^^^^^^^^^^^^^ |
| |
| |
2| EXPLANATION: |
| git reset --hard discards ALL uncommitted changes in your working |
| directory AND staging area. This is one of the most dangerous git |
| commands because changes that were never committed cannot be recovered |
| by any means. |
| |
| What gets destroyed: |
| - All modified files revert to the target commit |
| - All staged changes are lost |
| - Untracked files remain (use git clean to remove those) |
| |
3| Safer alternatives: |
| - git reset --soft <ref>: Move HEAD but keep all changes staged |
| - git reset --mixed <ref>: Move HEAD, unstage changes, keep working dir |
| (default) |
| - git stash: Save changes before resetting |
| |
| Preview what would be lost: |
| git status && git diff |
| |
| Pattern: reset-hard |
4| Pack: core.git (severity: CRITICAL) |
| Regex: (?:(?:^|[^[:alnum:]_-])git\s+(?:\S+\s+)*|(?:^|[;&|(\n]\s*)(?:[^\s;&|<>()]*/)?git-)reset\b(?:(?!\s--(?:\s|$))[^;&|\n<>()])*?\s--h(?:a(?:rd?)?)?\b |
+----------------------------------------------------------------------------+
Learn more:
5 $ dcg explain -- "git reset --hard HEAD~3"
6 $ dcg allow-once 803080
7 $ dcg allowlist add core.git:reset-hard --user
False positive? File an issue:
https://github.com/Dicklesworthstone/destructive_command_guard/issues/new?template=false_positive.yml- 1The part of the command that matched
- 2What the command destroys, in plain words
- 3Commands that reach the same goal without the loss
- 4The pack, the rule and its severity
- 5A full trace of how dcg decided
- 6A code that lets this exact command run once
- 7Make a lasting exception, by rule ID
What dcg explain prints for the same command
══════════════════════════════════════════════════════════════════
DCG EXPLAIN
══════════════════════════════════════════════════════════════════
Decision: DENY
Latency: 5.2ms
─── Command ───────────────────────────────────────────────────────
Input: git reset --hard HEAD~3
─── Match ─────────────────────────────────────────────────────────
Rule ID: core.git:reset-hard
Pack: core.git
Pattern: reset-hard
Reason: git reset --hard destroys uncommitted changes. Use 'git stash' first.
Explanation: git reset --hard discards ALL uncommitted changes in your working directory AND staging area. This is one of the most dangerous git commands because changes that were never committed cannot be recovered by any means.
What gets destroyed:
- All modified files revert to the target commit
- All staged changes are lost
- Untracked files remain (use git clean to remove those)
Safer alternatives:
- git reset --soft <ref>: Move HEAD but keep all changes staged
- git reset --mixed <ref>: Move HEAD, unstage changes, keep working dir (default)
- git stash: Save changes before resetting
Preview what would be lost:
git status && git diff
Span: bytes 0..16
Matched: git reset --hard
─── Pipeline Trace ────────────────────────────────────────────────
full_evaluation ( 5.0ms) matched keyword "core.git"
─── Suggestions ───────────────────────────────────────────────────
• Preview first: Run `git diff` and `git status` to see what would be lost
$ git diff && git status
• Safer alternative: Use `git reset --soft` or `--mixed` to preserve changes
$ git reset --soft HEAD~1
• Workflow fix: Consider using `git stash` to save changes temporarily
$ git stash
• Documentation: See Git documentation for reset options
→ https://git-scm.com/docs/git-reset
══════════════════════════════════════════════════════════════════
Regex: (?:(?:^|[^[:alnum:]_-])git\s+(?:\S+\s+)*|(?:^|[;&|(\n]\s*)(?:[^\s;&|<>()]*/)?git-)reset\b(?:(?!\s--(?:\s|$))[^;&|\n<>()])*?\s--h(?:a(?:rd?)?)?\bgit reset --hard HEAD~3. The agent receives the same facts as plain text, shown in What the agent sees.Exceptions
Narrow exceptions, each with a record.
An exception should be as small as the need. dcg offers three, scoped to one command, one rule or one rebase. For emergencies, DCG_BYPASS=1 turns the guard off for a single invocation, and dcg doctor reports it whenever it is set.
Pick the narrowest exception that does the job.
Once
For a command you meant to run. The code is tied to the exact command text and directory, is used up by the first run, and expires after 24 hours.
dcg allow-once 803080The denial tells the agent to ask you. The opt-in
careful_company_running_windows.guardrailspack also stops agents from runningdcg allow-onceordcg allowlist addthemselves.Always, with a reason
For a rule your workflow trips on purpose. Entries name the rule, carry a reason, and can be limited to a repository and given an expiry.
dcg allowlist add core.git:reset-hard \ -r "CI resets its scratch clone" \ --path "$PWD" --path "$PWD/**" \ --expires 2027-01-31T00:00:00ZLists, validation and pruning of expired entries are built in.
During a rebase
A failed pull can leave a messy tree, and the usual fix,
git checkout -- ., is one dcg blocks. While.git/rebase-mergeexists, it allows the four discard rules. Afterwards, one command issues a single-use, two-minute permit.dcg rebase-recovergit reset --hard,git clean -fand force pushes stay blocked throughout.
Policy
Deny, ask, warn or log.
Not every match needs a hard stop. Each rule resolves to one of four modes. Medium-severity rules, like dropping a single stash, warn by default: the command runs and the decision is recorded.
Severity sets the default. One line per rule changes it.
| Severity | Default mode | What happens | Example rule |
|---|---|---|---|
| Critical | deny | Blocked | core.git:reset-hard |
| High | deny | Blocked | core.git:checkout-discard |
| Medium | warn | Runs, with a warning on record | core.git:stash-drop |
| Low | log | Runs, recorded silently | cicd.github_actions:gh-actions-run-cancel |
[policy.rules]
"core.git:branch-delete" = "ask" # let the agent propose it; a person approves
"core.git:stash-drop" = "deny" # stricter than the default warn
"core.filesystem:rm-rf-general" = "warn" # let it run, but keep a recordA broad warn or log, for a whole pack or as the global default, is raised back to deny for critical rules. Relaxing a critical rule takes an entry naming that rule. ask requests a person’s review where the agent supports it, and blocks where it doesn’t.
Trust boundary
A cloned repository can’t loosen your guard.
Projects can ship a .dcg.toml, and dcg reads it automatically. Because a repository is untrusted the moment you clone it, that file may only add protection. Anything that grants trust is ignored unless you choose the file yourself.
What a .dcg.toml in a freshly cloned repository is allowed to change.
It can tighten
- Turn on built-in packs
- Add
denyentries for rules - Block on unreadable hook input (
fail_closed) - Turn on heredoc scanning, or remove its fallbacks
- Refuse commands dcg couldn’t verify in time
It can’t loosen
- Allow a command or a rule
- Turn packs off
- Load custom packs or regular expressions
- Raise size limits or narrow the scanned languages
- Exempt paths, or rewrite the text agents read
- Activate its own checked-in allowlist
DCG_CONFIG=.dcg.toml. A symlinked .dcg.toml is refused on every platform.06Review
Catch it in review, before any agent runs it.
The same rules run outside the hook. dcg scan reads Dockerfiles, CI workflows, Makefiles, package.json scripts, Terraform provisioners, Compose files and shell, PowerShell and batch scripts. It pulls out only the commands that will execute, skips comments and data, and runs as a pre-commit hook or a CI step.
dcg scan
It knows which lines will execute.
A grep for rm -rf flags comments, docs and test fixtures. The scanner reads each file in its own format: the RUN lines of a Dockerfile, the run: steps of a workflow, the recipe lines of a Makefile, the scripts of package.json. Then it judges those commands with the same rules as the hook.
Open each file in a small repository. Highlighted lines are what dcg scan reported.
1FROM node:22-slim2WORKDIR /app3COPY . .4RUN npm ci && npm run build5RUN rm -rf /app/srccore.filesystem:rm-rf-general1name: deploy2on: push3jobs:4 deploy:5 runs-on: ubuntu-latest6 steps:7 - uses: actions/checkout@v48 - run: npm test9 - run: git push --force origin HEAD:productioncore.git:push-force-long1build:2 cargo build --release3 4reset:5 git reset --hard origin/maincore.git:reset-hard6 git clean -fdxcore.git:clean-force1{2 "name": "api",3 "scripts": {4 "test": "vitest run",5 "db:reset": "rm -rf ./data && node seed.js"core.filesystem:rm-rf-general6 }7}1#!/bin/sh2# Never run rm -rf ~ here.3echo "cleaning build output"4rm -rf /tmp/api-buildNo findings. The comment is skipped and the path under /tmp is allowed.
Files: 5 considered, 5 scanned, 0 skipped
Commands extracted: 6
Findings: 5 (allow=0, warn=0, deny=5)
Severities: error=5, warning=0, info=0dcg scan --paths . over these five files, which exited 1 because it found blocking commands.Other ways in
Use the rules wherever commands appear.
Commands reach a shell from more places than an agent’s tool call, and the same rules can check them at each one.
The same engine, used outside the agent’s hook.
Before a commit
Install a pre-commit hook that scans staged files and fails the commit on a blocking finding.
dcg scan install-pre-commitIn CI
Scan only what a pull request changed. SARIF output feeds GitHub code scanning and similar dashboards.
dcg scan --git-diff origin/main..HEAD --format sarifAs an MCP server
Agents that speak MCP can ask before they act, with the tools
check_command,scan_fileandexplain_pattern.dcg mcp-serverBefore a rollout
Replay a log of real commands against a new config to see what it would block before you turn it on.
dcg simulate --file commands.logAfter the fact
With history turned on, dcg keeps a redacted record of its decisions and can suggest allowlist entries from repeated blocks.
dcg suggest-allowlist
07Proof
A guard has to be right every time.
dcg runs before every shell command your agents send, so a mistake in it costs either a lost afternoon or a blocked workflow. It is written in Rust with unsafe code forbidden, and release 0.17.2 ships with 7,936 tests, a 732-case regression corpus that includes known bypass attempts, and 11 fuzz targets.
The test suite
Tested like it sits in front of your work.
Much of the suite is regression tests. When a command slips through, or gets blocked when it shouldn’t, the fix lands together with that command as a test, so the same mistake can’t return unnoticed.
Counted from the v0.17.2 source when this site was built.
- 7,936testsUnit and integration tests in the release source.
- 732corpus casesKnown dangerous commands, known safe ones, and spellings meant to slip past, each with the verdict it must get.
- 11fuzz targetsParsers and evaluators fed generated input to find crashes and wrong answers.
- 11agent protocols checked per releaseA release-blocking suite sends each format’s real request to the release binary and checks the answer, the exit code and which stream it went to.
- 3,292commitsIn the repository’s history up to v0.17.2.
- 97tagged versionsFrom the first release to this one.
When it can’t finish
An unfinished check is never a yes.
Evaluation can run out of time, hit a parser limit, or meet input it can’t read. dcg takes the safe side in every case but one: hook input it cannot parse at all is allowed by default, after a scan for destructive commands, and one setting changes that.
What happens in each case where dcg can’t reach a clean answer.
| When | What dcg does | Posture |
|---|---|---|
| Evaluation runs past the 1,000 ms deadline | The result is indeterminate. Agents that support review ask you; the rest block. | Fails closed |
| The command is too large to analyze in full | Treated the same way: review where possible, otherwise blocked. | Fails closed |
| A rule’s regular expression fails partway | Any block it already proved stands. Otherwise review or block, never a silent allow. | Fails closed |
| Embedded code can’t be parsed in time | A bounded fallback scan still checks for the dangerous calls. Strict mode blocks instead. | Falls back |
| A plugin bridge starts dcg but gets no answer | Blocked, with the reason shown, for OpenCode, Oh My Pi and Amp. | Fails closed |
| The session runs without anyone watching | When the agent reports a bypass-permissions mode, unverifiable commands are denied instead of asked about. | Fails closed |
| The hook input itself is malformed JSON | dcg still scans the raw text for a command and blocks it if it is destructive. If none is found, it allows by default; fail_closed = true blocks. | Configurable |
Speed budgets
Fast enough to run on every command.
A guard that slows the agent down gets uninstalled. Most commands contain no keyword any enabled pack cares about, and those leave after a single scan of the text. Only commands that might matter reach the full evaluation.
Each stage of an evaluation has a target, a warning line and a hard ceiling. The scale is logarithmic.
- Quick reject: no relevant keyword1 µs target · 50 µs ceiling
- Check for embedded code5 µs target · 100 µs ceiling
- Detect the embedded language20 µs target · 200 µs ceiling
- Safe command with a keyword75 µs target · 500 µs ceiling
- Full pattern evaluation100 µs target · 1 ms ceiling
- Extract embedded code200 µs target · 2 ms ceiling
- Parse and match embedded code5 ms target · 20 ms ceiling
- Hook deadline, then indeterminate1,000 ms hard stop
src/perf.rs at v0.17.2. The per-stage numbers are design targets that benchmark runs report against. The 1,000 ms deadline is enforced on every hook call, and a release-blocking test measures the hook’s cost against it.Releases
Signed binaries for six platforms.
Native builds for Linux, macOS and Windows, on x86 and ARM, each published with a checksum and a signature.
What you download, and how the installer checks it.
- Linux x86_64static, musl
- Linux ARM64glibc
- macOS Apple Silicon
- macOS Intel
- Windows x64native
- Windows ARM64native
- SHA-256Every archive has a checksum file next to it.
- MinisignEvery archive and installer is signed with the project key
69B3955C8D2E62A8. The verified install recipe checks the installer’s signature and pinned hash before running a line of it. - ProvenanceEach binary records the exact tag and commit it was built from.
dcg --versionprints them, anddcg updaterefuses to replace a local build that is ahead of the release.
Limits
What dcg doesn’t do.
These are the gaps, stated plainly, so you can plan around them.
Four things to know before you rely on it.
It isn’t a sandbox.
dcg assumes an agent that means well and makes mistakes. Someone determined to get around a hook can. Treat it as a guard rail, not a security boundary.
It reads the command line, not the files a command runs.
If an agent writes a script to disk and runs
./cleanup.sh, dcg sees that call, not the script’s contents.It sees shell commands only.
Files an agent changes with its own editing tool never pass through a shell, so dcg never sees them.
It doesn’t replace backups.
Keep committing and pushing. dcg stops the commands that destroy work; it can’t restore what was lost some other way.
08Install
Put dcg in front of your agents.
The installer downloads the binary for your platform, checks its signature, and registers dcg with every supported agent it finds. After that there is nothing to run by hand: each agent calls dcg before every shell command.
Install minisign
The recipe uses it to check the installer’s signature. Get it from your package manager.
brew install minisign # macOS sudo apt install minisign # Debian, UbuntuDefine the verified installer
Paste this function into Bash. It downloads the v0.16.0 installer, refuses to run it unless the Minisign signature verifies against the project key and the SHA-256 matches the pinned value, and only then runs it.
dcg_install() ( # Explicit failure guards also work when called inside `if dcg_install ...`. set -eu umask 077 if [ "$#" -gt 1 ]; then printf '%s\n' 'Usage: dcg_install [--easy-mode|--system]' >&2 exit 1 fi case "${1:-}" in ''|--easy-mode|--system) ;; *) printf '%s\n' 'Usage: dcg_install [--easy-mode|--system]' >&2; exit 1 ;; esac readonly dcg_tag='v0.16.0' readonly dcg_sha256='072462974ad790008e8a3aadb1a9eecf2d9b6bd0ef7b469f69f0fb0fa3b51c7c' readonly dcg_key='RWSoYi6NXJWzaRs1mJmOwwXrZfPWcq6MXnQlNMLBYKzlIQTLwuVQG6uO' dcg_minisign=$(type -P minisign) || { printf '%s\n' 'Install minisign with your trusted OS package manager first.' >&2 exit 1 } dcg_curl=$(type -P curl) || exit 1 dcg_bash=$(type -P bash) || exit 1 if dcg_hash=$(type -P sha256sum); then dcg_hash_kind=sha256sum elif dcg_hash=$(type -P shasum); then dcg_hash_kind=shasum else printf '%s\n' 'A SHA-256 verifier (sha256sum or shasum) is required.' >&2 exit 1 fi dcg_tmp=$(mktemp -d "${TMPDIR:-/tmp}/dcg-install.XXXXXXXXXX") || exit 1 printf 'Installer verification files: %s\n' "$dcg_tmp" dcg_base="https://github.com/Dicklesworthstone/destructive_command_guard/releases/download/$dcg_tag" for dcg_asset in install.sh install.sh.minisig; do "$dcg_curl" --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL \ --max-time 120 --user-agent 'destructive_command_guard-installer' \ "$dcg_base/$dcg_asset" -o "$dcg_tmp/$dcg_asset" || exit 1 done "$dcg_minisign" -Vm "$dcg_tmp/install.sh" \ -x "$dcg_tmp/install.sh.minisig" -P "$dcg_key" || exit 1 if [ "$dcg_hash_kind" = sha256sum ]; then dcg_actual=$("$dcg_hash" "$dcg_tmp/install.sh") || exit 1 else dcg_actual=$("$dcg_hash" -a 256 "$dcg_tmp/install.sh") || exit 1 fi if [ "${dcg_actual%% *}" != "$dcg_sha256" ]; then printf '%s\n' 'Installer does not match the pinned release; refusing execution.' >&2 exit 1 fi case "${1:-}" in --system) # The first elevated command runs only after BOTH checks succeed. sudo -- "$dcg_bash" "$dcg_tmp/install.sh" \ --version "$dcg_tag" --require-minisign --system ;; --easy-mode) "$dcg_bash" "$dcg_tmp/install.sh" \ --version "$dcg_tag" --require-minisign --easy-mode ;; *) "$dcg_bash" "$dcg_tmp/install.sh" \ --version "$dcg_tag" --require-minisign ;; esac )Run it
Easy mode also adds dcg to your PATH. Use
--systemto install to /usr/local/bin with sudo, after verification.dcg_install --easy-mode
Install the binary
The tap covers Apple Silicon and Intel Macs and ARM64 and x86_64 Linux.
brew install dicklesworthstone/tap/dcgRegister the hooks
Homebrew installs only the binary. This finds your agents and adds dcg to each one.
dcg install
Use the verified PowerShell recipe
The PowerShell installer checks its own pinned SHA-256 and Minisign signature before it runs, then requires a signature on the native
dcg.exetoo. It adds dcg to your user PATH, runs a self-test, and configures the agents it finds.What you get
On Windows the
windows.filesystemandwindows.systempacks are on by default, sodel /s,rd /s,Remove-Item -Recurse,formatandvssadmin delete shadowsare blocked from the start.
Build from crates.io
Needs Rust 1.95 or newer. The crates.io build can trail the newest GitHub release;
dcg --versiontells you which you have.cargo install --locked destructive_command_guardRegister the hooks
dcg install
Then check it
Confirm every agent hook is registered and the config parses.
dcg doctorSee a block without risking anything.
dcg testevaluates a command and never runs it.dcg test "git reset --hard HEAD~3"Turn on packs for your stack, then start your agent as usual.
dcg packs --verbose
The verified recipe pins v0.16.0, the release the README currently verifies. Homebrew installs 0.17.2, the release every verdict on this site comes from. Release signing key ID: 69B3955C8D2E62A8.
Release 0.17.2, tagged 2026-11-25
Let agents run the shell without losing work.
dcg costs nothing, runs on Linux, macOS and Windows, and its source is on GitHub under an MIT-based license. Read the code, file an issue when it blocks something it shouldn’t, and watch the repository for new packs.