destructive_command_guard README

The project's README from github.com/Dicklesworthstone/destructive_command_guard. As one markdown file: README.md.

dcg (Destructive Command Guard)

Destructive Command Guard - Protecting your code from accidental destruction

Coverage License: custom

A high-performance hook for AI coding agents that blocks destructive commands before they execute, protecting your work from accidental deletion across Claude Code, Codex CLI, Gemini CLI, Copilot CLI, VS Code Copilot Chat, Cursor, Hermes Agent, Grok (xAI), Posit Assistant, Oh My Pi, and related tools.

Supported: Claude Code, Codex CLI 0.125.0+, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Cursor IDE, Hermes Agent, Posit Assistant (Positron/RStudio extension, standalone server, and pa terminal client), Grok (xAI) (native ~/.grok/hooks/ plus Claude compatibility layer), Antigravity CLI (agy) (native ~/.gemini/config/hooks.json via dcg install --agy), OpenCode (native tool.execute.before plugin via dcg install --opencode — see docs/opencode-integration.md), Oh My Pi (omp) (native tool_call extension via dcg install --omp), Crush (native hooks.PreToolUse entry in crush.json via dcg install --crush — see docs/crush-integration.md), Pi (via extension recipe), Aider (limited—git hooks only), Continue (detection only)

Quick Install

curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)" | bash -s -- --easy-mode

