dcg

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.

Commands from an agent session flow toward dcg. Most pass through to the shell. Destructive ones stop at the gate, where dcg names the rule they hit.

3 ran1 stopped

Inspect a recorded verdict

git reset --hard HEAD~3
Blocked

core.git:reset-hardCritical

git reset --hard destroys uncommitted changes. Use 'git stash' first.

Check it yourselfdcg 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.

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 output

The agent runs

git checkout -- .

What it destroys

Every uncommitted edit in the repository. Git never stored them, so there is nothing to recover.

Blockedcore.git:checkout-discardHigh

git 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.

Blockedcore.git:reset-hardCritical

git reset --hard destroys uncommitted changes. Use 'git stash' first.

What dcg suggests instead

  • git reset --soft <ref>Move HEAD but keep all changes staged
  • git 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.

Blockedcore.git:push-force-longCritical

Force 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.

Blockedcore.git:clean-forceCritical

git 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 deleted
  • git 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.

Blockedcore.filesystem:rm-rf-generalHigh

rm -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.

Blockeddatabase.postgresql:drop-tableHighwith database.postgresql on

DROP 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.

Blockedcore.git:stash-clearCritical

git stash clear permanently deletes ALL stashed changes.

What dcg suggests instead

  • git stash drop stash@{n}Remove one specific stash at a time
  • git stash listReview what would be lost first
  • git 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
  1. git pull --rebase origin mainRan

    error: 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.

  2. git checkout -- .Blocked by dcg

    core.git:checkout-discard: git checkout -- discards uncommitted changes permanently. Use 'git stash' first.

    AgentBlocked. The reason says to stash first, so stash instead.

  3. git stash push -m "wip: retry backoff"Ran

    Saved working directory and index state On main: wip: retry backoff
  4. git pull --rebase origin mainRan

    Successfully rebased and updated refs/heads/main.
  5. git stash popRan

    On branch main
    Changes not staged for commit:
      modified:   src/retry.rs
  6. cargo test --workspaceRan

    test result: ok. 214 passed; 0 failed; 0 ignored
Step 6 of 6

What dcg sent back

git checkout -- .

BLOCKED by dcg

Tip: dcg explain -- "git checkout -- ."

Reason: git checkout -- discards uncommitted changes permanently. Use 'git stash' first.

Explanation: git checkout -- <path> discards all uncommitted changes to the specified files in your working directory. These changes are permanently lost - they cannot be recovered because they were never committed.
             
             Safer alternatives:
             - git stash: Save changes temporarily, restore later with 'git stash pop'
             - git diff <path>: Review what would be lost before discarding
             
             Preview changes first:
               git diff -- <path>
             
             Recovering from a failed `git pull --rebase`?
             Run `dcg rebase-recover` in this repo, then retry the command on its own line (a leading `cd <repo> &&` is fine; nothing else may share the line). This issues a short-lived, single-shot permit that unblocks this rule only. A rebase already in progress (`.git/rebase-merge/` or `.git/rebase-apply/` present) auto-allows the same rule without a permit.

Rule: core.git:checkout-discard

If 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.

To permit this single command once, the user can approve it with: dcg allow-once 598718
The agent’s commands, tool output and thoughts are a typical transcript, written for this page. Every dcg reply is the release binary’s actual output for that command.

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.

