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), and related tools.
Supported: Claude Code, Codex CLI 0.125.0+, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Cursor IDE, Hermes Agent, Grok (xAI) (native ~/.grok/hooks/
plus Claude compatibility layer), Antigravity CLI ( agy) (native
~/.gemini/config/hooks.json
via dcg install --agy
), OpenCode(via
Pi(via
Aider(limitedβgit hooks only),
Continue(detection only)
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, 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.
& ([scriptblock]::Create((irm "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.ps1"))) -EasyMode -Verify
Installs native dcg.exe, verifies the SHA256 checksum (and the Sigstore/cosign signature when cosign is present), adds it 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, and Hermes Agent. 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 -Force, format, and vssadmin delete shadows are blocked out of the box. Pin a version with -Version vX.Y.Z.
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.
| 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 | |
| Fail-Open Design | |
| Never blocks your workflow due to timeouts or parse errors | |
| Explain Mode | |
dcg explain "command" shows exactly why something is blocked |
$ git reset --hard HEAD~5
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
[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
]
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 |
[agents.claude-code]
trust_level = "high"
additional_allowlist = ["npm run build", "cargo test"]
disabled_packs = ["kubernetes"]
[agents.unknown]
trust_level = "low"
extra_packs = ["paranoid"]
disabled_allowlist = true
See docs/agents.md for full documentation on supported agents, trust levels, and configuration options.
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.
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.
- Original concept and Python implementation (Jeffrey Emanuelsource); substantially expanded the Rust version with the modular pack system (50+ security packs), heredoc/inline-script scanning, the three-tier architecture, context classification, allowlists, scan mode, and the dual regex engine- Initial Rust port with performance optimizationsDarin Gordon
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.
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.
dcg uses a modular "pack" system to organize destructive command patterns by category. Packs can be enabled or disabled in the configuration file.
-
Full pack ID index:
docs/packs/README.md -
Canonical descriptions + pattern counts:
dcg packs --verbose
With no config file present, dcg enables only the packs that guard against the most catastrophic, unrecoverable mistakes:
core.filesystem
- Dangerous
rm -rf
outside temp directories*(always on; cannot be disabled)*core.git
- Destructive git commands that lose uncommitted work, rewrite history, or destroy stashes*(always on; cannot be disabled)*
system.disk
-mkfs
,dd
-to-device,fdisk
,parted
,mdadm
,lvm
removal,wipefs
(on by default; opt out withdisabled = ["system.disk"]
)
On Windows, two additional packs are on by default so a fresh install blocks the catastrophic native-Windows operations with no config:
windows.filesystem
- cmd
del /s
,rd /s
,format <drive>:
and PowerShellRemove-Item -Recurse -Force
(and aliases),Clear-Content
,Clear-RecycleBin
(default-onon Windows only; opt out withdisabled = ["windows.filesystem"]
or["windows"]
)windows.system
-vssadmin delete shadows
/wmic shadowcopy delete
(Volume Shadow Copy destruction),diskpart
,Format-Volume
,Clear-Disk
,Remove-Partition
,cipher /w
,bcdedit /delete
(default-onon Windows only; opt out withdisabled = ["windows.system"]
or["windows"]
)
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.s3
-
Protects against destructive S3 operations like bucket removal, recursive deletes, and sync --delete.
storage.gcs -
Protects against destructive GCS operations like bucket removal, object deletion, and recursive deletes.
storage.minio -
Protects against destructive MinIO Client (mc) operations like bucket removal, object deletion, and admin operations.
storage.azure_blob -
Protects against destructive Azure Blob Storage operations like container deletion, blob deletion, and azcopy remove.
remote.rsync
-
Protects against destructive rsync operations like --delete and its variants.
remote.scp -
Protects against destructive SCP operations like overwrites to system paths.
remote.ssh -
Protects against destructive SSH operations like remote command execution and key management.
database.postgresql
-
Protects against destructive PostgreSQL operations like DROP DATABASE, TRUNCATE, and dropdb.
database.mysql -
MySQL/MariaDB guard.
database.mongodb -
Protects against destructive MongoDB operations like dropDatabase, dropCollection, and remove without criteria.
database.redis -
Protects against destructive Redis operations like FLUSHALL, FLUSHDB, and mass key deletion.
database.sqlite -
Protects against destructive SQLite operations like DROP TABLE, DELETE without WHERE, and accidental data loss.
database.supabase -
Protects against destructive Supabase CLI operations including database resets, migration rollbacks, function/secret/storage deletion, project removal, and infrastructure changes.
containers.docker
-
Protects against destructive Docker operations like system prune, volume prune, and force removal.
containers.compose -
Protects against destructive Docker Compose operations like down -v which removes volumes.
containers.podman -
Protects against destructive Podman operations like system prune, volume prune, and force removal.
kubernetes.kubectl
-
Protects against destructive kubectl operations like delete namespace, drain, and mass deletion.
kubernetes.helm -
Protects against destructive Helm operations like uninstall and rollback without dry-run.
kubernetes.kustomize -
Protects against destructive Kustomize operations when combined with kubectl delete or applied without review.
cloud.aws
-
Protects against destructive AWS CLI operations like terminate-instances, delete-db-instance, and s3 rm --recursive.
cloud.azure -
Protects against destructive Azure CLI operations like vm delete, storage account delete, and resource group delete.
cloud.gcp -
Protects against destructive gcloud operations like instances delete, sql instances delete, and gsutil rm -r.
cdn.cloudflare_workers
-
Protects against destructive Cloudflare Workers, KV, R2, and D1 operations via the Wrangler CLI.
cdn.cloudfront -
Protects against destructive AWS CloudFront operations like deleting distributions, cache policies, and functions.
cdn.fastly -
Protects against destructive Fastly CLI operations like service, domain, backend, and VCL deletion.
apigateway.apigee
-
Protects against destructive Google Apigee CLI and apigeecli operations.
apigateway.aws -
Protects against destructive AWS API Gateway CLI operations for both REST APIs and HTTP APIs.
apigateway.kong -
Protects against destructive Kong Gateway CLI, deck CLI, and Admin API operations.
infrastructure.ansible
-
Protects against destructive Ansible operations like dangerous shell commands and unchecked playbook runs.
infrastructure.atmos -
Protects against destructive Atmos operations like terraform deploy (auto-approve), clean, destroy, state rm/taint, and helmfile destroy.
infrastructure.pulumi -
Protects against destructive Pulumi operations like destroy and up with -y (auto-approve).
infrastructure.terraform -
Protects against destructive Terraform operations like destroy, taint, and apply with -auto-approve.
system.disk
-
Protects against destructive disk operations including dd to devices, mkfs, partition table modifications (fdisk/parted), RAID management (mdadm), btrfs filesystem operations, device-mapper (dmsetup), network block devices (nbd-client), and LVM commands (pvremove, vgremove, lvremove, lvreduce, pvmove).
system.permissions -
Protects against dangerous permission changes like chmod 777, recursive chmod/chown on system directories.
system.services -
Protects against dangerous service operations like stopping critical services and modifying init configuration.
cicd.circleci
-
Protects against destructive CircleCI operations like deleting contexts, removing secrets, deleting orbs/namespaces, or removing pipelines.
cicd.github_actions -
Protects against destructive GitHub Actions operations like deleting secrets/variables or using gh api DELETE against /actions endpoints.
cicd.gitlab_ci -
Protects against destructive GitLab CI/CD operations like deleting variables, removing artifacts, and unregistering runners.
cicd.jenkins -
Protects against destructive Jenkins CLI/API operations like deleting jobs, nodes, credentials, or build history.
secrets.aws_secrets
-
Protects against destructive AWS Secrets Manager and SSM Parameter Store operations like delete-secret and delete-parameter.
secrets.doppler -
Protects against destructive Doppler CLI operations like deleting secrets, configs, environments, or projects.
secrets.onepassword -
Protects against destructive 1Password CLI operations like deleting items, documents, users, groups, and vaults.
secrets.vault -
Protects against destructive Vault CLI operations like deleting secrets, disabling auth/secret engines, revoking leases/tokens, and deleting policies.
platform.github
-
Protects against destructive GitHub CLI operations like deleting repositories, gists, releases, or SSH keys.
platform.gitlab -
Protects against destructive GitLab platform operations like deleting projects, releases, protected branches, and webhooks.
platform.kamal -
Protects against destructive Kamal 2.x operations that tear down the stack (
kamal remove
), delete accessory data directories (kamal accessory remove
), drop proxy routing, take the app offline, or prune the images thatkamal rollback
relies on.platform.modal
- Protects against destructive Modal serverless platform operations like recursive volume removal, app stops with
--force
, and secret deletion.platform.railway
- Protects against destructive Railway CLI and Public API operations that can delete projects, environments, services, functions, volumes, variables, or deployments.
dns.cloudflare
-
Protects against destructive Cloudflare DNS operations like record deletion, zone deletion, and targeted Terraform destroy.
dns.generic -
Protects against destructive or risky DNS tooling usage (nsupdate deletes, zone transfers).
dns.route53 -
Protects against destructive AWS Route53 DNS operations like hosted zone deletion and record set DELETE changes.
email.mailgun
-
Protects against destructive Mailgun API operations like domain deletion, route deletion, and mailing list removal.
email.postmark -
Protects against destructive Postmark API operations like server deletion, template deletion, and sender signature removal.
email.sendgrid -
Protects against destructive SendGrid API operations like template deletion, API key deletion, and domain authentication removal.
email.ses -
Protects against destructive AWS Simple Email Service operations like identity deletion, template deletion, and configuration set removal.
featureflags.flipt
-
Protects against destructive Flipt CLI and API operations.
featureflags.launchdarkly -
Protects against destructive LaunchDarkly CLI and API operations.
featureflags.split -
Protects against destructive Split.io CLI and API operations.
featureflags.unleash -
Protects against destructive Unleash CLI and API operations.
loadbalancer.elb
-
Protects against destructive AWS Elastic Load Balancing (ELB/ALB/NLB) operations like deleting load balancers, target groups, or deregistering targets from live traffic.
loadbalancer.haproxy -
Protects against destructive HAProxy load balancer operations like stopping the service or disabling backends via runtime API.
loadbalancer.nginx -
Protects against destructive nginx load balancer operations like stopping the service or deleting config files.
loadbalancer.traefik -
Protects against destructive Traefik load balancer operations like stopping containers, deleting config, or API deletions.
messaging.kafka
-
Protects against destructive Kafka CLI operations like deleting topics, removing consumer groups, resetting offsets, and deleting records.
messaging.nats -
Protects against destructive NATS/JetStream operations like deleting streams, consumers, key-value entries, objects, and accounts.
messaging.rabbitmq -
Protects against destructive RabbitMQ operations like deleting queues/exchanges, purging queues, deleting vhosts, and resetting cluster state.
messaging.sqs_sns -
Protects against destructive AWS SQS and SNS operations like deleting queues, purging messages, deleting topics, and removing subscriptions.
monitoring.datadog
-
Protects against destructive Datadog CLI/API operations like deleting monitors and dashboards.
monitoring.newrelic -
Protects against destructive New Relic CLI/API operations like deleting entities or alerting resources.
monitoring.pagerduty -
Protects against destructive PagerDuty CLI/API operations like deleting services and schedules (which can break incident routing).
monitoring.prometheus -
Protects against destructive Prometheus/Grafana operations like deleting time series data or dashboards/datasources.
monitoring.splunk -
Protects against destructive Splunk CLI/API operations like index removal and REST API DELETE calls.
payment.braintree
-
Protects against destructive Braintree/PayPal payment operations like deleting customers or cancelling subscriptions via API/SDK calls.
payment.square -
Protects against destructive Square CLI/API operations like deleting catalog objects or customers (which can break payment flows).
payment.stripe -
Protects against destructive Stripe CLI/API operations like deleting webhook endpoints and customers, or rotating API keys without coordination.
search.algolia
-
Protects against destructive Algolia operations like deleting indices, clearing objects, removing rules/synonyms, and deleting API keys.
search.elasticsearch -
Protects against destructive Elasticsearch REST API operations like index deletion, delete-by-query, index close, and cluster setting changes.
search.meilisearch -
Protects against destructive Meilisearch REST API operations like index deletion, document deletion, delete-batch, and API key removal.
search.opensearch -
Protects against destructive OpenSearch REST API operations and AWS CLI domain deletions.
backup.borg
-
Protects against destructive borg operations like delete, prune, compact, and recreate.
backup.rclone -
Protects against destructive rclone operations like sync, delete, purge, dedupe, and move.
backup.restic -
Protects against destructive restic operations like forgetting snapshots, pruning data, removing keys, and cache cleanup.
backup.velero -
Protects against destructive velero operations like deleting backups, schedules, and locations.
Native-Windows (cmd.exe + PowerShell) destructive-command protection. windows.filesystem
and
windows.system
are default-on on Windows (off/opt-in on Unix); windows.misc
and
windows.powershell
are opt-in everywhere. All patterns are case-insensitive.
windows.filesystem
- Recursive/forced filesystem destruction: cmd
del /s
,rd /s
/rmdir /s
,format <drive>:
; PowerShellRemove-Item -Recurse -Force
(and aliasesrm
/del
/rd
/ri
),Clear-Content
,Clear-RecycleBin
. Whitelists PowerShell-WhatIf
previews only on cmdlets/aliases that honor it, plus temp-dir deletes.windows.system
- Catastrophic disk/system operations:
vssadmin delete shadows
andwmic shadowcopy delete
(Volume Shadow Copy destruction β a ransomware hallmark),diskpart
,Format-Volume
,Clear-Disk
,Remove-Partition
,Initialize-Disk
/Reset-PhysicalDisk
,cipher /w
,bcdedit /delete
.windows.misc
- Registry/account/service/WSL/copy destruction:
reg delete
,net user|localgroup /delete
,sc delete
,schtasks /delete
,wsl --unregister
(destroys a WSL distro),robocopy /MIR
(mirror-delete).windows.powershell
- Destructive PowerShell cmdlets: registry/provider deletes (
Remove-Item HKLM:\
,Remove-ItemProperty
,Remove-PSDrive
),Remove-LocalUser
/Remove-LocalGroup
,Unregister-ScheduledTask
,Disable-ComputerRestore
, forcedStop-Computer
/Restart-Computer
,Remove-VM
/Remove-AppxPackage
.
package_managers
-
Protects against dangerous package manager operations like publishing packages and removing critical system packages.
strict_git -
Stricter git protections: blocks all force pushes, rebases, and history rewriting operations.
Enable packs in ~/.config/dcg/config.toml
:
[packs]
enabled = [
"database.postgresql",
"database.redis",
"database.supabase",
"containers.docker",
"kubernetes", # Enables all kubernetes sub-packs
"cloud.aws",
"cloud.gcp",
"secrets.aws_secrets",
"secrets.vault",
"cicd.jenkins",
"cicd.gitlab_ci",
"messaging.kafka",
"messaging.sqs_sns",
"search.elasticsearch",
"backup.restic",
"platform.github",
"platform.railway",
"monitoring.splunk",
]
Create your own organization-specific security packs using YAML files. Custom packs let you define patterns for internal tools, deployment scripts, and proprietary systems without modifying dcg.
[packs]
custom_paths = [
"~/.config/dcg/packs/*.yaml", # User packs
".dcg/packs/*.yaml", # Project-local packs
]
For detailed pack authoring guide, schema reference, and examples, see docs/custom-packs.md.
Validate your pack before deployment:
dcg pack validate mypack.yaml
Heredoc scanning configuration:
[heredoc]
enabled = true
timeout_ms = 50
max_body_bytes = 1048576
max_body_lines = 10000
max_heredocs = 10
fallback_on_parse_error = true
fallback_on_timeout = true
CLI overrides for heredoc scanning:
--heredoc-scan
/--no-heredoc-scan
--heredoc-timeout <ms>
--heredoc-languages <lang1,lang2,...>
Heredoc documentation:
docs/adr-001-heredoc-scanning.md
(architecture and rationale)docs/patterns.md
(pattern authoring + inventory)docs/security.md
(threat model and incident response)
Heredoc and inline script scanning uses a three-tier pipeline designed for performance and accuracy:
Command Input
β
βΌ
βββββββββββββββββββ
β Tier 1: Trigger β βββ No match βββΊ ALLOW (fast path, <100ΞΌs)
β (RegexSet) β
ββββββββββ¬βββββββββ
β Match
βΌ
βββββββββββββββββββ
β Tier 2: Extract β βββ Error/Timeout βββΊ ALLOW + fallback check
β (<1ms) β
ββββββββββ¬βββββββββ
β Success
βΌ
βββββββββββββββββββ
β Tier 3: AST β βββ No match βββΊ ALLOW
β (<5ms) β βββ Match βββΊ BLOCK
βββββββββββββββββββ
Tier 1: Trigger Detection (<100ΞΌs)
Ultra-fast regex screening to detect heredoc indicators. Uses a compiled RegexSet
for O(n) matching against all trigger patterns simultaneously:
static HEREDOC_TRIGGERS: LazyLock<RegexSet> = LazyLock::new(|| {
RegexSet::new([
r"<<-?\s*(?:['\x22][^'\x22]*['\x22]|[\w.-]+)", // Heredocs
r"<<<", // Here-strings
r"\bpython[0-9.]*\b.*\s+-[A-Za-z]*[ce]", // python -c/-e
r"\bruby[0-9.]*\b.*\s+-[A-Za-z]*e", // ruby -e
r"\bnode(js)?[0-9.]*\b.*\s+-[A-Za-z]*[ep]", // node -e/-p
r"\b(sh|bash|zsh)\b.*\s+-[A-Za-z]*c", // bash -c
// ... more patterns
])
});
Commands without any trigger patterns skip directly to ALLOWβno further processing needed.
Tier 2: Content Extraction (<1ms)
For commands that trigger, extract the actual content to be evaluated:
Heredocs:cat <<EOF ... EOF
β extracts body between delimitersHere-strings:cat <<< "content"
β extracts quoted contentInline scripts:python -c "code"
β extracts the code argument
Extraction is bounded by configurable limits:
- Maximum body size (default: 1MB)
- Maximum lines (default: 10,000)
- Maximum heredocs per command (default: 10)
- Timeout (default: 50ms)
pub struct ExtractionLimits {
pub max_body_bytes: usize,
pub max_body_lines: usize,
pub max_heredocs: usize,
pub timeout_ms: u64,
}
Tier 3: AST Pattern Matching (<5ms)
Extracted content is parsed using language-specific AST grammars (via tree-sitter/ast-grep) and matched against structural patterns:
// Example: detect subprocess.run with shell=True and rm -rf
let pattern = r#"
call_expression {
function: attribute { object: "subprocess" attr: "run" }
arguments: argument_list {
contains string { contains "rm -rf" }
contains keyword_argument { keyword: "shell" value: "True" }
}
}
"#;
Recursive Shell Analysis:
When extracted content is itself a shell script (e.g., bash -c "git reset --hard"
), Tier 3 recursively extracts inner commands and re-evaluates them through the full pipeline:
if content.language == ScriptLanguage::Bash {
let inner_commands = extract_shell_commands(&content.content);
for inner in inner_commands {
// Re-evaluate inner command against all packs
if let Some(result) = evaluate_command(&inner, ...) {
if result.decision == Deny {
return result; // Block the outer command
}
}
}
}
If you encounter commands that should be blocked, please file an issue.
Environment variables override config files (highest priority):
DCG_PACKS="containers.docker,kubernetes"
: enable packs (comma-separated)DCG_DISABLE="kubernetes.helm"
: disable packs/sub-packs (comma-separated)DCG_VERBOSE=0-3
: verbosity level (0 = quiet, 3 = trace)DCG_QUIET=1
: suppress non-error outputDCG_COLOR=auto|always|never
: color modeDCG_NO_RICH=1
: disable rich terminal formatting and use plain renderingDCG_NO_COLOR=1
: disable colored output (same as NO_COLOR)DCG_LEGACY_OUTPUT=1
: force plain output paths (same as--legacy-output
)DCG_ROBOT=1
: enable robot mode for JSON stdout and quiet stderrDCG_HIGH_CONTRAST=1
: enable high-contrast output (ASCII borders + monochrome palette)DCG_FORMAT=text|json|sarif
: default output format (command-specific β seeOutput Formatsfor which values each subcommand actually accepts; real SARIF isdcg scan
-only)DCG_FAIL_CLOSED=1
: block (deny) on hook input that cannot be parsed, instead of the default fail-open allow (opt-in; seeFail-Open Philosophy)DCG_BYPASS=1
: bypass dcg entirely (escape hatch; use sparingly)DCG_CONFIG=/path/to/config.toml
: use explicit config fileDCG_HEREDOC_ENABLED=true|false
: enable/disable heredoc scanningDCG_HEREDOC_TIMEOUT=50
: heredoc extraction timeout (milliseconds)DCG_HEREDOC_TIMEOUT_MS=50
: heredoc extraction timeout (milliseconds)DCG_HEREDOC_LANGUAGES=python,bash
: filter heredoc languagesDCG_POLICY_DEFAULT_MODE=deny|warn|log
: global default decision modeDCG_HOOK_TIMEOUT_MS=200
: hook evaluation timeout budget (milliseconds)
--format
(and the DCG_FORMAT
env var, which seeds the default) is
command-specific: each subcommand accepts only its own set of values, and an
unrecognized value is a usage error (exit 2). DCG_FORMAT
applies wherever a
command has a --format
flag and is silently ignored by commands that don't.
| Command | Accepted --format values |
Notes |
|---|---|---|
dcg scan |
pretty , json , markdown , sarif |
Only command that emits real SARIF 2.1.0 |
dcg test |
pretty (alias text ), json (aliases sarif , structured ), toon |
|
dcg config |
pretty (alias text ), json (alias sarif ) |
|
dcg packs |
pretty (alias text ), json (alias sarif ) |
|
dcg explain |
pretty , json (alias sarif ) |
|
dcg doctor |
pretty , json (alias sarif ) |
|
dcg simulate |
pretty , json (alias sarif ) |
|
dcg corpus |
json , pretty (alias sarif ) |
|
dcg suggest-allowlist |
text , json (alias sarif ) |
** sarif is a JSON alias on every command except dcg scan.** This is deliberate so that setting
DCG_FORMAT=sarif
globally degrades gracefully β
dcg scan
produces a real SARIF report while other commands fall back to their
structured JSON rather than erroring. If you need machine-readable output from a
non-scan command, prefer --format json
(which is unambiguous); use dcg scan --format sarif
for SARIF. --robot
forces JSON regardless of --format
.dcg supports layered configuration from multiple sources, with higher-priority sources overriding lower ones:
- Environment Variables (DCG_* prefix) [HIGHEST PRIORITY]
- Explicit Config File (DCG_CONFIG env var)
- Project Config (.dcg.toml in repo root)
- User Config (~/.config/dcg/config.toml)
- System Config (/etc/dcg/config.toml)
- Compiled Defaults [LOWEST PRIORITY]
dcg supports colorblind-safe palettes and high-contrast output. Colors are always paired with symbols/labels to avoid conveying meaning by color alone.
[output]
high_contrast = true # ASCII borders + black/white palette
[theme]
palette = "colorblind" # default | colorblind | high-contrast
use_unicode = true # false for ASCII-only
use_color = true # false for monochrome
Configuration File Locations:
| Level | Path | Use Case |
|---|---|---|
| System | /etc/dcg/config.toml |
|
| Organization-wide defaults | ||
| User | ~/.config/dcg/config.toml |
|
| Personal preferences | ||
| Project | .dcg.toml (repo root) |
|
| Project-specific settings | ||
| Explicit | DCG_CONFIG=/path/to/file |
|
| Testing or override |
Merging Behavior:
Configuration layers are merged additively, with higher-priority sources overriding specific fields:
// Only fields explicitly set in higher-priority configs override
// Missing fields retain values from lower-priority sources
fn merge_layer(&mut self, other: ConfigLayer) {
if let Some(verbose) = other.general.verbose {
self.general.verbose = verbose; // Override if present
}
// Unset fields retain previous values
}
This means you can set organization defaults in /etc/dcg/config.toml
, personal preferences in ~/.config/dcg/config.toml
, and project-specific overrides in .dcg.toml
βeach layer only needs to specify the settings that differ from defaults.
Project-Specific Pack Configuration:
The [projects]
section allows different pack configurations for different repositories:
[projects."/home/user/work/production-api"]
packs = { enabled = ["database.postgresql", "cloud.aws"], disabled = [] }
[projects."/home/user/personal/experiments"]
packs = { enabled = [], disabled = ["core.git"] } # More permissive for experiments
dcg is designed with a fail-open philosophy: when the tool cannot safely analyze a command (due to timeouts, parse errors, or resource limits), it allows the command to proceed rather than blocking it and breaking the user's workflow.
Why Fail-Open?
Workflow Continuity: A blocked legitimate command is more disruptive than a missed dangerous one** Performance Guarantees**: The hook must never become a bottleneck** Graceful Degradation**: Partial analysis is better than no analysis
Fail-Open Scenarios:
| Scenario | Behavior | Rationale |
|---|---|---|
| Parse error in heredoc | ALLOW + warn | Malformed input shouldn't block work |
| Extraction timeout | ALLOW + warn | Slow inputs shouldn't hang terminal |
| Size limit exceeded | ALLOW + fallback check | Large inputs get reduced analysis |
| Regex engine timeout | ALLOW + warn | Pathological patterns shouldn't block |
| AST matching error | Skip that heredoc | Continue evaluating other content |
| Deadline exceeded | ALLOW immediately | Hard cap prevents runaway processing |
Configurable Strictness:
For high-security environments, fail-open can be disabled.
For heredoc/inline-script analysis specifically:
[heredoc]
fallback_on_parse_error = false # Block on heredoc parse errors
fallback_on_timeout = false # Block on heredoc timeouts
For the top-level hook input (the JSON dcg reads from stdin), enable fail-closed mode so that input which cannot be parsed at all is blocked instead of allowed:
[general]
fail_closed = true # Deny when the hook input itself is unparseable
or at runtime:
DCG_FAIL_CLOSED=1 # env var overrides the config value
The default is fail-open (unparseable input is allowed) and is unchanged
unless you opt in. With fail-closed enabled, a genuinely unparseable hook
payload produces a deny (a permissionDecision: deny
for Claude-style hooks; a
"decision":"deny"
line plus a non-zero exit for dcg hook --batch
). Transient IO read errors still fail open even in this mode, since they are not attacker-controlled malformed payloads.
A leading UTF-8 BOM (
EF BB BF
) is stripped before parsing in all hook paths, so a BOM-prefixed but otherwise-valid command is correctly evaluated (and blocked if dangerous) rather than allowed through as "unparseable".
With strict mode enabled, dcg will block commands when analysis fails, providing detailed error messages explaining why.
Fallback Pattern Checking:
Even when full analysis is skipped, dcg performs a lightweight fallback check for critical destructive patterns:
static FALLBACK_PATTERNS: LazyLock<RegexSet> = LazyLock::new(|| {
RegexSet::new([
r"shutil\.rmtree",
r"os\.remove",
r"fs\.rmSync",
r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f",
r"\bgit\s+reset\s+--hard\b",
// ... other critical patterns
])
});
This ensures that even oversized or malformed inputs are checked for the most dangerous operations before being allowed.
Absolute Timeout:
To prevent any single command from blocking indefinitely, dcg enforces an absolute maximum processing time of 200ms. Any command exceeding this threshold is immediately allowed with a warning logged.
The easiest way to install is using the install script, which downloads a prebuilt binary for your platform:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)" | bash -s -- --easy-mode
Easy mode auto-detects your platform, downloads the right binary, verifies SHA256 checksums, configures all supported AI agent hooks (Claude Code, Codex CLI, Gemini CLI, GitHub Copilot CLI, Cursor IDE, Hermes Agent, Aider), and updates your PATH. For Codex CLI 0.125.0+, the installer merges a PreToolUse
Bash hook into ~/.codex/hooks.json
; invalid JSON or malformed existing Codex hook shapes are left unchanged and reported instead of being overwritten.
Other options:
Interactive mode (prompts for each step):
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)" | bash
Install specific version:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)" | bash -s -- --version v0.5.0
Install to /usr/local/bin (system-wide, requires sudo):
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)" | sudo bash -s -- --system
Build from source instead of down binary:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)" | bash -s -- --from-source
Download/install only (skip agent hook configuration):
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)" | bash -s -- --no-configure
Note:If you have[gum]installed, the installer will use it for fancy terminal formatting.
The installer also verifies Sigstore cosign bundles when available (falls back to checksum-only), falls back to building from source if no prebuilt is available, and removes the legacy Python predecessor (git_safety_guard.py
) if present.
Agent-specific notes #
Aider: No PreToolUse-style interception. The installer enablesgit-commit-verify: true
in~/.aider.conf.yml
so git hooks run. For full protection, install dcg as agit pre-commit hook.Continue: No shell command interception hooks. The installer detects Continue but cannot auto-configure protection. Use agit pre-commit hookinstead.Codex CLI: PreToolUse hooks via~/.codex/hooks.json
(stable in Codex 0.125.0+; thecodex_hooks
feature is on by default). dcg detects Codex from theturn_id
stdin field and emits the minimal documentedhookSpecificOutput
deny JSON with exit code 0; dcg-only metadata is omitted so Codex's strict parser accepts the decision. The Unix installer andinstall.ps1
both merge dcg's hook into the existing hooks object, detect an already-current dcg hook exactly, leave invalid JSON or malformed hook shapes untouched, and surface the failure reason in the install summary. After installation, open Codex's/hooks
UI once to trust the hook.uninstall.sh
anduninstall.ps1
remove only dcg-owned Codex hooks and preserve coexisting entries. See theCodex integration notes. Caveats: the model can still write scripts to disk to bypass hook-based blocking; and Codex'sPreToolUse
hooksdo not yet intercept every, so treat it as a guardrail rather than a complete enforcement boundary.unified_exec
shell pathGitHub Copilot CLI: The installer writes a user-level hook to${COPILOT_HOME:-~/.copilot}/hooks/dcg.json
, protecting every workspace. The generatedpreToolUse
hook covers both Unixbash
and Windowspowershell
payloads and emits Copilot's exact top-level permission-decision JSON.VS Code Copilot Chat: Current VS Code releases load~/.claude/settings.json
by default, so the Claude Code hook installed by dcg also protects Copilot Chat without a second bridge or duplicate hook. dcg recognizes VS Code's documentedrunTerminalCommand
shell tool plus the observed compatibility namesrun_in_terminal
andrunInTerminal
, readstool_input.command
, and returns VS Code's documentedhookSpecificOutput
deny. Agent hooks are still a VS Code preview feature and can be disabled by organization policy; useDeveloper: Show Agent Debug Logs or theGitHub Copilot Chat Hooks output channel to confirm that the hook loaded.Cursor IDE: Hooks are configured through~/.cursor/hooks.json
plus a generated bridge (dcg-pre-shell.ps1
on Windows). The installer inserts dcg first inbeforeShellExecution
, collapses duplicate dcg entries, and preserves coexisting Cursor hooks.Hermes Agent:NousResearch's Hermes Agentdeclares shell hooks in~/.hermes/config.yaml
underhooks.pre_tool_call
. The installer merges a singlematcher: "terminal"
entry that invokes dcg directly β no wrapper script β because Hermes' input JSON (hook_event_name: "pre_tool_call"
,tool_name: "terminal"
,tool_input.command
) deserializes straight into dcg's existingHookInput
. Hermesexplicitly documentsthat "non-zero exit codes... never abort the agent loop", so dcg switches to Hermes' JSON block protocol on output:{"decision":"block","reason":...}
(plus the alternate{"action":"block","message":...}
form for cross-version compatibility). The installer also setshooks_auto_accept: true
if not already set; Hermes silently drops un-allowlisted hooks in non-TTY runs (gateway/cron) without it.unconfigure_hermes
inuninstall.sh
removes only the dcg-owned entry and leaveshooks_auto_accept
alone (other Hermes hooks may rely on it).Grok (xAI):Grok Build / Grok CLIauto-discovers every*.json
under~/.grok/hooks/
.dcg install --grok
writes a self-contained~/.grok/hooks/dcg.json
with aPreToolUse
/matcher: "Bash"
entry β Grok internally aliases Claude-style"Bash"
to its ownrun_terminal_cmd
tool, so a single rule covers every shell command. dcg detects Grok at runtime from the camelCase wire shape (hookEventName: "pre_tool_use"
,toolName: "run_terminal_cmd"
) or from theGROK_SESSION_ID
/GROK_HOOK_EVENT
/GROK_WORKSPACE_ROOT
environment variables, and switches its output to Grok's JSON contract:{"decision":"deny","reason":...}
(note"deny"
, not Hermes'"block"
). Grok also picks up dcg automatically through its~/.claude/settings.json
compatibility layer, so existing Claude Code users get protection with no additional install step. Add--project
to write<repo>/.grok/hooks/dcg.json
for a per-repo install (Grok requires/hooks-trust
the first time it opens a repo with hooks).Antigravity CLI (agy
):Google Antigravity'sships a Claude-Code-compatible hooks system.agy
CLIdcg install --agy
merges aPreToolUse
/matcher: "Bash"
entry into~/.gemini/config/hooks.json
(the canonical path;agy
migrates the legacy~/.gemini/antigravity-cli/hooks.json
here and symlinks the old path to it).agy
runs the hook before itsrun_command
shell tool; dcg detectsagy
at runtime from the distinctive nestedtoolCall
envelope ({"toolCall":{"name":"run_command","args":{"CommandLine":"β¦"}},"conversationId":β¦,"stepIdx":β¦}
) β the shell command is read fromtoolCall.args.CommandLine
β or from theANTIGRAVITY_CONVERSATION_ID
environment variable /agy
parent-process name. dcg switches its output toagy
's JSON contract:{"decision":"block","reason":β¦}
with exit code 0 (verified:agy
honors both"block"
and"deny"
and aborts the tool; a non-zero exit code is only logged and does NOT reliably block, so dcg always emits exit 0 + JSON). Add--project
to write<repo>/.gemini/config/hooks.json
for a per-repo install. Restartagy
(start a new session) after installing.OpenCode: Not auto-configured. Requires a Bun-based plugin with"tool.execute.before"
hook key. A working community plugin:aspiers/ai-config/dcg-guard.js.Pi: Not auto-configured.Piintercepts shell commands through user-authored TypeScript extensions (pi.on("tool_call", β¦)
, auto-loaded from~/.pi/agent/extensions/*.ts
or<repo>/.pi/extensions/*.ts
). A ready-to-usedcg-guard.ts
extension that routes eachbash
command throughdcg --robot test
(exit 1 = deny) and blocks with the dcg reason is documented indocs/pi-integration.md.
Recommended:After installing, rundcg setup
to add a[shell startup check]that warns you if the dcg hook is ever silently removed from~/.claude/settings.json
.
This project uses Rust Edition 2024 features and requires the nightly toolchain. The repository includes a rust-toolchain.toml
that automatically selects the correct toolchain.
rustup install nightly
cargo +nightly install --git https://github.com/Dicklesworthstone/destructive_command_guard destructive_command_guard
git clone https://github.com/Dicklesworthstone/destructive_command_guard
cd destructive_command_guard
cargo build --release
cp target/release/dcg ~/.local/bin/
Run the built-in updater to re-run the installer for your platform:
dcg update
Optional flags mirror the installer scripts (examples):
dcg update --version v0.2.7
dcg update --system
dcg update --verify
You can always re-run install.sh
/ install.ps1
directly if preferred.
Prebuilt binaries are available for:
- Linux x86_64 (
x86_64-unknown-linux-gnu
) - Linux ARM64 (
aarch64-unknown-linux-gnu
) - macOS Intel (
x86_64-apple-darwin
) - macOS Apple Silicon (
aarch64-apple-darwin
) - Windows x64 (
x86_64-pc-windows-msvc
) - Windows ARM64 (
aarch64-pc-windows-msvc
)
Download from GitHub Releases and verify the SHA256 checksum.
If you have cosign installed, each release also includes a Sigstore bundle (.sigstore.json
) so you can verify provenance with cosign verify-blob
.
Remove dcg and all its hooks from AI agents:
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/uninstall.sh | bash
On Windows:
irm https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/uninstall.ps1 | iex
The Unix uninstaller:
- Removes dcg hooks from Claude Code, Codex CLI, Cursor IDE, Gemini CLI, GitHub Copilot CLI (user-level plus legacy repo-local), Hermes Agent, and Aider
- Removes the dcg binary
- Removes configuration (
~/.config/dcg/
) and history (~/.local/share/dcg/
) - Prompts for confirmation before making changes
The PowerShell uninstaller removes the Windows dcg.exe
binary, the exact User PATH entry added by install.ps1
, dcg hooks from Claude Code, Codex CLI, Gemini CLI, GitHub Copilot CLI, Cursor IDE, Hermes Agent, Grok, and Antigravity (agy
), plus dcg configuration/history directories.
Options:
--yes
-
Skip confirmation prompt
--keep-config -
Preserve configuration files
--keep-history -
Preserve history database
--purge -
Remove everything (overrides keep flags)
Add to ~/.claude/settings.json
:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "dcg"
}
]
}
]
}
}
Important: Restart Claude Code after adding the hook configuration.
Codex CLI 0.125.0+ supports stable PreToolUse
hooks. The installer writes or
merges this automatically, but the manual configuration lives at
~/.codex/hooks.json
:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "dcg"
}
]
}
]
}
}
Codex denials intentionally omit dcg's extended Claude-only fields: dcg exits 0
with the minimal documented hookSpecificOutput
JSON on stdout. Allowed commands stay silent with exit code 0.
Add to ~/.gemini/settings.json
:
{
"hooks": {
"BeforeTool": [
{
"matcher": "run_shell_command",
"hooks": [
{
"name": "dcg",
"type": "command",
"command": "dcg",
"timeout": 5000
}
]
}
]
}
}
Important: Restart Gemini CLI after adding the hook configuration.
While primarily designed as a hook, the binary supports direct invocation for testing, debugging, and understanding why commands are blocked or allowed.
dcg --version
dcg --help
echo '{"tool_name":"Bash","tool_input":{"command":"git reset --hard"}}' | dcg
Use dcg test
to evaluate a command without executing it. This is useful for CI checks, false-positive debugging, and config validation before rollout.
dcg test "rm -rf ./build"
dcg test --format json "kubectl delete namespace prod" | jq -r .decision
dcg test --config .dcg.prod.toml "docker system prune"
dcg test --with-packs containers.docker,database.postgresql "docker system prune"
dcg test --explain "git reset --hard"
0
: command would be allowed1
: command would be blocked
-c, --config <PATH>
: use a specific config file--with-packs <ID1,ID2>
: temporarily enable extra packs--explain
: print detailed decision trace-f, --format <pretty|json|toon>
: output format (default:pretty
)--no-color
: disable ANSI color output--heredoc-scan
: force-enable heredoc/inline-script scanning--no-heredoc-scan
: force-disable heredoc/inline-script scanning--heredoc-timeout <MS>
: override heredoc extraction timeout budget--heredoc-languages <LANG1,LANG2>
: limit heredoc AST scanning languages
pretty
: human-readable output with command context, matched rule info, and suggestionsjson
: structured payload for scripts/CI; includes metadata likeschema_version
,dcg_version
,command
,decision
, rule/pack fields, and allowlist/agent context when presenttoon
: token-efficient structured encoding of the same payload used byjson
(useful for agent-to-agent/tool pipelines)
Fail fast in shell pipelines:
dcg test --format json "rm -rf /" > /tmp/dcg.json
jq -e '.decision == "allow"' /tmp/dcg.json
Minimal GitHub Actions step:
- name: Validate dangerous command policy
run: |
~/.local/bin/dcg test --format json "git reset --hard HEAD~1" > /tmp/dcg-test.json
jq -e '.decision == "allow"' /tmp/dcg-test.json
- Use
--format json
(orDCG_FORMAT=json
) for machine parsing. - Add
--no-color
if logs or parsers choke on ANSI output. - If results differ between environments, check config precedence (
DCG_CONFIG
, project.dcg.toml
, user/system config). - If a command is unexpectedly allowed, inspect active allowlists (
dcg allowlist list
) and enabled packs (dcg packs --verbose
). - For full decision traces, run
dcg test --explain "<command>"
(ordcg explain "<command>"
).
When you need to understand exactly why a command was blocked (or allowed), the dcg explain
command provides a detailed trace of the decision-making process:
dcg explain "git reset --hard HEAD"
dcg explain "git status"
dcg explain --verbose "rm -rf /tmp/build"
dcg explain --format json "kubectl delete namespace production"
JSON output is versioned via schema_version
(currently 2). v2 adds
matched_span
, matched_text_preview
, and explanation
in the match
object when a pattern is detected.
Example Output:
Command: git reset --hard HEAD
Normalized: git reset --hard HEAD
Decision: BLOCKED
Pack: core.git
Rule: reset-hard
Reason: git reset --hard destroys uncommitted changes
Evaluation Trace:
[ 0.8ΞΌs] Quick reject: passed (contains 'git')
[ 2.1ΞΌs] Normalize: no changes
[ 5.3ΞΌs] Safe patterns: no match (checked 34 patterns)
[ 12.7ΞΌs] Destructive patterns: MATCH at pattern 'reset-hard'
[ 12.9ΞΌs] Total time: 12.9ΞΌs
Suggestion: Consider using 'git stash' first to save your changes.
The explain mode shows:
Normalized command: How dcg sees the command after path normalization** Decision**: Whether the command would be blocked or allowed** Matching rule**: Which pack and pattern triggered the decision** Evaluation trace**: Step-by-step timing of each evaluation stage** Suggestion**: Actionable guidance for safer alternatives
This is invaluable for debugging false positives, understanding pack coverage, and verifying that custom allowlist entries work as expected.
Sometimes you need to run a blocked command temporarily without permanently modifying your allowlist. The allow-once system provides short codes:
dcg allow-once 123456
dcg allow-once 123456 --single-use
How Allow-Once Works:
- When dcg blocks a command, it generates a short code (currently 6 numeric digits; collisions are handled via
--pick
/--hash
) - The code is tied to the exact command that was blocked
- Running
dcg allow-once <code>
creates a temporary exception - The exception is stored in
~/.config/dcg/pending_exceptions.jsonl
- Exceptions expire after 24 hours (or after first use if
--single-use
is used) - While active, the exception allows the same command in the same directory scope
This workflow is useful for:
- One-time administrative operations that are intentionally destructive
- Migration scripts that need to reset state
- Emergency fixes where permanent allowlist changes aren't appropriate
Security Considerations:
- Short codes are derived from SHA256 (or optional HMAC-SHA256 when
DCG_ALLOW_ONCE_SECRET
is set) - Codes are never logged or transmitted
- The pending exceptions file is readable only by the current user
- Expired codes are automatically cleaned up
AI coding agents routinely get stuck when git pull --rebase
fails partway β unstaged-changes errors, stash-pop conflicts, interrupted rebases. The documented recovery path is almost always git checkout -- .
or git restore <paths>
, both of which dcg hard-blocks (core.git:checkout-discard
, core.git:restore-worktree
). Agents then have to stop and ask a human to run the command manually.
Rebase-recovery mode is a narrow, bounded relaxation of those two rules that only fires under a genuine recovery signal. Outside that signal the default block is unchanged.
Two complementary signals unlock recovery:
Active rebase state (automatic, zero-config). When.git/rebase-merge/
or.git/rebase-apply/
exists, a rebase is in progress and the discard operationsarethe documented recovery path. dcg detects this state and converts the deny into an allow with a[dcg] Allowing ... β rebase-recovery mode
note on stderr. No permit needed. -
Explicit permit cookie (opt-in, short-lived). When the rebase already finished but the worktree is still messy (e.g. after a badgit stash pop
), run:
dcg rebase-recover # default ttl: 120s
dcg rebase-recover --ttl 60 # custom ttl (max: 600s)
This writes a timestamp to
.dcg/rebase-recovery-permit
at the repo root. For the next N seconds (or until the first matching allow, whichever comes first),git checkout -- <path>
andgit restore <paths>
are allowed. The permit issingle-shotβ one successful allow consumes it β so it can't silently unblock later unrelated commands within the TTL.
Scope and safety guarantees:
- Only four rules participate:
core.git:checkout-discard
,core.git:checkout-ref-discard
,core.git:restore-worktree
,core.git:restore-worktree-explicit
. Nothing else is affected.git reset --hard
,git clean -f
,git push --force
, etc. stay blocked even during an active rebase or with a permit active.- The permit is scoped to the current repo's
.dcg/
directory. It does not cross repos. - Expired permits are auto-cleaned on the next check.
Typical recovery flow:
$ git pull --rebase
$ git stash
$ git pull --rebase # succeeds
$ git stash pop # leaves messy worktree
$ git checkout -- .
BLOCKED by dcg (core.git:checkout-discard)
... Recovering from a failed `git pull --rebase`?
... Run `dcg rebase-recover` in this repo, then retry the command.
$ dcg rebase-recover
dcg rebase-recovery permit issued ...
$ git checkout -- . # now allowed, permit consumed
$ git push
See issue #104 for background.
The --version
output includes build metadata for debugging:
dcg 0.1.0
Built: 2026-01-07T22:13:10.413872881Z
Rustc: 1.94.0-nightly
Target: x86_64-unknown-linux-gnu
This metadata is embedded at compile time via vergen, making it easy to identify exactly which build is running when troubleshooting.
While the hook protects interactive command execution, teams also need protection against destructive commands that get committed into repositories. The dcg scan
command extracts executable command contexts from files and evaluates them using the same pattern engine.
What it is:
- An extractor-based scanner that understands executable contexts
- Uses the same evaluator as hook mode for consistency
- Supports CI integration and pre-commit hooks
What it is NOT:
- A naive grep that matches strings everywhere
- A replacement for code review
- A static analysis tool for arbitrary languages
The key difference from grep: dcg scan
understands that "rm -rf /"
in a comment is data, not code. It uses extractors that understand file structure (shell scripts, Dockerfiles, CI workflows, package scripts, Makefiles, Terraform, Docker Compose) to find only actually-executed commands.
dcg scan includes specialized extractors for each file format, understanding which parts contain executable commands:
| File Type | Detection | Executable Contexts |
|---|---|---|
| Shell Scripts | ||
*.sh , *.bash , *.zsh , *.dash , *.ksh |
||
| Non-comment executable command lines | ||
| Dockerfile | ||
Dockerfile , Dockerfile.* , *.dockerfile |
||
RUN instructions (shell and exec forms) |
||
| GitHub Actions | ||
.github/workflows/*.yml , .github/workflows/*.yaml |
||
run: fields in steps |
||
| GitLab CI | ||
.gitlab-ci.yml , *.gitlab-ci.yml |
||
script: , before_script: , after_script: |
||
| Azure Pipelines | ||
azure-pipelines.yml , azure-pipelines.yaml , azure-pipelines-*.yml , azure-pipelines-*.yaml |
||
script: , bash: , powershell: , pwsh: tasks |
||
| CircleCI | ||
.circleci/config.yml , .circleci/config.yaml |
||
run: steps and nested command: fields |
||
| Makefile | ||
Makefile |
||
| Tab-indented recipe lines | ||
| package.json | ||
package.json |
||
scripts object values |
||
| Terraform | ||
*.tf |
||
provisioner blocks (local-exec , remote-exec ) |
||
| Docker Compose | ||
docker-compose.yml , docker-compose.yaml , compose.yml , compose.yaml |
||
command: , entrypoint: , healthcheck.test: fields |
||
| PowerShell | ||
*.ps1 , *.psm1 , *.psd1 |
||
| Executable statements with line and block comments excluded | ||
| Batch Scripts | ||
*.cmd , *.bat |
||
| Executable command lines with comments excluded |
Context-Aware Extraction:
Each extractor understands its format's semantics:
- name: Build
run: | # β Extracted
npm install
npm run build
env:
NODE_ENV: production # β Skipped (not executable)
FROM node:18
COPY . /app # β Skipped
RUN npm install # β Extracted
RUN ["node", "server.js"] # β Extracted (exec form)
ENV PORT=3000 # β Skipped
build:
npm install # β Extracted (recipe line)
npm run build # β Extracted
SOURCES = $(wildcard *.js) # β Skipped (variable assignment)
Non-Executable Context Filtering:
Extractors intelligently skip data-only sections:
Shell: Assignment-only lines (export VAR=value
)YAML:environment:
,labels:
,volumes:
,variables:
blocksTerraform: Everything outsideprovisioner
blocksAll formats: Comments (format-appropriate:#
,//
, etc.)
dcg scan install-pre-commit
dcg scan --staged
dcg scan --paths scripts/ .github/workflows/
Start conservative to avoid developer friction:
dcg scan --staged --fail-on error # Only fail on catastrophic rules
Create .dcg/hooks.toml
with conservative defaults:
[scan]
fail_on = "error" # Only fail on high-confidence catastrophic rules
format = "pretty" # Human-readable output
redact = "quoted" # Hide sensitive strings
truncate = 120 # Shorten long commands
[scan.paths]
include = [
".github/workflows/**", # Start with CI configs
"Dockerfile", # Container builds
"Makefile", # Build scripts
]
exclude = [
"target/**",
"node_modules/**",
"vendor/**",
]
Gradual expansion:
Week 1-2: Start with workflows/Dockerfiles only,--fail-on error
Week 3-4: Add Makefiles and shell scripts inscripts/
Month 2: Add--fail-on warning
after reviewing findingsOngoing: Add new extractors as team confidence grows
dcg scan install-pre-commit
This creates a .git/hooks/pre-commit
that runs dcg scan --staged
.
If you prefer manual control or use a hook manager:
#!/bin/bash
set -e
dcg scan --staged --fail-on error
dcg scan uninstall-pre-commit
This only removes hooks installed by dcg (detected via sentinel comment).
The output includes:
scripts/deploy.sh:42:5: [ERROR] core.git:reset-hard
Command: git reset --hard HEAD
Reason: git reset --hard destroys uncommitted changes
Suggestion: Consider using 'git stash' first to save changes.
File:Line:Col: Location in the source file** Severity**:ERROR
(catastrophic) orWARNING
(concerning)Rule ID: Stable identifier likecore.git:reset-hard
Command: The extracted command (may be redacted/truncated)** Reason**: Why this command is flagged** Suggestion**: How to make it safer
Replace the dangerous command with a safer alternative:
git reset --hard
git stash push -m "before reset"
git reset --hard
Get detailed analysis:
dcg explain "git reset --hard HEAD"
If the command is genuinely needed:
dcg allowlist add core.git:reset-hard --reason "Required for CI cleanup" --project
dcg allowlist add-command "rm -rf ./build" --reason "Build cleanup" --project
The finding output includes a copy-paste allowlist command for convenience.
Heredoc rules use stable IDs like heredoc.python.shutil_rmtree
.
Scan supports redaction of potentially sensitive content in output. Use --redact quoted
to hide quoted strings that may contain secrets:
curl -H "Authorization: Bearer $TOKEN" https://api.example.com
curl -H "..." https://api.example.com
Options:
--redact none
: Show full commands (default)--redact quoted
: Hide quoted strings (recommended for CI logs)--redact aggressive
: Hide more potential secrets
.dcg/hooks.toml
(project-level, committed):
[scan]
fail_on = "error" # Options: none, warning, error
format = "pretty" # Options: pretty, json, markdown
max_file_size = 1000000
max_findings = 50
redact = "quoted" # Options: none, quoted, aggressive
truncate = 120
[scan.paths]
include = [
"scripts/**",
".github/workflows/**",
"Dockerfile*",
"Makefile",
]
exclude = [
"target/**",
"node_modules/**",
"*.md",
]
CLI flags override config file values.
name: Security Scan
on: [pull_request]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install dcg
run: |
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh" | bash
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Scan changed files
run: |
dcg scan --git-diff origin/${{ github.base_ref }}..HEAD \
--format markdown \
--fail-on error
scan:
stage: test
script:
- curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh" | bash
- ~/.local/bin/dcg scan --git-diff origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME..HEAD --fail-on error
rules:
- if: $CI_MERGE_REQUEST_ID
If you need to bypass the pre-commit hook temporarily:
git commit --no-verify -m "Emergency fix"
This is logged and visible in git history. For permanent exceptions, use allowlists instead.
Your AI agent invokes dcg as a PreToolUse hook before executing each shell command. The hook receives the command as JSON on stdin and runs through a four-stage pipeline:
JSON Parsing-- Validates the hook payload (Claude/Gemini/Copilot variants), extracts the command string. Non-shell tools are immediately allowed.Normalization-- Strips absolute paths (/usr/bin/git
becomesgit
) while preserving arguments.Quick Reject-- O(n) substring search for keywords like "git" or "rm". Commands without these substrings skip regex matching entirely (handles 99%+ of non-destructive commands).Pattern Matching-- Safe patterns checked first (match = allow). Destructive patterns checked second (match = deny with explanation). No match on either = allow.
If blocked under a Claude-compatible JSON hook protocol, dcg outputs a JSON denial on stdout and a colorful human-readable warning on stderr. If blocked under Codex CLI, dcg follows Codex's strict hook contract with minimal stdout JSON and exit code 0. If allowed, dcg exits silently. Rich formatting is automatically disabled for CI, non-TTY output, dumb terminals, and no-color environments.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Claude / Codex / Gemini / Copilot / Cursor / Hermes hooks β
β β
β User: "delete the build artifacts" β
β Agent: executes `rm -rf ./build` β
β β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ PreToolUse hook (stdin: JSON)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β dcg β
β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Parse βββββΆβ Normalize βββββΆβ Quick Reject β β
β β JSON β β Command β β Filter β β
β ββββββββββββββββ ββββββββββββββββ ββββββββ¬ββββββββ β
β β β
β βββββββββββββββββββββββββββββ β
β βΌ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Pattern Matching β β
β β β β
β β 1. Check SAFE_PATTERNS (whitelist) βββΆ Allow if match β β
β β 2. Check DESTRUCTIVE_PATTERNS βββββββΆ Deny if match β β
β β 3. No match βββββββββββββββββββββββββΆ Allow (default) β β
β β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ stdout: JSON deny / empty allow
stderr: rich human output / Codex deny reason
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Claude / Codex / Gemini / Copilot / Cursor / Hermes hooks β
β β
β If denied: Shows block message, does NOT execute command β
β If allowed: Proceeds with command execution β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Not every occurrence of a dangerous pattern is actually dangerous. The string git reset --hard
appearing in a comment, a heredoc body, or a quoted string is fundamentally different from the same string appearing as an executed command. dcg uses a sophisticated context classification system to reduce false positives without compromising safety.
SpanKind Classification
Every token in a command is classified into one of these categories:
| SpanKind | Description | Treatment |
|---|---|---|
Executed |
||
| Command words and unquoted arguments | MUST check - highest priority | |
InlineCode |
||
Content inside -c /-e flags (bash -c, python -c) |
||
| MUST check - code will be executed | ||
Argument |
||
| Quoted arguments to known-safe commands | Lower priority, context-dependent | |
Data |
||
| Single-quoted strings (shell cannot interpolate) | Can skip - treated as literal data | |
HeredocBody |
||
| Content inside heredocs | Escalated to Tier 2/3 heredoc scanning | |
Comment |
||
Shell comments (# ... ) |
||
| Skip - never executed | ||
Unknown |
||
| Cannot determine context | Conservative treatment as Executed |
Why Context Matters
Consider these commands:
echo "Reminder: never run git reset --hard" # git reset --hard destroys changes
grep "git reset --hard" documentation.md
cat <<EOF > safety_guide.md
Warning: git reset --hard destroys uncommitted changes
EOF
git reset --hard HEAD
bash -c "git reset --hard"
Without context classification, the first three examples would trigger false positives. The context classifier analyzes the AST (abstract syntax tree) structure to understand where patterns appear and only flags genuinely dangerous occurrences.
Implementation Details
The context classifier uses a multi-pass approach:
Lexical Analysis: Identify quoted strings, comments, and heredoc markers** Structural Analysis**: Build a tree of command structure, identifying pipes, subshells, and command substitutions** Flag Analysis**: Detect-c
,-e
, and similar flags that introduce inline code contextsSpan Annotation: Tag each character range with its SpanKind
This approach achieves a significant reduction in false positives while maintaining the zero-false-negatives philosophy for actual command execution.
Safe patterns are checked before destructive patterns. This design ensures that explicitly safe commands (like git checkout -b
) are never accidentally blocked, even if they partially match a destructive pattern (like git checkout
).
git checkout -b feature β Matches SAFE "checkout-new-branch" β ALLOW
git checkout -- file.txt β No safe match, matches DESTRUCTIVE β DENY
The hook uses a default-allow policy for unrecognized commands. This ensures:
- The hook never breaks legitimate workflows
- Only knowndangerous patterns are blocked - New git commands are allowed until explicitly categorized
The pattern set prioritizes never allowing dangerous commands over avoiding false positives. A few extra prompts for manual confirmation are acceptable; lost work is not.
This hook is one layer of protection. It complements (not replaces):
- Regular commits and pushes
- Git stash before risky operations
- Proper backup strategies
- Code review processes
Every Bash command passes through this hook. Performance is critical:
- Lazy-initialized static regex patterns (compiled once, reused)
- Quick rejection filter eliminates 99%+ of commands before regex
- No heap allocations on the hot path for safe commands
- Sub-millisecond execution for typical commands
The safe pattern list contains 34 patterns covering:
| Category | Patterns | Purpose |
|---|---|---|
| Branch creation | checkout -b , checkout --orphan |
|
| Creating branches is safe | ||
| Staged-only | restore --staged , restore -S |
|
| Unstaging doesn't touch working tree | ||
| Dry run | clean -n , clean --dry-run |
|
| Preview mode, no actual deletion | ||
| Temp cleanup | rm -rf /tmp/* , rm -rf /var/tmp/* |
|
| Ephemeral directories are safe | ||
| Variable expansion | rm -rf $TMPDIR/* , rm -rf ${TMPDIR}/* |
|
| Shell variable forms | ||
| Quoted paths | rm -rf "$TMPDIR/*" |
|
| Quoted variable forms | ||
| Separate flags | rm -r -f /tmp/* , rm -r -f $TMPDIR/* |
|
| Flag ordering variants | ||
| Long flags | rm --recursive --force /tmp/* , $TMPDIR/* |
|
| GNU-style long options |
The destructive pattern list contains 16 patterns covering:
| Category | Pattern | Reason |
|---|---|---|
| Work destruction | reset --hard , reset --merge |
|
| Destroys uncommitted changes | ||
| File reversion | checkout -- <path> |
|
| Discards file modifications | ||
| Worktree restore | restore (without --staged) |
|
| Discards uncommitted changes | ||
| Untracked deletion | clean -f |
|
| Permanently removes untracked files | ||
| History rewrite | push --force , push -f |
|
| Can destroy remote commits | ||
| Unsafe branch delete | branch -D |
|
| Force-deletes without merge check | ||
| Stash destruction | stash drop , stash clear |
|
| Permanently deletes stashed work | ||
| Filesystem nuke | rm -rf (non-temp paths) |
|
| Recursive deletion outside temp |
Patterns use fancy-regex for advanced features:
// Negative lookahead: block restore UNLESS --staged is present
r"git\s+restore\s+(?!--staged\b)(?!-S\b)"
// Negative lookahead: don't match --force-with-lease
r"git\s+push\s+.*--force(?![-a-z])"
// Character class: match any flag ordering
r"rm\s+-[a-zA-Z]*[rR][a-zA-Z]*f[a-zA-Z]*"