Works on Linux, macOS, and Windows via WSL. Auto-detects your platform, downloads the right binary, and configures supported agent hooks including Claude Code, Codex CLI, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat (through VS Code's Claude-hook compatibility), Cursor IDE, Hermes Agent, Posit Assistant, Oh My Pi, and Grok (xAI) (via dcg install --grok for a native ~/.grok/hooks/dcg.json, or via the Claude compatibility layer automatically picked up by Grok). For native Windows, use the PowerShell installer below.

Windows (native, PowerShell)

& ([scriptblock]::Create((irm "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.ps1"))) -EasyMode -Verify

Installs native dcg.exe, verifies the mandatory SHA256 checksum, verifies the release's long-lived minisign signature when minisign is available, and verifies Sigstore/cosign provenance when both cosign and a trusted bundle are available. It adds dcg to your User PATH (-EasyMode), runs a self-test (-Verify), and configures detected agent hooks for Claude Code, Codex CLI, Gemini CLI, GitHub Copilot CLI, Cursor IDE, Hermes Agent, Posit Assistant, and Oh My Pi. Copilot is configured at the user level under %COPILOT_HOME%\hooks (or %USERPROFILE%\.copilot\hooks) so every workspace is protected. On Windows the windows.filesystem and windows.system packs are on by default, so del /s, rd /s, Remove-Item -Recurse (with or without -Force), format, and vssadmin delete shadows are blocked out of the box. Pin a version with -Version vX.Y.Z; use -RequireMinisign to fail closed if the sidecar or verifier is unavailable.


TL;DR

The Problem: AI coding agents (Claude, Codex, Gemini, Copilot, etc.) occasionally run catastrophic commands like git reset --hard, rm -rf ./src, or DROP TABLE users—destroying hours of uncommitted work in seconds.

The Solution: dcg is a high-performance hook that intercepts destructive commands before they execute, blocking them with clear explanations and safer alternatives.

Why Use dcg?

Feature What It Does
Zero-Config Protection Blocks dangerous git/filesystem commands out of the box
50+ Security Packs Databases, Kubernetes, Docker, AWS/GCP/Azure, Terraform, and more
Sub-Millisecond Latency SIMD-accelerated filtering—you won't notice it's there
Heredoc/Inline Script Scanning Catches python -c "os.remove(...)" and embedded shell scripts
Smart Context Detection Won't block grep "rm -rf" (data) but will block rm -rf / (execution)
Rich Terminal Output Human-readable denial panels, rule context, and suggestions on stderr
Agent-Safe Streams Machine-readable hook output stays on stdout while rich UI stays on stderr
Native Codex Support Codex CLI 0.125.0+ receives a minimal stdout JSON denial that current clients enforce reliably
Graceful Degradation Plain output for CI, pipes, dumb terminals, and no-color environments
Scan Mode for CI Pre-commit hooks and CI integration to catch dangerous commands in code review
Bounded Failure Policy Analysis timeouts become explicit review/block outcomes; malformed raw hook envelopes remain auditable and configurable
Explain Mode dcg explain "command" shows exactly why something is blocked

Quick Example

# AI agent tries to run:
$ git reset --hard HEAD~5

# dcg intercepts and blocks:
════════════════════════════════════════════════════════════════
BLOCKED  dcg
────────────────────────────────────────────────────────────────
Reason:  git reset --hard destroys uncommitted changes

Command: git reset --hard HEAD~5

Tip: Consider using 'git stash' first to save your changes.
════════════════════════════════════════════════════════════════

Enable More Protection

# ~/.config/dcg/config.toml
[packs]
enabled = [
    "database.postgresql",    # Blocks DROP TABLE, TRUNCATE
    "kubernetes.kubectl",     # Blocks kubectl delete namespace
    "cloud.aws",              # Blocks aws ec2 terminate-instances
    "containers.docker",      # Blocks docker system prune
]

Agent-Specific Profiles

dcg automatically detects which AI coding agent is invoking it and can apply agent-specific configuration. The trust_level field is an advisory label recorded in JSON output and logs — it does not directly change rule evaluation. Behavioral differences come from the other profile fields:

Option Effect
disabled_packs Removes rule packs from evaluation
extra_packs Adds rule packs to evaluation
additional_allowlist Adds command patterns that bypass deny rules
disabled_allowlist When true, ignores all allowlist entries
# Trust Claude Code more — wider allowlist, fewer packs
[agents.claude-code]
trust_level = "high"
additional_allowlist = ["npm run build", "cargo test"]
disabled_packs = ["kubernetes"]

# Oh My Pi has its own canonical profile (distinct from legacy Pi)
[agents.omp]
trust_level = "medium"
extra_packs = ["strict_git"]

# Restrict unknown agents — extra rules, no allowlist bypass
[agents.unknown]
trust_level = "low"
extra_packs = ["strict_git", "database"]  # real pack / category IDs (see `dcg packs`)
disabled_allowlist = true

extra_packs/disabled_packs take the same pack and category IDs as [packs] enabled/disabled — a category ID like "database" expands to every database.* sub-pack. Use IDs listed by dcg packs or in docs/packs/README.md; "paranoid" is a graduation mode, not a pack, so enable the real strict_git pack for stricter git rules.

See docs/agents.md for full documentation on supported agents, trust levels, and configuration options.

Codex Support

dcg now treats Codex CLI as a first-class hook target, not just a Claude-shaped compatibility path. The installer configures Codex CLI 0.125.0+ automatically when it detects codex on PATH or an existing ~/.codex/ directory.

Codex behavior dcg handling
Hook config Merges a PreToolUse Bash hook into ~/.codex/hooks.json
Denied command Exits 0 with a minimal hookSpecificOutput denial on stdout; human warning stays on stderr
Allowed command Exits 0 with empty stdout and stderr
Existing hooks Preserves coexisting hooks, keeps dcg first for Bash, and refuses to overwrite malformed JSON
Validation Covered by subprocess protocol tests plus an opt-in real Codex E2E harness

Codex's hook input is intentionally close to Claude Code's, but Codex rejects unknown fields in hook output. dcg detects Codex payloads from the non-empty turn_id field and emits only Codex's documented denial fields so a blocked command is reported as blocked rather than as a failed hook. See docs/codex-integration.md for protocol details, manual probes, and troubleshooting.


Origins & Authors

This project began as a Python script by Jeffrey Emanuel, who recognized that AI coding agents, while incredibly useful, occasionally run catastrophic commands that destroy hours of uncommitted work. The original implementation was a simple but effective hook that intercepted dangerous git and filesystem commands before execution.

The initial Rust port by Darin maintained pattern compatibility with the original Python implementation while adding sub-millisecond execution through SIMD-accelerated filtering and lazy-compiled regex patterns. Jeffrey subsequently expanded the Rust codebase dramatically to add the features described above.

Escape Hatch / Bypass

If dcg is blocking something you genuinely need to run:

Method Scope How
Env var bypass Single command DCG_BYPASS=1 <command>
Allow-once code Single command Copy the short code from the block message, run dcg allow-once <code>
Permanent allowlist Rule or command dcg allowlist add core.git:reset-hard -r "reason"
Remove the hook All commands Delete or comment out the dcg entry in ~/.claude/settings.json (or equivalent for your agent)

DCG_BYPASS=1 disables all protection for that invocation. Use it sparingly and prefer allowlists for recurring needs.

Modular Pack System

dcg uses a modular "pack" system to organize destructive command patterns by category. Packs can be enabled or disabled in the configuration file.

Category IDs expand to their sub-packs. Listing a bare category in enabled turns on every pack under it: enabled = ["database"] activates database.postgresql, database.mysql, and the rest of that category. You can still drop a single sub-pack with disabled = ["database.redis"]. The same expansion applies to agent-profile extra_packs / disabled_packs. Always use real pack or category IDs from dcg packs / docs/packs/README.md — a name like "paranoid" is a graduation mode, not a pack.

Enabled by default (no config file)

With no config file present, dcg enables only the packs that guard against the most catastrophic, unrecoverable mistakes:

On Windows, two additional packs are on by default so a fresh install blocks the catastrophic native-Windows operations with no config:

The broader windows.misc (reg delete, net user /delete, wsl --unregister, robocopy /MIR) and windows.powershell (registry/provider deletes, Remove-LocalUser, Disable-ComputerRestore, Remove-VM) packs are opt-in on every platform. On Unix the windows.* packs are registered but off by default; enable them (e.g. to scan committed .ps1/.cmd scripts in CI) via [packs] enabled = ["windows"].

Every other pack — including database.postgresql and containers.docker — is opt-in and is not active until a config file enables it. Running dcg init writes a starter ~/.config/dcg/config.toml whose [packs] enabled list turns on database.postgresql and containers.docker as common examples, but that is a generated starter config, not the no-config default. Enable any pack below by adding it to [packs] enabled — see Enable More Protection.

Storage Packs

Remote Packs

Database Packs

Container Packs

Kubernetes Packs

Cloud Provider Packs

CDN Packs

API Gateway Packs

Infrastructure Packs

destructive_command_guard (Dicklesworthstone/destructive_command_guard)

Searching Database…

Что это такое?dcg (Destructive Command Guard) — это высокопроизводительный хук на Rust, который перехватывает и блокирует катастрофические shell- и git-команды (например, 'git reset --hard' или 'rm -rf') до того, как ИИ-агенты для программирования смогут их выполнить, защищая незакоммиченную работу.
dcg — это хук, который я подключаю к агенту, или отдельное приложение, которое нужно запускать вручную?Это бинарный файл-хук, который ваш агент для программирования вызывает автоматически перед выполнением команды (по схеме PreToolUse), а не то, что вы запускаете сами; он встраивается в такие агенты, как Claude Code, Codex CLI, Gemini CLI, Cursor и Copilot.
Какие агенты для программирования он действительно поддерживает?Claude Code, Codex CLI 0.125.0+, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Cursor IDE, Hermes Agent, Grok (xAI), Posit Assistant, Antigravity CLI, OpenCode, Oh My Pi и Crush, с ограниченной поддержкой Aider и только обнаружением для Continue.
Что делать, если dcg блокирует команду, которую мне действительно нужно выполнить?Можно обойти блокировку для отдельной команды с помощью переменной окружения DCGBYPASS=1 или одноразового кода разрешения из сообщения о блокировке либо навсегда добавить правило в белый список командой 'dcg allowlist add'; полное удаление хука отключает всю защиту.
Работает ли он нативно на Windows или только через WSL?И так, и так: кроссплатформенный скрипт быстрой установки работает на Linux, macOS и Windows через WSL, а также есть отдельный нативный установщик PowerShell для Windows, который по умолчанию включает наборы правил, специфичные для файловой системы и системы Windows.
Как устроена система паков?Шаблоны опасных команд организованы в более чем 50 переключаемых 'паков' по категориям (git, файловая система, базы данных, Kubernetes, Docker, облачное хранилище, Terraform и т. д.); по умолчанию включены только core.filesystem, core.git и system.disk, а остальные подключаются вручную через config.toml.
Сколько задержки проверка добавляет к каждой команде?dcg использует фильтрацию с ускорением SIMD и регулярные выражения, которые компилируются по мере необходимости, поэтому задержка составляет доли миллисекунды и не заметна при обычной работе агента.
Size
47 MB
Stars
6.2K
Age
9mo
Commits · 90 Days