QuestionApprove every commandSkip all approvalsWith dcg
Who reads each commandYou, every timeNobodydcg, before it runs
git statusWaits for your clickRunsRuns
git reset --hardLooks like the 200 approvals before itRuns, and the work is goneStops with a reason; you can approve it once
What it asks of youAttention on every commandNothing, until something is lostAttention only when something would be destroyed
Runs unattendedNoYesYes
Skipping approvals is a real setting: Claude Code’s --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
17of 36 rightYour filter
36of 36 rightdcg 0.17.2
CommandYour filterdcg
git reset --hard HEAD~3BlockedcorrectBlockedcorrectcore.git:reset-hard
sudo env git reset --hardWrappers are stripped firstBlockedcorrectBlockedcorrectcore.git:reset-hard
/usr/bin/git reset --hardBlockedcorrectBlockedcorrectcore.git:reset-hard
git -C ./app reset --hardOptions before the subcommandAllowedwrongBlockedcorrectcore.git:reset-hard
bash -c 'git reset --hard'A nested shell is read tooBlockedcorrectBlockedcorrectcore.git:reset-hard
git status && git reset --hardBlockedcorrectBlockedcorrectcore.git:reset-hard
rm -r'f' ~The shell joins r and 'f' into -rfAllowedwrongBlockedcorrectcore.filesystem:rm-rf-root-home
RM -rf ~On macOS and Windows, RM finds the rm binaryAllowedwrongBlockedcorrectcore.filesystem:rm-rf-root-home
{rm,-rf,~}Brace expansion produces rm -rf ~AllowedwrongBlockedcorrectcore.filesystem:rm-rf-root-home
rm${IFS}-rf${IFS}~$IFS expands to a spaceAllowedwrongBlockedcorrectcore.filesystem:rm-rf-root-home
echo 'rm -rf ~' | bashBlockedcorrectBlockedcorrectcore.filesystem:rm-rf-root-home
find ~ -exec rm -rf {} +BlockedcorrectBlockedcorrectcore.filesystem:rm-rf-general
git push origin +mainA leading + forces the pushAllowedwrongBlockedcorrectcore.git:push-force-refspec
alias x='rm -rf ~'; xBlockedcorrectBlockedcorrectcore.filesystem:rm-rf-root-home
cat <<'EOF' | bash git reset --hard origin/main EOFBlockedcorrectBlockedcorrectcore.git:reset-hard
python3 -c "import shutil; shutil.rmtree('/home/me/project')"AllowedwrongBlockedcorrectheredoc.python:shutil_rmtree
python3 -c "import os; os.system('git reset --hard')"BlockedcorrectBlockedcorrectheredoc.python:os_system.git_reset_hard
python3 - <<'PY' import shutil shutil.rmtree("/srv/app") PYAllowedwrongBlockedcorrectheredoc.python:shutil_rmtree
node -e "require('fs').rmSync('/Users/me/app', {recursive: true, force: true})"AllowedwrongBlockedcorrectheredoc.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 /AllowedwrongBlockedcorrectheredoc.javascript:exec_sink.rm_rf_catastrophic
ruby -e "require 'fileutils'; FileUtils.rm_rf(Dir.home)"AllowedwrongBlockedcorrectheredoc.ruby:fileutils_rm_rf.catastrophic
perl -e 'use File::Path; rmtree("/home/me")'AllowedwrongBlockedcorrectheredoc.perl:file_path.rmtree
grep -rn "rm -rf" docs/BlockedwrongAllowedcorrect
rg "git reset --hard" README.mdBlockedwrongAllowedcorrect
git commit -m "Stop running rm -rf in the cleanup script"BlockedwrongAllowedcorrect
echo "never run git reset --hard on a dirty tree"BlockedwrongAllowedcorrect
git log --grep="force push"AllowedcorrectAllowedcorrect
cat > NOTES.md <<'EOF' Never run: git clean -fdx EOFWriting text to a file runs nothingBlockedwrongAllowedcorrect
man git-resetAllowedcorrectAllowedcorrect
git checkout -b fix/retryAllowedcorrectAllowedcorrect
rm -rf /tmp/buildBlockedwrongAllowedcorrect
git push --force-with-lease origin featureBlockedwrongAllowedcorrect
git restore --staged src/main.rsAllowedcorrectAllowedcorrect
git clean -nAllowedcorrectAllowedcorrect
git reset --soft HEAD~1AllowedcorrectAllowedcorrect
python3 -c "import shutil; shutil.rmtree('/tmp/build')"AllowedcorrectAllowedcorrect
The filter runs in your browser as a JavaScript regular expression. Each dcg verdict was recorded from release 0.17.2. A row counts as right when the verdict matches what the command does: block it if running it destroys something, allow it if not.

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. 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. 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. 3

    Parse

    A Python grammar turns the body into a syntax tree. The rules look for calls such as shutil.rmtree, os.remove, os.system and subprocess.run, then check what they are pointed at.

    import shutil
    shutil.rmtree("/srv/app")
Blockedheredoc.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_hard
  • node -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.catastrophic
  • perl -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
  • PowerShellRemove-Item -Recurse -Force C:\srcBlockedcore.filesystem:powershell-remove-item-recursive
  • PowerShellGet-ChildItem C:\srcAllowed
  • PowerShellFormat-Volume -DriveLetter DBlockedcore.filesystem:format-volume
  • PowerShellvssadmin delete shadows /all /quietBlockedcore.filesystem:vssadmin-delete-shadows
  • cmd.exerd /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.

Interactive

Claude 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"
    }
  }
}
Requests follow each agent’s documented hook format, as dcg’s own end-to-end suite sends them. Answers are what release 0.17.2 printed for the blocked command 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. 1

    Install

    The installer downloads the binary for your platform and verifies its signature.

    dcg_install --easy-mode
  2. 2

    Detect

    It looks for each supported agent’s config directory or binary on the machine.

    ~/.claude ~/.codex ~/.gemini ~/.cursor …
  3. 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. 4

    Check

    Doctor verifies every registration. dcg setup can 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.

Interactive

104 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-databasecritical

    DROP DATABASE permanently deletes the entire database (even with IF EXISTS). Verify and back up first.

  • drop-schemacritical

    DROP SCHEMA permanently deletes the schema and all its objects (even with IF EXISTS).

  • dropdb-clicritical

    dropdb permanently deletes the entire database. Verify the database name carefully.

  • delete-without-wherehigh

    DELETE without WHERE clause deletes ALL rows. Add a WHERE clause or use TRUNCATE intentionally.

All rules in database.postgresql
config.toml
# ~/.config/dcg/config.toml
[packs]
enabled = []  # core.git, core.filesystem and system.disk are on already
A category name enables every pack in it: enabled = ["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
CommandPackVerdict
psql -c "DROP TABLE users"database.postgresqlBlockeddrop-table
dropdb productiondatabase.postgresqlBlockeddropdb-cli
psql -c "SELECT count(*) FROM users"database.postgresqlAllowed
kubectl delete namespace productionkubernetes.kubectlBlockeddelete-namespace
kubectl get pods -n productionkubernetes.kubectlAllowed
terraform destroy -auto-approveinfrastructure.terraformBlockeddestroy
terraform planinfrastructure.terraformAllowed
docker system prune -af --volumescontainers.dockerBlockedsystem-prune
docker ps -acontainers.dockerAllowed
docker compose down -vcontainers.composeBlockeddown-volumes
aws s3 rb s3://prod-backups --forcecloud.awsBlockeds3-rb
aws ec2 terminate-instances --instance-ids i-0abc123cloud.awsBlockedec2-terminate
redis-cli FLUSHALLdatabase.redisBlockedflushall
mongosh --eval "db.dropDatabase()"database.mongodbBlockeddrop-database
sqlite3 app.db "DELETE FROM orders"database.sqliteBlockeddelete-without-where
gh repo delete acme/api --yesplatform.githubBlockedgh-repo-delete
wrangler d1 delete prod-dbcdn.cloudflare_workersBlockedwrangler-d1-delete
git rebase -i HEAD~5strict_gitBlockedrebase

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 output
~/.config/dcg/packs/acme-deploy.yaml
schema_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.
config.toml
[packs]
custom_paths = ["~/.config/dcg/packs/*.yaml"]
dcg pack validate acme-deploy.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-shared
  • deployctl 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                                                   |
|  ^^^^^^^^^^^^^^^^                                                          |
|                                                                            |
|                                                                            |
|  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                                                  |
|                                                                            |
|  Pattern: reset-hard                                                       |
|  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:
  $ dcg explain -- "git reset --hard HEAD~3"
  $ dcg allow-once 803080
  $ 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
  1. The part of the command that matched
  2. What the command destroys, in plain words
  3. Commands that reach the same goal without the loss
  4. The pack, the rule and its severity
  5. A full trace of how dcg decided
  6. A code that lets this exact command run once
  7. Make 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?)?)?\b
Recorded from release 0.17.2 for git 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 803080

    The denial tells the agent to ask you. The opt-in careful_company_running_windows.guardrails pack also stops agents from running dcg allow-once or dcg allowlist add themselves.

  • 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:00Z

    Lists, 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-merge exists, it allows the four discard rules. Afterwards, one command issues a single-use, two-minute permit.

    dcg rebase-recover

    git reset --hard, git clean -f and 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.

SeverityDefault modeWhat happensExample rule
CriticaldenyBlockedcore.git:reset-hard
HighdenyBlockedcore.git:checkout-discard
MediumwarnRuns, with a warning on recordcore.git:stash-drop
LowlogRuns, recorded silentlycicd.github_actions:gh-actions-run-cancel
~/.config/dcg/config.toml
[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 record

A 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 deny entries 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
To give a project file full authority after reviewing it, select it explicitly for that run: 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.

Recorded output
1FROM node:22-slim2WORKDIR /app3COPY . .4RUN npm ci && npm run build5RUN rm -rf /app/srccore.filesystem:rm-rf-general
1name: 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-long
1build:2	cargo build --release3 4reset:5	git reset --hard origin/maincore.git:reset-hard6	git clean -fdxcore.git:clean-force
1{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-build

No 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=0
Findings recorded from release 0.17.2 running dcg 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-commit
  • In 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 sarif
  • As an MCP server

    Agents that speak MCP can ask before they act, with the tools check_command, scan_file and explain_pattern.

    dcg mcp-server
  • Before 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.log
  • After 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.

WhenWhat dcg doesPosture
Evaluation runs past the 1,000 ms deadlineThe result is indeterminate. Agents that support review ask you; the rest block.Fails closed
The command is too large to analyze in fullTreated the same way: review where possible, otherwise blocked.Fails closed
A rule’s regular expression fails partwayAny block it already proved stands. Otherwise review or block, never a silent allow.Fails closed
Embedded code can’t be parsed in timeA bounded fallback scan still checks for the dangerous calls. Strict mode blocks instead.Falls back
A plugin bridge starts dcg but gets no answerBlocked, with the reason shown, for OpenCode, Oh My Pi and Amp.Fails closed
The session runs without anyone watchingWhen the agent reports a bypass-permissions mode, unverifiable commands are denied instead of asked about.Fails closed
The hook input itself is malformed JSONdcg 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
From the bounded failure policy in the README. A slow evaluation never counts as proof that a command is safe.

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.

Budgets read from 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
  1. SHA-256Every archive has a checksum file next to it.
  2. 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.
  3. ProvenanceEach binary records the exact tag and commit it was built from. dcg --version prints them, and dcg update refuses 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.

  1. 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, Ubuntu
  2. Define 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.

    bash
    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
    )
    
  3. Run it

    Easy mode also adds dcg to your PATH. Use --system to install to /usr/local/bin with sudo, after verification.

    dcg_install --easy-mode
  1. Install the binary

    The tap covers Apple Silicon and Intel Macs and ARM64 and x86_64 Linux.

    brew install dicklesworthstone/tap/dcg
  2. Register the hooks

    Homebrew installs only the binary. This finds your agents and adds dcg to each one.

    dcg install
  1. 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.exe too. It adds dcg to your user PATH, runs a self-test, and configures the agents it finds.

    Open the Windows instructions

  2. What you get

    On Windows the windows.filesystem and windows.system packs are on by default, so del /s, rd /s, Remove-Item -Recurse, format and vssadmin delete shadows are blocked from the start.

  1. Build from crates.io

    Needs Rust 1.95 or newer. The crates.io build can trail the newest GitHub release; dcg --version tells you which you have.

    cargo install --locked destructive_command_guard
  2. Register the hooks

    dcg install

Then check it

  • Confirm every agent hook is registered and the config parses.

    dcg doctor
  • See a block without risking anything. dcg test evaluates 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.