{"slug": "show-hn-block-dangerous-git-and-shell-commands-from-being-executed-by-agents", "title": "Show HN: Block dangerous Git and shell commands from being executed by agents", "summary": "A developer released a high-performance hook tool called dcg that blocks dangerous Git and shell commands from being executed by AI coding agents, protecting against accidental data loss from commands like git reset --hard or rm -rf. The tool supports multiple agent platforms including Claude Code, Codex CLI, Gemini CLI, and Copilot CLI, and offers zero-config protection with sub-millisecond latency.", "body_md": "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.\n\n**Supported:** [Claude Code](https://claude.ai/code), [Codex CLI 0.125.0+](https://github.com/openai/codex), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/concepts/agents/coding-agent/about-hooks), [VS Code Copilot Chat](https://code.visualstudio.com/docs/agent-customization/hooks), [Cursor IDE](https://cursor.com), [Hermes Agent](https://github.com/NousResearch/hermes-agent), [Grok (xAI)](https://x.ai/news/grok-build-cli) (native `~/.grok/hooks/`\n\nplus Claude compatibility layer), [Antigravity CLI ( agy)](https://antigravity.google) (native\n\n`~/.gemini/config/hooks.json`\n\nvia `dcg install --agy`\n\n), [OpenCode](https://opencode.ai)(via\n\n[community plugin](https://github.com/aspiers/ai-config/blob/main/.config/opencode/plugins/dcg-guard.js)),\n\n[Pi](https://github.com/earendil-works/pi)(via\n\n[extension recipe](/Dicklesworthstone/destructive_command_guard/blob/main/docs/pi-integration.md)),\n\n[Aider](https://aider.chat/)(limited—git hooks only),\n\n[Continue](https://continue.dev)(detection only)\n\n```\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash -s -- --easy-mode\n```\n\n*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.*\n\n```\n& ([scriptblock]::Create((irm \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.ps1\"))) -EasyMode -Verify\n```\n\n*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.*\n\n**The Problem**: AI coding agents (Claude, Codex, Gemini, Copilot, etc.) occasionally run catastrophic commands like `git reset --hard`\n\n, `rm -rf ./src`\n\n, or `DROP TABLE users`\n\n—destroying hours of uncommitted work in seconds.\n\n**The Solution**: dcg is a high-performance hook that intercepts destructive commands *before* they execute, blocking them with clear explanations and safer alternatives.\n\n| Feature | What It Does |\n|---|---|\nZero-Config Protection |\nBlocks dangerous git/filesystem commands out of the box |\n50+ Security Packs |\nDatabases, Kubernetes, Docker, AWS/GCP/Azure, Terraform, and more |\nSub-Millisecond Latency |\nSIMD-accelerated filtering—you won't notice it's there |\nHeredoc/Inline Script Scanning |\nCatches `python -c \"os.remove(...)\"` and embedded shell scripts |\nSmart Context Detection |\nWon't block `grep \"rm -rf\"` (data) but will block `rm -rf /` (execution) |\nRich Terminal Output |\nHuman-readable denial panels, rule context, and suggestions on stderr |\nAgent-Safe Streams |\nMachine-readable hook output stays on stdout while rich UI stays on stderr |\nNative Codex Support |\nCodex CLI 0.125.0+ receives a minimal stdout JSON denial that current clients enforce reliably |\nGraceful Degradation |\nPlain output for CI, pipes, dumb terminals, and no-color environments |\nScan Mode for CI |\nPre-commit hooks and CI integration to catch dangerous commands in code review |\nFail-Open Design |\nNever blocks your workflow due to timeouts or parse errors |\nExplain Mode |\n`dcg explain \"command\"` shows exactly why something is blocked |\n\n``` bash\n# AI agent tries to run:\n$ git reset --hard HEAD~5\n\n# dcg intercepts and blocks:\n════════════════════════════════════════════════════════════════\nBLOCKED  dcg\n────────────────────────────────────────────────────────────────\nReason:  git reset --hard destroys uncommitted changes\n\nCommand: git reset --hard HEAD~5\n\nTip: Consider using 'git stash' first to save your changes.\n════════════════════════════════════════════════════════════════\n# ~/.config/dcg/config.toml\n[packs]\nenabled = [\n    \"database.postgresql\",    # Blocks DROP TABLE, TRUNCATE\n    \"kubernetes.kubectl\",     # Blocks kubectl delete namespace\n    \"cloud.aws\",              # Blocks aws ec2 terminate-instances\n    \"containers.docker\",      # Blocks docker system prune\n]\n```\n\ndcg automatically detects which AI coding agent is invoking it and can apply\nagent-specific configuration. The `trust_level`\n\nfield is an **advisory label**\nrecorded in JSON output and logs — it does not directly change rule evaluation.\nBehavioral differences come from the other profile fields:\n\n| Option | Effect |\n|---|---|\n`disabled_packs` |\nRemoves rule packs from evaluation |\n`extra_packs` |\nAdds rule packs to evaluation |\n`additional_allowlist` |\nAdds command patterns that bypass deny rules |\n`disabled_allowlist` |\nWhen `true` , ignores all allowlist entries |\n\n```\n# Trust Claude Code more — wider allowlist, fewer packs\n[agents.claude-code]\ntrust_level = \"high\"\nadditional_allowlist = [\"npm run build\", \"cargo test\"]\ndisabled_packs = [\"kubernetes\"]\n\n# Restrict unknown agents — extra rules, no allowlist bypass\n[agents.unknown]\ntrust_level = \"low\"\nextra_packs = [\"paranoid\"]\ndisabled_allowlist = true\n```\n\nSee [docs/agents.md](/Dicklesworthstone/destructive_command_guard/blob/main/docs/agents.md) for full documentation on supported agents,\ntrust levels, and configuration options.\n\ndcg now treats Codex CLI as a first-class hook target, not just a Claude-shaped\ncompatibility path. The installer configures Codex CLI 0.125.0+ automatically\nwhen it detects `codex`\n\non `PATH`\n\nor an existing `~/.codex/`\n\ndirectory.\n\n| Codex behavior | dcg handling |\n|---|---|\n| Hook config | Merges a `PreToolUse` Bash hook into `~/.codex/hooks.json` |\n| Denied command | Exits 0 with a minimal `hookSpecificOutput` denial on stdout; human warning stays on stderr |\n| Allowed command | Exits 0 with empty stdout and stderr |\n| Existing hooks | Preserves coexisting hooks, keeps dcg first for Bash, and refuses to overwrite malformed JSON |\n| Validation | Covered by subprocess protocol tests plus an opt-in real Codex E2E harness |\n\nCodex's hook input is intentionally close to Claude Code's, but Codex rejects\nunknown fields in hook output. dcg detects Codex payloads from the non-empty\n`turn_id`\n\nfield and emits only Codex's documented denial fields so a blocked\ncommand is reported as blocked rather than as a failed hook. See\n[docs/codex-integration.md](/Dicklesworthstone/destructive_command_guard/blob/main/docs/codex-integration.md) for protocol details,\nmanual probes, and troubleshooting.\n\nThis 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.\n\n- Original concept and Python implementation ([Jeffrey Emanuel](https://github.com/Dicklesworthstone)[source](https://github.com/Dicklesworthstone/misc_coding_agent_tips_and_scripts/blob/main/DESTRUCTIVE_GIT_COMMAND_CLAUDE_HOOKS_SETUP.md)); 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 optimizations[Darin Gordon](https://github.com/Dowwie)\n\nThe 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.\n\nIf dcg is blocking something you genuinely need to run:\n\n| Method | Scope | How |\n|---|---|---|\nEnv var bypass |\nSingle command | `DCG_BYPASS=1 <command>` |\nAllow-once code |\nSingle command | Copy the short code from the block message, run `dcg allow-once <code>` |\nPermanent allowlist |\nRule or command | `dcg allowlist add core.git:reset-hard -r \"reason\"` |\nRemove the hook |\nAll commands | Delete or comment out the dcg entry in `~/.claude/settings.json` (or equivalent for your agent) |\n\n`DCG_BYPASS=1`\n\ndisables all protection for that invocation. Use it sparingly and prefer allowlists for recurring needs.\n\ndcg uses a modular \"pack\" system to organize destructive command patterns by category. Packs can be enabled or disabled in the configuration file.\n\n- Full pack ID index:\n`docs/packs/README.md`\n\n- Canonical descriptions + pattern counts:\n`dcg packs --verbose`\n\nWith **no config file present**, dcg enables only the packs that guard against the\nmost catastrophic, unrecoverable mistakes:\n\n`core.filesystem`\n\n- Dangerous`rm -rf`\n\noutside temp directories*(always on; cannot be disabled)*`core.git`\n\n- Destructive git commands that lose uncommitted work, rewrite history, or destroy stashes*(always on; cannot be disabled)*`system.disk`\n\n-`mkfs`\n\n,`dd`\n\n-to-device,`fdisk`\n\n,`parted`\n\n,`mdadm`\n\n,`lvm`\n\nremoval,`wipefs`\n\n*(on by default; opt out with*`disabled = [\"system.disk\"]`\n\n)\n\nOn **Windows**, two additional packs are on by default so a fresh install blocks the\ncatastrophic native-Windows operations with no config:\n\n`windows.filesystem`\n\n- cmd`del /s`\n\n,`rd /s`\n\n,`format <drive>:`\n\nand PowerShell`Remove-Item -Recurse -Force`\n\n(and aliases),`Clear-Content`\n\n,`Clear-RecycleBin`\n\n*(default-on***on Windows only**; opt out with`disabled = [\"windows.filesystem\"]`\n\nor`[\"windows\"]`\n\n)`windows.system`\n\n-`vssadmin delete shadows`\n\n/`wmic shadowcopy delete`\n\n(Volume Shadow Copy destruction),`diskpart`\n\n,`Format-Volume`\n\n,`Clear-Disk`\n\n,`Remove-Partition`\n\n,`cipher /w`\n\n,`bcdedit /delete`\n\n*(default-on***on Windows only**; opt out with`disabled = [\"windows.system\"]`\n\nor`[\"windows\"]`\n\n)\n\nThe broader `windows.misc`\n\n(`reg delete`\n\n, `net user /delete`\n\n, `wsl --unregister`\n\n, `robocopy /MIR`\n\n) and\n`windows.powershell`\n\n(registry/provider deletes, `Remove-LocalUser`\n\n, `Disable-ComputerRestore`\n\n, `Remove-VM`\n\n)\npacks are opt-in on every platform. On Unix the `windows.*`\n\npacks are registered but off by default; enable\nthem (e.g. to scan committed `.ps1`\n\n/`.cmd`\n\nscripts in CI) via `[packs] enabled = [\"windows\"]`\n\n.\n\nEvery other pack — including `database.postgresql`\n\nand `containers.docker`\n\n— is\n**opt-in** and is *not* active until a config file enables it. Running `dcg init`\n\nwrites a starter `~/.config/dcg/config.toml`\n\nwhose `[packs] enabled`\n\nlist turns on\n`database.postgresql`\n\nand `containers.docker`\n\nas common examples, but that is a\ngenerated starter config, not the no-config default. Enable any pack below by adding\nit to `[packs] enabled`\n\n— see [Enable More Protection](#enable-more-protection).\n\n`storage.s3`\n\n- Protects against destructive S3 operations like bucket removal, recursive deletes, and sync --delete.`storage.gcs`\n\n- Protects against destructive GCS operations like bucket removal, object deletion, and recursive deletes.`storage.minio`\n\n- Protects against destructive MinIO Client (mc) operations like bucket removal, object deletion, and admin operations.`storage.azure_blob`\n\n- Protects against destructive Azure Blob Storage operations like container deletion, blob deletion, and azcopy remove.\n\n`remote.rsync`\n\n- Protects against destructive rsync operations like --delete and its variants.`remote.scp`\n\n- Protects against destructive SCP operations like overwrites to system paths.`remote.ssh`\n\n- Protects against destructive SSH operations like remote command execution and key management.\n\n`database.postgresql`\n\n- Protects against destructive PostgreSQL operations like DROP DATABASE, TRUNCATE, and dropdb.`database.mysql`\n\n- MySQL/MariaDB guard.`database.mongodb`\n\n- Protects against destructive MongoDB operations like dropDatabase, dropCollection, and remove without criteria.`database.redis`\n\n- Protects against destructive Redis operations like FLUSHALL, FLUSHDB, and mass key deletion.`database.sqlite`\n\n- Protects against destructive SQLite operations like DROP TABLE, DELETE without WHERE, and accidental data loss.`database.supabase`\n\n- Protects against destructive Supabase CLI operations including database resets, migration rollbacks, function/secret/storage deletion, project removal, and infrastructure changes.\n\n`containers.docker`\n\n- Protects against destructive Docker operations like system prune, volume prune, and force removal.`containers.compose`\n\n- Protects against destructive Docker Compose operations like down -v which removes volumes.`containers.podman`\n\n- Protects against destructive Podman operations like system prune, volume prune, and force removal.\n\n`kubernetes.kubectl`\n\n- Protects against destructive kubectl operations like delete namespace, drain, and mass deletion.`kubernetes.helm`\n\n- Protects against destructive Helm operations like uninstall and rollback without dry-run.`kubernetes.kustomize`\n\n- Protects against destructive Kustomize operations when combined with kubectl delete or applied without review.\n\n`cloud.aws`\n\n- Protects against destructive AWS CLI operations like terminate-instances, delete-db-instance, and s3 rm --recursive.`cloud.azure`\n\n- Protects against destructive Azure CLI operations like vm delete, storage account delete, and resource group delete.`cloud.gcp`\n\n- Protects against destructive gcloud operations like instances delete, sql instances delete, and gsutil rm -r.\n\n`cdn.cloudflare_workers`\n\n- Protects against destructive Cloudflare Workers, KV, R2, and D1 operations via the Wrangler CLI.`cdn.cloudfront`\n\n- Protects against destructive AWS CloudFront operations like deleting distributions, cache policies, and functions.`cdn.fastly`\n\n- Protects against destructive Fastly CLI operations like service, domain, backend, and VCL deletion.\n\n`apigateway.apigee`\n\n- Protects against destructive Google Apigee CLI and apigeecli operations.`apigateway.aws`\n\n- Protects against destructive AWS API Gateway CLI operations for both REST APIs and HTTP APIs.`apigateway.kong`\n\n- Protects against destructive Kong Gateway CLI, deck CLI, and Admin API operations.\n\n`infrastructure.ansible`\n\n- Protects against destructive Ansible operations like dangerous shell commands and unchecked playbook runs.`infrastructure.atmos`\n\n- Protects against destructive Atmos operations like terraform deploy (auto-approve), clean, destroy, state rm/taint, and helmfile destroy.`infrastructure.pulumi`\n\n- Protects against destructive Pulumi operations like destroy and up with -y (auto-approve).`infrastructure.terraform`\n\n- Protects against destructive Terraform operations like destroy, taint, and apply with -auto-approve.\n\n`system.disk`\n\n- 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`\n\n- Protects against dangerous permission changes like chmod 777, recursive chmod/chown on system directories.`system.services`\n\n- Protects against dangerous service operations like stopping critical services and modifying init configuration.\n\n`cicd.circleci`\n\n- Protects against destructive CircleCI operations like deleting contexts, removing secrets, deleting orbs/namespaces, or removing pipelines.`cicd.github_actions`\n\n- Protects against destructive GitHub Actions operations like deleting secrets/variables or using gh api DELETE against /actions endpoints.`cicd.gitlab_ci`\n\n- Protects against destructive GitLab CI/CD operations like deleting variables, removing artifacts, and unregistering runners.`cicd.jenkins`\n\n- Protects against destructive Jenkins CLI/API operations like deleting jobs, nodes, credentials, or build history.\n\n`secrets.aws_secrets`\n\n- Protects against destructive AWS Secrets Manager and SSM Parameter Store operations like delete-secret and delete-parameter.`secrets.doppler`\n\n- Protects against destructive Doppler CLI operations like deleting secrets, configs, environments, or projects.`secrets.onepassword`\n\n- Protects against destructive 1Password CLI operations like deleting items, documents, users, groups, and vaults.`secrets.vault`\n\n- Protects against destructive Vault CLI operations like deleting secrets, disabling auth/secret engines, revoking leases/tokens, and deleting policies.\n\n`platform.github`\n\n- Protects against destructive GitHub CLI operations like deleting repositories, gists, releases, or SSH keys.`platform.gitlab`\n\n- Protects against destructive GitLab platform operations like deleting projects, releases, protected branches, and webhooks.`platform.kamal`\n\n- Protects against destructive Kamal 2.x operations that tear down the stack (`kamal remove`\n\n), delete accessory data directories (`kamal accessory remove`\n\n), drop proxy routing, take the app offline, or prune the images that`kamal rollback`\n\nrelies on.`platform.modal`\n\n- Protects against destructive Modal serverless platform operations like recursive volume removal, app stops with`--force`\n\n, and secret deletion.`platform.railway`\n\n- Protects against destructive Railway CLI and Public API operations that can delete projects, environments, services, functions, volumes, variables, or deployments.\n\n`dns.cloudflare`\n\n- Protects against destructive Cloudflare DNS operations like record deletion, zone deletion, and targeted Terraform destroy.`dns.generic`\n\n- Protects against destructive or risky DNS tooling usage (nsupdate deletes, zone transfers).`dns.route53`\n\n- Protects against destructive AWS Route53 DNS operations like hosted zone deletion and record set DELETE changes.\n\n`email.mailgun`\n\n- Protects against destructive Mailgun API operations like domain deletion, route deletion, and mailing list removal.`email.postmark`\n\n- Protects against destructive Postmark API operations like server deletion, template deletion, and sender signature removal.`email.sendgrid`\n\n- Protects against destructive SendGrid API operations like template deletion, API key deletion, and domain authentication removal.`email.ses`\n\n- Protects against destructive AWS Simple Email Service operations like identity deletion, template deletion, and configuration set removal.\n\n`featureflags.flipt`\n\n- Protects against destructive Flipt CLI and API operations.`featureflags.launchdarkly`\n\n- Protects against destructive LaunchDarkly CLI and API operations.`featureflags.split`\n\n- Protects against destructive Split.io CLI and API operations.`featureflags.unleash`\n\n- Protects against destructive Unleash CLI and API operations.\n\n`loadbalancer.elb`\n\n- 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`\n\n- Protects against destructive HAProxy load balancer operations like stopping the service or disabling backends via runtime API.`loadbalancer.nginx`\n\n- Protects against destructive nginx load balancer operations like stopping the service or deleting config files.`loadbalancer.traefik`\n\n- Protects against destructive Traefik load balancer operations like stopping containers, deleting config, or API deletions.\n\n`messaging.kafka`\n\n- Protects against destructive Kafka CLI operations like deleting topics, removing consumer groups, resetting offsets, and deleting records.`messaging.nats`\n\n- Protects against destructive NATS/JetStream operations like deleting streams, consumers, key-value entries, objects, and accounts.`messaging.rabbitmq`\n\n- Protects against destructive RabbitMQ operations like deleting queues/exchanges, purging queues, deleting vhosts, and resetting cluster state.`messaging.sqs_sns`\n\n- Protects against destructive AWS SQS and SNS operations like deleting queues, purging messages, deleting topics, and removing subscriptions.\n\n`monitoring.datadog`\n\n- Protects against destructive Datadog CLI/API operations like deleting monitors and dashboards.`monitoring.newrelic`\n\n- Protects against destructive New Relic CLI/API operations like deleting entities or alerting resources.`monitoring.pagerduty`\n\n- Protects against destructive PagerDuty CLI/API operations like deleting services and schedules (which can break incident routing).`monitoring.prometheus`\n\n- Protects against destructive Prometheus/Grafana operations like deleting time series data or dashboards/datasources.`monitoring.splunk`\n\n- Protects against destructive Splunk CLI/API operations like index removal and REST API DELETE calls.\n\n`payment.braintree`\n\n- Protects against destructive Braintree/PayPal payment operations like deleting customers or cancelling subscriptions via API/SDK calls.`payment.square`\n\n- Protects against destructive Square CLI/API operations like deleting catalog objects or customers (which can break payment flows).`payment.stripe`\n\n- Protects against destructive Stripe CLI/API operations like deleting webhook endpoints and customers, or rotating API keys without coordination.\n\n`search.algolia`\n\n- Protects against destructive Algolia operations like deleting indices, clearing objects, removing rules/synonyms, and deleting API keys.`search.elasticsearch`\n\n- Protects against destructive Elasticsearch REST API operations like index deletion, delete-by-query, index close, and cluster setting changes.`search.meilisearch`\n\n- Protects against destructive Meilisearch REST API operations like index deletion, document deletion, delete-batch, and API key removal.`search.opensearch`\n\n- Protects against destructive OpenSearch REST API operations and AWS CLI domain deletions.\n\n`backup.borg`\n\n- Protects against destructive borg operations like delete, prune, compact, and recreate.`backup.rclone`\n\n- Protects against destructive rclone operations like sync, delete, purge, dedupe, and move.`backup.restic`\n\n- Protects against destructive restic operations like forgetting snapshots, pruning data, removing keys, and cache cleanup.`backup.velero`\n\n- Protects against destructive velero operations like deleting backups, schedules, and locations.\n\nNative-Windows (cmd.exe + PowerShell) destructive-command protection. `windows.filesystem`\n\nand\n`windows.system`\n\nare **default-on on Windows** (off/opt-in on Unix); `windows.misc`\n\nand\n`windows.powershell`\n\nare opt-in everywhere. All patterns are case-insensitive.\n\n`windows.filesystem`\n\n- Recursive/forced filesystem destruction: cmd`del /s`\n\n,`rd /s`\n\n/`rmdir /s`\n\n,`format <drive>:`\n\n; PowerShell`Remove-Item -Recurse -Force`\n\n(and aliases`rm`\n\n/`del`\n\n/`rd`\n\n/`ri`\n\n),`Clear-Content`\n\n,`Clear-RecycleBin`\n\n. Whitelists PowerShell`-WhatIf`\n\npreviews only on cmdlets/aliases that honor it, plus temp-dir deletes.`windows.system`\n\n- Catastrophic disk/system operations:`vssadmin delete shadows`\n\nand`wmic shadowcopy delete`\n\n(Volume Shadow Copy destruction — a ransomware hallmark),`diskpart`\n\n,`Format-Volume`\n\n,`Clear-Disk`\n\n,`Remove-Partition`\n\n,`Initialize-Disk`\n\n/`Reset-PhysicalDisk`\n\n,`cipher /w`\n\n,`bcdedit /delete`\n\n.`windows.misc`\n\n- Registry/account/service/WSL/copy destruction:`reg delete`\n\n,`net user|localgroup /delete`\n\n,`sc delete`\n\n,`schtasks /delete`\n\n,`wsl --unregister`\n\n(destroys a WSL distro),`robocopy /MIR`\n\n(mirror-delete).`windows.powershell`\n\n- Destructive PowerShell cmdlets: registry/provider deletes (`Remove-Item HKLM:\\`\n\n,`Remove-ItemProperty`\n\n,`Remove-PSDrive`\n\n),`Remove-LocalUser`\n\n/`Remove-LocalGroup`\n\n,`Unregister-ScheduledTask`\n\n,`Disable-ComputerRestore`\n\n, forced`Stop-Computer`\n\n/`Restart-Computer`\n\n,`Remove-VM`\n\n/`Remove-AppxPackage`\n\n.\n\n`package_managers`\n\n- Protects against dangerous package manager operations like publishing packages and removing critical system packages.`strict_git`\n\n- Stricter git protections: blocks all force pushes, rebases, and history rewriting operations.\n\nEnable packs in `~/.config/dcg/config.toml`\n\n:\n\n```\n[packs]\nenabled = [\n    # Databases\n    \"database.postgresql\",\n    \"database.redis\",\n    \"database.supabase\",\n\n    # Containers and orchestration\n    \"containers.docker\",\n    \"kubernetes\",  # Enables all kubernetes sub-packs\n\n    # Cloud providers\n    \"cloud.aws\",\n    \"cloud.gcp\",\n\n    # Secrets management\n    \"secrets.aws_secrets\",\n    \"secrets.vault\",\n\n    # CI/CD\n    \"cicd.jenkins\",\n    \"cicd.gitlab_ci\",\n\n    # Messaging\n    \"messaging.kafka\",\n    \"messaging.sqs_sns\",\n\n    # Search engines\n    \"search.elasticsearch\",\n\n    # Backup\n    \"backup.restic\",\n\n    # Platform\n    \"platform.github\",\n    \"platform.railway\",\n\n    # Monitoring\n    \"monitoring.splunk\",\n]\n```\n\nCreate 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.\n\n```\n[packs]\ncustom_paths = [\n    \"~/.config/dcg/packs/*.yaml\",      # User packs\n    \".dcg/packs/*.yaml\",               # Project-local packs\n]\n```\n\nFor detailed pack authoring guide, schema reference, and examples, see [ docs/custom-packs.md](/Dicklesworthstone/destructive_command_guard/blob/main/docs/custom-packs.md).\n\nValidate your pack before deployment:\n\n```\ndcg pack validate mypack.yaml\n```\n\nHeredoc scanning configuration:\n\n```\n[heredoc]\n# Enable scanning for heredocs and inline scripts (python -c, bash -c, etc.).\nenabled = true\n\n# Extraction timeout budget (milliseconds).\ntimeout_ms = 50\n\n# Resource limits for extracted bodies.\nmax_body_bytes = 1048576\nmax_body_lines = 10000\nmax_heredocs = 10\n\n# Optional language filter (scan only these languages). Omit for \"all\".\n# languages = [\"python\", \"bash\", \"javascript\", \"typescript\", \"ruby\", \"perl\", \"go\"]\n\n# Graceful degradation (hook defaults are fail-open).\nfallback_on_parse_error = true\nfallback_on_timeout = true\n```\n\nCLI overrides for heredoc scanning:\n\n`--heredoc-scan`\n\n/`--no-heredoc-scan`\n\n`--heredoc-timeout <ms>`\n\n`--heredoc-languages <lang1,lang2,...>`\n\nHeredoc documentation:\n\n`docs/adr-001-heredoc-scanning.md`\n\n(architecture and rationale)`docs/patterns.md`\n\n(pattern authoring + inventory)`docs/security.md`\n\n(threat model and incident response)\n\nHeredoc and inline script scanning uses a three-tier pipeline designed for performance and accuracy:\n\n```\nCommand Input\n     │\n     ▼\n┌─────────────────┐\n│ Tier 1: Trigger │ ─── No match ──► ALLOW (fast path, <100μs)\n│   (RegexSet)    │\n└────────┬────────┘\n         │ Match\n         ▼\n┌─────────────────┐\n│ Tier 2: Extract │ ─── Error/Timeout ──► ALLOW + fallback check\n│   (<1ms)        │\n└────────┬────────┘\n         │ Success\n         ▼\n┌─────────────────┐\n│ Tier 3: AST     │ ─── No match ──► ALLOW\n│   (<5ms)        │ ─── Match ──► BLOCK\n└─────────────────┘\n```\n\n**Tier 1: Trigger Detection** (<100μs)\n\nUltra-fast regex screening to detect heredoc indicators. Uses a compiled `RegexSet`\n\nfor O(n) matching against all trigger patterns simultaneously:\n\n```\nstatic HEREDOC_TRIGGERS: LazyLock<RegexSet> = LazyLock::new(|| {\n    RegexSet::new([\n        r\"<<-?\\s*(?:['\\x22][^'\\x22]*['\\x22]|[\\w.-]+)\",  // Heredocs\n        r\"<<<\",                                          // Here-strings\n        r\"\\bpython[0-9.]*\\b.*\\s+-[A-Za-z]*[ce]\",        // python -c/-e\n        r\"\\bruby[0-9.]*\\b.*\\s+-[A-Za-z]*e\",             // ruby -e\n        r\"\\bnode(js)?[0-9.]*\\b.*\\s+-[A-Za-z]*[ep]\",     // node -e/-p\n        r\"\\b(sh|bash|zsh)\\b.*\\s+-[A-Za-z]*c\",           // bash -c\n        // ... more patterns\n    ])\n});\n```\n\nCommands without any trigger patterns skip directly to ALLOW—no further processing needed.\n\n**Tier 2: Content Extraction** (<1ms)\n\nFor commands that trigger, extract the actual content to be evaluated:\n\n**Heredocs**:`cat <<EOF ... EOF`\n\n→ extracts body between delimiters**Here-strings**:`cat <<< \"content\"`\n\n→ extracts quoted content**Inline scripts**:`python -c \"code\"`\n\n→ extracts the code argument\n\nExtraction is bounded by configurable limits:\n\n- Maximum body size (default: 1MB)\n- Maximum lines (default: 10,000)\n- Maximum heredocs per command (default: 10)\n- Timeout (default: 50ms)\n\n```\npub struct ExtractionLimits {\n    pub max_body_bytes: usize,\n    pub max_body_lines: usize,\n    pub max_heredocs: usize,\n    pub timeout_ms: u64,\n}\n```\n\n**Tier 3: AST Pattern Matching** (<5ms)\n\nExtracted content is parsed using language-specific AST grammars (via tree-sitter/ast-grep) and matched against structural patterns:\n\n``` js\n// Example: detect subprocess.run with shell=True and rm -rf\nlet pattern = r#\"\n    call_expression {\n        function: attribute { object: \"subprocess\" attr: \"run\" }\n        arguments: argument_list {\n            contains string { contains \"rm -rf\" }\n            contains keyword_argument { keyword: \"shell\" value: \"True\" }\n        }\n    }\n\"#;\n```\n\n**Recursive Shell Analysis**:\n\nWhen extracted content is itself a shell script (e.g., `bash -c \"git reset --hard\"`\n\n), Tier 3 recursively extracts inner commands and re-evaluates them through the full pipeline:\n\n``` js\nif content.language == ScriptLanguage::Bash {\n    let inner_commands = extract_shell_commands(&content.content);\n    for inner in inner_commands {\n        // Re-evaluate inner command against all packs\n        if let Some(result) = evaluate_command(&inner, ...) {\n            if result.decision == Deny {\n                return result; // Block the outer command\n            }\n        }\n    }\n}\n```\n\nIf you encounter commands that should be blocked, please file an issue.\n\nEnvironment variables override config files (highest priority):\n\n`DCG_PACKS=\"containers.docker,kubernetes\"`\n\n: enable packs (comma-separated)`DCG_DISABLE=\"kubernetes.helm\"`\n\n: disable packs/sub-packs (comma-separated)`DCG_VERBOSE=0-3`\n\n: verbosity level (0 = quiet, 3 = trace)`DCG_QUIET=1`\n\n: suppress non-error output`DCG_COLOR=auto|always|never`\n\n: color mode`DCG_NO_RICH=1`\n\n: disable rich terminal formatting and use plain rendering`DCG_NO_COLOR=1`\n\n: disable colored output (same as NO_COLOR)`DCG_LEGACY_OUTPUT=1`\n\n: force plain output paths (same as`--legacy-output`\n\n)`DCG_ROBOT=1`\n\n: enable robot mode for JSON stdout and quiet stderr`DCG_HIGH_CONTRAST=1`\n\n: enable high-contrast output (ASCII borders + monochrome palette)`DCG_FORMAT=text|json|sarif`\n\n: default output format (command-specific — see[Output Formats](#output-formats-and-dcg_format)for which values each subcommand actually accepts; real SARIF is`dcg scan`\n\n-only)`DCG_FAIL_CLOSED=1`\n\n: block (deny) on hook input that cannot be parsed, instead of the default fail-open allow (opt-in; see[Fail-Open Philosophy](#fail-open-philosophy))`DCG_BYPASS=1`\n\n: bypass dcg entirely (escape hatch; use sparingly)`DCG_CONFIG=/path/to/config.toml`\n\n: use explicit config file`DCG_HEREDOC_ENABLED=true|false`\n\n: enable/disable heredoc scanning`DCG_HEREDOC_TIMEOUT=50`\n\n: heredoc extraction timeout (milliseconds)`DCG_HEREDOC_TIMEOUT_MS=50`\n\n: heredoc extraction timeout (milliseconds)`DCG_HEREDOC_LANGUAGES=python,bash`\n\n: filter heredoc languages`DCG_POLICY_DEFAULT_MODE=deny|warn|log`\n\n: global default decision mode`DCG_HOOK_TIMEOUT_MS=200`\n\n: hook evaluation timeout budget (milliseconds)\n\n`--format`\n\n(and the `DCG_FORMAT`\n\nenv var, which seeds the default) is\n**command-specific**: each subcommand accepts only its own set of values, and an\nunrecognized value is a usage error (exit 2). `DCG_FORMAT`\n\napplies wherever a\ncommand has a `--format`\n\nflag and is silently ignored by commands that don't.\n\n| Command | Accepted `--format` values |\nNotes |\n|---|---|---|\n`dcg scan` |\n`pretty` , `json` , `markdown` , `sarif` |\nOnly command that emits real SARIF 2.1.0 |\n`dcg test` |\n`pretty` (alias `text` ), `json` (aliases `sarif` , `structured` ), `toon` |\n|\n`dcg config` |\n`pretty` (alias `text` ), `json` (alias `sarif` ) |\n|\n`dcg packs` |\n`pretty` (alias `text` ), `json` (alias `sarif` ) |\n|\n`dcg explain` |\n`pretty` , `json` (alias `sarif` ) |\n|\n`dcg doctor` |\n`pretty` , `json` (alias `sarif` ) |\n|\n`dcg simulate` |\n`pretty` , `json` (alias `sarif` ) |\n|\n`dcg corpus` |\n`json` , `pretty` (alias `sarif` ) |\n|\n`dcg suggest-allowlist` |\n`text` , `json` (alias `sarif` ) |\n\n** sarif is a JSON alias on every command except dcg scan.** This is\ndeliberate so that setting\n\n`DCG_FORMAT=sarif`\n\nglobally degrades gracefully —\n`dcg scan`\n\nproduces a real SARIF report while other commands fall back to their\nstructured JSON rather than erroring. If you need machine-readable output from a\nnon-scan command, prefer `--format json`\n\n(which is unambiguous); use `dcg scan --format sarif`\n\nfor SARIF. `--robot`\n\nforces JSON regardless of `--format`\n\n.dcg supports layered configuration from multiple sources, with higher-priority sources overriding lower ones:\n\n- Environment Variables (DCG_* prefix) [HIGHEST PRIORITY]\n- Explicit Config File (DCG_CONFIG env var)\n- Project Config (.dcg.toml in repo root)\n- User Config (~/.config/dcg/config.toml)\n- System Config (/etc/dcg/config.toml)\n- Compiled Defaults [LOWEST PRIORITY]\n\ndcg supports colorblind-safe palettes and high-contrast output. Colors are always paired with symbols/labels to avoid conveying meaning by color alone.\n\n```\n[output]\nhigh_contrast = true       # ASCII borders + black/white palette\n\n[theme]\npalette = \"colorblind\"     # default | colorblind | high-contrast\nuse_unicode = true         # false for ASCII-only\nuse_color = true           # false for monochrome\n```\n\n**Configuration File Locations**:\n\n| Level | Path | Use Case |\n|---|---|---|\n| System | `/etc/dcg/config.toml` |\nOrganization-wide defaults |\n| User | `~/.config/dcg/config.toml` |\nPersonal preferences |\n| Project | `.dcg.toml` (repo root) |\nProject-specific settings |\n| Explicit | `DCG_CONFIG=/path/to/file` |\nTesting or override |\n\n**Merging Behavior**:\n\nConfiguration layers are merged additively, with higher-priority sources overriding specific fields:\n\n```\n// Only fields explicitly set in higher-priority configs override\n// Missing fields retain values from lower-priority sources\nfn merge_layer(&mut self, other: ConfigLayer) {\n    if let Some(verbose) = other.general.verbose {\n        self.general.verbose = verbose;  // Override if present\n    }\n    // Unset fields retain previous values\n}\n```\n\nThis means you can set organization defaults in `/etc/dcg/config.toml`\n\n, personal preferences in `~/.config/dcg/config.toml`\n\n, and project-specific overrides in `.dcg.toml`\n\n—each layer only needs to specify the settings that differ from defaults.\n\n**Project-Specific Pack Configuration**:\n\nThe `[projects]`\n\nsection allows different pack configurations for different repositories:\n\n```\n[projects.\"/home/user/work/production-api\"]\npacks = { enabled = [\"database.postgresql\", \"cloud.aws\"], disabled = [] }\n\n[projects.\"/home/user/personal/experiments\"]\npacks = { enabled = [], disabled = [\"core.git\"] }  # More permissive for experiments\n```\n\ndcg 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.\n\n**Why Fail-Open?**\n\n**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\n\n**Fail-Open Scenarios**:\n\n| Scenario | Behavior | Rationale |\n|---|---|---|\n| Parse error in heredoc | ALLOW + warn | Malformed input shouldn't block work |\n| Extraction timeout | ALLOW + warn | Slow inputs shouldn't hang terminal |\n| Size limit exceeded | ALLOW + fallback check | Large inputs get reduced analysis |\n| Regex engine timeout | ALLOW + warn | Pathological patterns shouldn't block |\n| AST matching error | Skip that heredoc | Continue evaluating other content |\n| Deadline exceeded | ALLOW immediately | Hard cap prevents runaway processing |\n\n**Configurable Strictness**:\n\nFor high-security environments, fail-open can be disabled.\n\nFor **heredoc/inline-script** analysis specifically:\n\n```\n[heredoc]\nfallback_on_parse_error = false  # Block on heredoc parse errors\nfallback_on_timeout = false      # Block on heredoc timeouts\n```\n\nFor the **top-level hook input** (the JSON dcg reads from stdin), enable\nfail-closed mode so that input which cannot be parsed at all is **blocked**\ninstead of allowed:\n\n```\n[general]\nfail_closed = true   # Deny when the hook input itself is unparseable\n```\n\nor at runtime:\n\n``` js\nDCG_FAIL_CLOSED=1   # env var overrides the config value\n```\n\nThe default is **fail-open** (unparseable input is allowed) and is unchanged\nunless you opt in. With fail-closed enabled, a genuinely unparseable hook\npayload produces a deny (a `permissionDecision: deny`\n\nfor Claude-style hooks; a\n`\"decision\":\"deny\"`\n\nline plus a non-zero exit for `dcg hook --batch`\n\n).\nTransient IO read errors still fail open even in this mode, since they are not\nattacker-controlled malformed payloads.\n\nA leading UTF-8 BOM (\n\n`EF BB BF`\n\n) 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\".\n\nWith strict mode enabled, dcg will block commands when analysis fails, providing detailed error messages explaining why.\n\n**Fallback Pattern Checking**:\n\nEven when full analysis is skipped, dcg performs a lightweight fallback check for critical destructive patterns:\n\n```\nstatic FALLBACK_PATTERNS: LazyLock<RegexSet> = LazyLock::new(|| {\n    RegexSet::new([\n        r\"shutil\\.rmtree\",\n        r\"os\\.remove\",\n        r\"fs\\.rmSync\",\n        r\"\\brm\\s+-[a-zA-Z]*r[a-zA-Z]*f\",\n        r\"\\bgit\\s+reset\\s+--hard\\b\",\n        // ... other critical patterns\n    ])\n});\n```\n\nThis ensures that even oversized or malformed inputs are checked for the most dangerous operations before being allowed.\n\n**Absolute Timeout**:\n\nTo 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.\n\nThe easiest way to install is using the install script, which downloads a prebuilt binary for your platform:\n\n```\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash -s -- --easy-mode\n```\n\nEasy 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`\n\nBash hook into `~/.codex/hooks.json`\n\n; invalid JSON or malformed existing Codex hook shapes are left unchanged and reported instead of being overwritten.\n\n**Other options:**\n\nInteractive mode (prompts for each step):\n\n```\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash\n```\n\nInstall specific version:\n\n```\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash -s -- --version v0.5.0\n```\n\nInstall to /usr/local/bin (system-wide, requires sudo):\n\n```\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | sudo bash -s -- --system\n```\n\nBuild from source instead of downloading binary:\n\n```\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash -s -- --from-source\n```\n\nDownload/install only (skip agent hook configuration):\n\n```\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash -s -- --no-configure\n```\n\nNote:If you have[gum]installed, the installer will use it for fancy terminal formatting.\n\nThe 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`\n\n) if present.\n\n## Agent-specific notes\n\n**Aider:** No PreToolUse-style interception. The installer enables`git-commit-verify: true`\n\nin`~/.aider.conf.yml`\n\nso git hooks run. For full protection, install dcg as a[git pre-commit hook](/Dicklesworthstone/destructive_command_guard/blob/main/docs/scan-precommit-guide.md).**Continue:** No shell command interception hooks. The installer detects Continue but cannot auto-configure protection. Use a[git pre-commit hook](/Dicklesworthstone/destructive_command_guard/blob/main/docs/scan-precommit-guide.md)instead.**Codex CLI:** PreToolUse hooks via`~/.codex/hooks.json`\n\n(stable in Codex 0.125.0+; the`codex_hooks`\n\nfeature is on by default). dcg detects Codex from the`turn_id`\n\nstdin field and emits the minimal documented`hookSpecificOutput`\n\ndeny JSON with exit code 0; dcg-only metadata is omitted so Codex's strict parser accepts the decision. The Unix installer and`install.ps1`\n\nboth 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`\n\nUI once to trust the hook.`uninstall.sh`\n\nand`uninstall.ps1`\n\nremove only dcg-owned Codex hooks and preserve coexisting entries. See the[Codex integration notes](/Dicklesworthstone/destructive_command_guard/blob/main/docs/codex-integration.md). Caveats: the model can still write scripts to disk to bypass hook-based blocking; and Codex's`PreToolUse`\n\nhooks[do not yet intercept every](/Dicklesworthstone/destructive_command_guard/blob/main/docs/codex-integration.md#known-limitation-codex-unified_exec-path-windows-desktop--cli), so treat it as a guardrail rather than a complete enforcement boundary.`unified_exec`\n\nshell path**GitHub Copilot CLI:** The installer writes a user-level hook to`${COPILOT_HOME:-~/.copilot}/hooks/dcg.json`\n\n, protecting every workspace. The generated`preToolUse`\n\nhook covers both Unix`bash`\n\nand Windows`powershell`\n\npayloads and emits Copilot's exact top-level permission-decision JSON.**VS Code Copilot Chat:** Current VS Code releases load`~/.claude/settings.json`\n\nby 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 documented`runTerminalCommand`\n\nshell tool plus the observed compatibility names`run_in_terminal`\n\nand`runInTerminal`\n\n, reads`tool_input.command`\n\n, and returns VS Code's documented`hookSpecificOutput`\n\ndeny. Agent hooks are still a VS Code preview feature and can be disabled by organization policy; use**Developer: Show Agent Debug Logs** or the**GitHub Copilot Chat Hooks** output channel to confirm that the hook loaded.**Cursor IDE:** Hooks are configured through`~/.cursor/hooks.json`\n\nplus a generated bridge (`dcg-pre-shell.ps1`\n\non Windows). The installer inserts dcg first in`beforeShellExecution`\n\n, collapses duplicate dcg entries, and preserves coexisting Cursor hooks.**Hermes Agent:**[NousResearch's Hermes Agent](https://github.com/NousResearch/hermes-agent)declares shell hooks in`~/.hermes/config.yaml`\n\nunder`hooks.pre_tool_call`\n\n. The installer merges a single`matcher: \"terminal\"`\n\nentry that invokes dcg directly — no wrapper script — because Hermes' input JSON (`hook_event_name: \"pre_tool_call\"`\n\n,`tool_name: \"terminal\"`\n\n,`tool_input.command`\n\n) deserializes straight into dcg's existing`HookInput`\n\n. Hermes[explicitly documents](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/hooks.md)that \"non-zero exit codes... never abort the agent loop\", so dcg switches to Hermes' JSON block protocol on output:`{\"decision\":\"block\",\"reason\":...}`\n\n(plus the alternate`{\"action\":\"block\",\"message\":...}`\n\nform for cross-version compatibility). The installer also sets`hooks_auto_accept: true`\n\nif not already set; Hermes silently drops un-allowlisted hooks in non-TTY runs (gateway/cron) without it.`unconfigure_hermes`\n\nin`uninstall.sh`\n\nremoves only the dcg-owned entry and leaves`hooks_auto_accept`\n\nalone (other Hermes hooks may rely on it).**Grok (xAI):**[Grok Build / Grok CLI](https://x.ai/news/grok-build-cli)auto-discovers every`*.json`\n\nunder`~/.grok/hooks/`\n\n.`dcg install --grok`\n\nwrites a self-contained`~/.grok/hooks/dcg.json`\n\nwith a`PreToolUse`\n\n/`matcher: \"Bash\"`\n\nentry — Grok internally aliases Claude-style`\"Bash\"`\n\nto its own`run_terminal_cmd`\n\ntool, so a single rule covers every shell command. dcg detects Grok at runtime from the camelCase wire shape (`hookEventName: \"pre_tool_use\"`\n\n,`toolName: \"run_terminal_cmd\"`\n\n) or from the`GROK_SESSION_ID`\n\n/`GROK_HOOK_EVENT`\n\n/`GROK_WORKSPACE_ROOT`\n\nenvironment variables, and switches its output to Grok's JSON contract:`{\"decision\":\"deny\",\"reason\":...}`\n\n(note`\"deny\"`\n\n, not Hermes'`\"block\"`\n\n). Grok also picks up dcg automatically through its`~/.claude/settings.json`\n\ncompatibility layer, so existing Claude Code users get protection with no additional install step. Add`--project`\n\nto write`<repo>/.grok/hooks/dcg.json`\n\nfor a per-repo install (Grok requires`/hooks-trust`\n\nthe first time it opens a repo with hooks).**Antigravity CLI (**`agy`\n\n):[Google Antigravity's](https://antigravity.google)ships a Claude-Code-compatible hooks system.`agy`\n\nCLI`dcg install --agy`\n\nmerges a`PreToolUse`\n\n/`matcher: \"Bash\"`\n\nentry into`~/.gemini/config/hooks.json`\n\n(the canonical path;`agy`\n\nmigrates the legacy`~/.gemini/antigravity-cli/hooks.json`\n\nhere and symlinks the old path to it).`agy`\n\nruns the hook before its`run_command`\n\nshell tool; dcg detects`agy`\n\nat runtime from the distinctive nested`toolCall`\n\nenvelope (`{\"toolCall\":{\"name\":\"run_command\",\"args\":{\"CommandLine\":\"…\"}},\"conversationId\":…,\"stepIdx\":…}`\n\n) — the shell command is read from`toolCall.args.CommandLine`\n\n— or from the`ANTIGRAVITY_CONVERSATION_ID`\n\nenvironment variable /`agy`\n\nparent-process name. dcg switches its output to`agy`\n\n's JSON contract:`{\"decision\":\"block\",\"reason\":…}`\n\nwith exit code 0 (verified:`agy`\n\nhonors both`\"block\"`\n\nand`\"deny\"`\n\nand 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`\n\nto write`<repo>/.gemini/config/hooks.json`\n\nfor a per-repo install. Restart`agy`\n\n(start a new session) after installing.**OpenCode:** Not auto-configured. Requires a Bun-based plugin with`\"tool.execute.before\"`\n\nhook key. A working community plugin:[aspiers/ai-config/dcg-guard.js](https://github.com/aspiers/ai-config/blob/main/.config/opencode/plugins/dcg-guard.js).**Pi:** Not auto-configured.[Pi](https://github.com/earendil-works/pi)intercepts shell commands through user-authored TypeScript extensions (`pi.on(\"tool_call\", …)`\n\n, auto-loaded from`~/.pi/agent/extensions/*.ts`\n\nor`<repo>/.pi/extensions/*.ts`\n\n). A ready-to-use`dcg-guard.ts`\n\nextension that routes each`bash`\n\ncommand through`dcg --robot test`\n\n(exit 1 = deny) and blocks with the dcg reason is documented in[docs/pi-integration.md](/Dicklesworthstone/destructive_command_guard/blob/main/docs/pi-integration.md).\n\nRecommended:After installing, run`dcg setup`\n\nto add a[shell startup check]that warns you if the dcg hook is ever silently removed from`~/.claude/settings.json`\n\n.\n\nThis project uses Rust Edition 2024 features and requires the nightly toolchain. The repository includes a `rust-toolchain.toml`\n\nthat automatically selects the correct toolchain.\n\n```\n# Install Rust nightly if you don't have it\nrustup install nightly\n\n# Install directly from GitHub\ncargo +nightly install --git https://github.com/Dicklesworthstone/destructive_command_guard destructive_command_guard\ngit clone https://github.com/Dicklesworthstone/destructive_command_guard\ncd destructive_command_guard\n# rust-toolchain.toml automatically selects nightly\ncargo build --release\ncp target/release/dcg ~/.local/bin/\n```\n\nRun the built-in updater to re-run the installer for your platform:\n\n```\ndcg update\n```\n\nOptional flags mirror the installer scripts (examples):\n\n```\ndcg update --version v0.2.7\ndcg update --system\ndcg update --verify\n```\n\nYou can always re-run `install.sh`\n\n/ `install.ps1`\n\ndirectly if preferred.\n\nPrebuilt binaries are available for:\n\n- Linux x86_64 (\n`x86_64-unknown-linux-gnu`\n\n) - Linux ARM64 (\n`aarch64-unknown-linux-gnu`\n\n) - macOS Intel (\n`x86_64-apple-darwin`\n\n) - macOS Apple Silicon (\n`aarch64-apple-darwin`\n\n) - Windows x64 (\n`x86_64-pc-windows-msvc`\n\n) - Windows ARM64 (\n`aarch64-pc-windows-msvc`\n\n)\n\nDownload from [GitHub Releases](https://github.com/Dicklesworthstone/destructive_command_guard/releases) and verify the SHA256 checksum.\nIf you have cosign installed, each release also includes a Sigstore bundle (`.sigstore.json`\n\n) so you can verify provenance with `cosign verify-blob`\n\n.\n\nRemove dcg and all its hooks from AI agents:\n\n```\ncurl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/uninstall.sh | bash\n```\n\nOn Windows:\n\n```\nirm https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/uninstall.ps1 | iex\n```\n\nThe Unix uninstaller:\n\n- 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\n- Removes the dcg binary\n- Removes configuration (\n`~/.config/dcg/`\n\n) and history (`~/.local/share/dcg/`\n\n) - Prompts for confirmation before making changes\n\nThe PowerShell uninstaller removes the Windows `dcg.exe`\n\nbinary, the exact User PATH entry added by `install.ps1`\n\n, dcg hooks from Claude Code, Codex CLI, Gemini CLI, GitHub Copilot CLI, Cursor IDE, Hermes Agent, Grok, and Antigravity (`agy`\n\n), plus dcg configuration/history directories.\n\nOptions:\n\n`--yes`\n\n- Skip confirmation prompt`--keep-config`\n\n- Preserve configuration files`--keep-history`\n\n- Preserve history database`--purge`\n\n- Remove everything (overrides keep flags)\n\nAdd to `~/.claude/settings.json`\n\n:\n\n```\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"dcg\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Important:** Restart Claude Code after adding the hook configuration.\n\nCodex CLI 0.125.0+ supports stable `PreToolUse`\n\nhooks. The installer writes or\nmerges this automatically, but the manual configuration lives at\n`~/.codex/hooks.json`\n\n:\n\n```\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"dcg\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\nCodex denials intentionally omit dcg's extended Claude-only fields: dcg exits 0\nwith the minimal documented `hookSpecificOutput`\n\nJSON on stdout. Allowed\ncommands stay silent with exit code 0.\n\nAdd to `~/.gemini/settings.json`\n\n:\n\n```\n{\n  \"hooks\": {\n    \"BeforeTool\": [\n      {\n        \"matcher\": \"run_shell_command\",\n        \"hooks\": [\n          {\n            \"name\": \"dcg\",\n            \"type\": \"command\",\n            \"command\": \"dcg\",\n            \"timeout\": 5000\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Important:** Restart Gemini CLI after adding the hook configuration.\n\nWhile primarily designed as a hook, the binary supports direct invocation for testing, debugging, and understanding why commands are blocked or allowed.\n\n```\n# Show version with build metadata\ndcg --version\n\n# Show help with blocked command categories\ndcg --help\n\n# Test a command manually (pipe JSON to stdin)\necho '{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"git reset --hard\"}}' | dcg\n```\n\nUse `dcg test`\n\nto evaluate a command **without executing it**. This is useful for CI checks, false-positive debugging, and config validation before rollout.\n\n```\n# Basic evaluation (human-readable output)\ndcg test \"rm -rf ./build\"\n\n# Structured output for automation\ndcg test --format json \"kubectl delete namespace prod\" | jq -r .decision\n\n# Use a specific config file\ndcg test --config .dcg.prod.toml \"docker system prune\"\n\n# Temporarily enable extra packs only for this test run\ndcg test --with-packs containers.docker,database.postgresql \"docker system prune\"\n\n# Print full evaluation trace (same engine as `dcg explain`)\ndcg test --explain \"git reset --hard\"\n```\n\n`0`\n\n: command would be allowed`1`\n\n: command would be blocked\n\n`-c, --config <PATH>`\n\n: use a specific config file`--with-packs <ID1,ID2>`\n\n: temporarily enable extra packs`--explain`\n\n: print detailed decision trace`-f, --format <pretty|json|toon>`\n\n: output format (default:`pretty`\n\n)`--no-color`\n\n: disable ANSI color output`--heredoc-scan`\n\n: force-enable heredoc/inline-script scanning`--no-heredoc-scan`\n\n: force-disable heredoc/inline-script scanning`--heredoc-timeout <MS>`\n\n: override heredoc extraction timeout budget`--heredoc-languages <LANG1,LANG2>`\n\n: limit heredoc AST scanning languages\n\n`pretty`\n\n: human-readable output with command context, matched rule info, and suggestions`json`\n\n: structured payload for scripts/CI; includes metadata like`schema_version`\n\n,`dcg_version`\n\n,`command`\n\n,`decision`\n\n, rule/pack fields, and allowlist/agent context when present`toon`\n\n: token-efficient structured encoding of the same payload used by`json`\n\n(useful for agent-to-agent/tool pipelines)\n\nFail fast in shell pipelines:\n\n```\ndcg test --format json \"rm -rf /\" > /tmp/dcg.json\njq -e '.decision == \"allow\"' /tmp/dcg.json\n```\n\nMinimal GitHub Actions step:\n\n```\n- name: Validate dangerous command policy\n  run: |\n    ~/.local/bin/dcg test --format json \"git reset --hard HEAD~1\" > /tmp/dcg-test.json\n    jq -e '.decision == \"allow\"' /tmp/dcg-test.json\n```\n\n- Use\n`--format json`\n\n(or`DCG_FORMAT=json`\n\n) for machine parsing. - Add\n`--no-color`\n\nif logs or parsers choke on ANSI output. - If results differ between environments, check config precedence (\n`DCG_CONFIG`\n\n, project`.dcg.toml`\n\n, user/system config). - If a command is unexpectedly allowed, inspect active allowlists (\n`dcg allowlist list`\n\n) and enabled packs (`dcg packs --verbose`\n\n). - For full decision traces, run\n`dcg test --explain \"<command>\"`\n\n(or`dcg explain \"<command>\"`\n\n).\n\nWhen you need to understand exactly why a command was blocked (or allowed), the `dcg explain`\n\ncommand provides a detailed trace of the decision-making process:\n\n```\n# Explain why a command is blocked\ndcg explain \"git reset --hard HEAD\"\n\n# Explain a safe command\ndcg explain \"git status\"\n\n# Explain with verbose timing information\ndcg explain --verbose \"rm -rf /tmp/build\"\n\n# Output as JSON for programmatic use\ndcg explain --format json \"kubectl delete namespace production\"\n```\n\nJSON output is versioned via `schema_version`\n\n(currently 2). v2 adds\n`matched_span`\n\n, `matched_text_preview`\n\n, and `explanation`\n\nin the `match`\n\nobject when a pattern is detected.\n\n**Example Output**:\n\n```\nCommand: git reset --hard HEAD\nNormalized: git reset --hard HEAD\n\nDecision: BLOCKED\n  Pack: core.git\n  Rule: reset-hard\n  Reason: git reset --hard destroys uncommitted changes\n\nEvaluation Trace:\n  [  0.8μs] Quick reject: passed (contains 'git')\n  [  2.1μs] Normalize: no changes\n  [  5.3μs] Safe patterns: no match (checked 34 patterns)\n  [ 12.7μs] Destructive patterns: MATCH at pattern 'reset-hard'\n  [ 12.9μs] Total time: 12.9μs\n\nSuggestion: Consider using 'git stash' first to save your changes.\n```\n\nThe explain mode shows:\n\n**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\n\nThis is invaluable for debugging false positives, understanding pack coverage, and verifying that custom allowlist entries work as expected.\n\nSometimes you need to run a blocked command temporarily without permanently modifying your allowlist. The allow-once system provides short codes:\n\n```\n# When a command is blocked, dcg outputs a short code\n# BLOCKED: git reset --hard HEAD\n# Allow-once code: 123456\n# To allow this: dcg allow-once 123456\n\n# Use the short code to create a temporary exception\ndcg allow-once 123456\n\n# Or, use --single-use to make the exception one-shot\ndcg allow-once 123456 --single-use\n```\n\n**How Allow-Once Works**:\n\n- When dcg blocks a command, it generates a short code (currently 6 numeric digits; collisions are handled via\n`--pick`\n\n/`--hash`\n\n) - The code is tied to the exact command that was blocked\n- Running\n`dcg allow-once <code>`\n\ncreates a temporary exception - The exception is stored in\n`~/.config/dcg/pending_exceptions.jsonl`\n\n- Exceptions expire after 24 hours (or after first use if\n`--single-use`\n\nis used) - While active, the exception allows the same command in the same directory scope\n\nThis workflow is useful for:\n\n- One-time administrative operations that are intentionally destructive\n- Migration scripts that need to reset state\n- Emergency fixes where permanent allowlist changes aren't appropriate\n\n**Security Considerations**:\n\n- Short codes are derived from SHA256 (or optional HMAC-SHA256 when\n`DCG_ALLOW_ONCE_SECRET`\n\nis set) - Codes are never logged or transmitted\n- The pending exceptions file is readable only by the current user\n- Expired codes are automatically cleaned up\n\nAI coding agents routinely get stuck when `git pull --rebase`\n\nfails partway — unstaged-changes errors, stash-pop conflicts, interrupted rebases. The documented recovery path is almost always `git checkout -- .`\n\nor `git restore <paths>`\n\n, both of which dcg hard-blocks (`core.git:checkout-discard`\n\n, `core.git:restore-worktree`\n\n). Agents then have to stop and ask a human to run the command manually.\n\nRebase-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.\n\n**Two complementary signals unlock recovery:**\n\n-\n**Active rebase state (automatic, zero-config).** When`.git/rebase-merge/`\n\nor`.git/rebase-apply/`\n\nexists, a rebase is in progress and the discard operations*are*the documented recovery path. dcg detects this state and converts the deny into an allow with a`[dcg] Allowing ... → rebase-recovery mode`\n\nnote on stderr. No permit needed. -\n**Explicit permit cookie (opt-in, short-lived).** When the rebase already finished but the worktree is still messy (e.g. after a bad`git stash pop`\n\n), run:\n\n```\ndcg rebase-recover            # default ttl: 120s\ndcg rebase-recover --ttl 60   # custom ttl (max: 600s)\n```\n\nThis writes a timestamp to\n\n`.dcg/rebase-recovery-permit`\n\nat the repo root. For the next N seconds (or until the first matching allow, whichever comes first),`git checkout -- <path>`\n\nand`git restore <paths>`\n\nare allowed. The permit is**single-shot**— one successful allow consumes it — so it can't silently unblock later unrelated commands within the TTL.\n\n**Scope and safety guarantees:**\n\n- Only four rules participate:\n`core.git:checkout-discard`\n\n,`core.git:checkout-ref-discard`\n\n,`core.git:restore-worktree`\n\n,`core.git:restore-worktree-explicit`\n\n. **Nothing else is affected.**`git reset --hard`\n\n,`git clean -f`\n\n,`git push --force`\n\n, etc. stay blocked even during an active rebase or with a permit active.- The permit is scoped to the current repo's\n`.dcg/`\n\ndirectory. It does not cross repos. - Expired permits are auto-cleaned on the next check.\n\n**Typical recovery flow:**\n\n``` bash\n$ git pull --rebase\n# ... fails with \"unstaged changes\" ...\n$ git stash\n$ git pull --rebase        # succeeds\n$ git stash pop            # leaves messy worktree\n$ git checkout -- .\nBLOCKED by dcg  (core.git:checkout-discard)\n  ... Recovering from a failed `git pull --rebase`?\n  ... Run `dcg rebase-recover` in this repo, then retry the command.\n$ dcg rebase-recover\ndcg rebase-recovery permit issued ...\n$ git checkout -- .        # now allowed, permit consumed\n$ git push\n```\n\nSee issue [#104](https://github.com/Dicklesworthstone/destructive_command_guard/issues/104) for background.\n\nThe `--version`\n\noutput includes build metadata for debugging:\n\n```\ndcg 0.1.0\n  Built: 2026-01-07T22:13:10.413872881Z\n  Rustc: 1.94.0-nightly\n  Target: x86_64-unknown-linux-gnu\n```\n\nThis metadata is embedded at compile time via [vergen](https://github.com/rustyhorde/vergen), making it easy to identify exactly which build is running when troubleshooting.\n\nWhile the hook protects **interactive** command execution, teams also need protection against destructive commands that get **committed into repositories**. The `dcg scan`\n\ncommand extracts executable command contexts from files and evaluates them using the same pattern engine.\n\n**What it is:**\n\n- An extractor-based scanner that understands executable contexts\n- Uses the same evaluator as hook mode for consistency\n- Supports CI integration and pre-commit hooks\n\n**What it is NOT:**\n\n- A naive grep that matches strings everywhere\n- A replacement for code review\n- A static analysis tool for arbitrary languages\n\nThe key difference from grep: `dcg scan`\n\nunderstands that `\"rm -rf /\"`\n\nin 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.\n\ndcg scan includes specialized extractors for each file format, understanding which parts contain executable commands:\n\n| File Type | Detection | Executable Contexts |\n|---|---|---|\nShell Scripts |\n`*.sh` , `*.bash` , `*.zsh` , `*.dash` , `*.ksh` |\nNon-comment executable command lines |\nDockerfile |\n`Dockerfile` , `Dockerfile.*` , `*.dockerfile` |\n`RUN` instructions (shell and exec forms) |\nGitHub Actions |\n`.github/workflows/*.yml` , `.github/workflows/*.yaml` |\n`run:` fields in steps |\nGitLab CI |\n`.gitlab-ci.yml` , `*.gitlab-ci.yml` |\n`script:` , `before_script:` , `after_script:` |\nAzure Pipelines |\n`azure-pipelines.yml` , `azure-pipelines.yaml` , `azure-pipelines-*.yml` , `azure-pipelines-*.yaml` |\n`script:` , `bash:` , `powershell:` , `pwsh:` tasks |\nCircleCI |\n`.circleci/config.yml` , `.circleci/config.yaml` |\n`run:` steps and nested `command:` fields |\nMakefile |\n`Makefile` |\nTab-indented recipe lines |\npackage.json |\n`package.json` |\n`scripts` object values |\nTerraform |\n`*.tf` |\n`provisioner` blocks (`local-exec` , `remote-exec` ) |\nDocker Compose |\n`docker-compose.yml` , `docker-compose.yaml` , `compose.yml` , `compose.yaml` |\n`command:` , `entrypoint:` , `healthcheck.test:` fields |\nPowerShell |\n`*.ps1` , `*.psm1` , `*.psd1` |\nExecutable statements with line and block comments excluded |\nBatch Scripts |\n`*.cmd` , `*.bat` |\nExecutable command lines with comments excluded |\n\n**Context-Aware Extraction**:\n\nEach extractor understands its format's semantics:\n\n```\n# GitHub Actions - only 'run:' is extracted\n- name: Build\n  run: |                    # ← Extracted\n    npm install\n    npm run build\n  env:\n    NODE_ENV: production    # ← Skipped (not executable)\n# Dockerfile - only RUN instructions\nFROM node:18\nCOPY . /app                 # ← Skipped\nRUN npm install             # ← Extracted\nRUN [\"node\", \"server.js\"]   # ← Extracted (exec form)\nENV PORT=3000               # ← Skipped\n# Makefile - tab-indented lines under targets\nbuild:\n\tnpm install             # ← Extracted (recipe line)\n\tnpm run build           # ← Extracted\nSOURCES = $(wildcard *.js)  # ← Skipped (variable assignment)\n```\n\n**Non-Executable Context Filtering**:\n\nExtractors intelligently skip data-only sections:\n\n**Shell**: Assignment-only lines (`export VAR=value`\n\n)**YAML**:`environment:`\n\n,`labels:`\n\n,`volumes:`\n\n,`variables:`\n\nblocks**Terraform**: Everything outside`provisioner`\n\nblocks**All formats**: Comments (format-appropriate:`#`\n\n,`//`\n\n, etc.)\n\n```\n# Install the pre-commit hook\ndcg scan install-pre-commit\n\n# Or manually run on staged files\ndcg scan --staged\n\n# Scan specific paths\ndcg scan --paths scripts/ .github/workflows/\n```\n\n**Start conservative to avoid developer friction:**\n\n```\n# Week 1-2: Warn-first with narrow scope\ndcg scan --staged --fail-on error  # Only fail on catastrophic rules\n```\n\nCreate `.dcg/hooks.toml`\n\nwith conservative defaults:\n\n```\n[scan]\nfail_on = \"error\"          # Only fail on high-confidence catastrophic rules\nformat = \"pretty\"          # Human-readable output\nredact = \"quoted\"          # Hide sensitive strings\ntruncate = 120             # Shorten long commands\n\n[scan.paths]\ninclude = [\n    \".github/workflows/**\",  # Start with CI configs\n    \"Dockerfile\",            # Container builds\n    \"Makefile\",              # Build scripts\n]\nexclude = [\n    \"target/**\",\n    \"node_modules/**\",\n    \"vendor/**\",\n]\n```\n\n**Gradual expansion:**\n\n**Week 1-2**: Start with workflows/Dockerfiles only,`--fail-on error`\n\n**Week 3-4**: Add Makefiles and shell scripts in`scripts/`\n\n**Month 2**: Add`--fail-on warning`\n\nafter reviewing findings**Ongoing**: Add new extractors as team confidence grows\n\n```\ndcg scan install-pre-commit\n```\n\nThis creates a `.git/hooks/pre-commit`\n\nthat runs `dcg scan --staged`\n\n.\n\nIf you prefer manual control or use a hook manager:\n\n``` bash\n#!/bin/bash\n# .git/hooks/pre-commit (or equivalent for your hook manager)\n\nset -e\n\n# Run dcg scan on staged files\ndcg scan --staged --fail-on error\n\n# Add other hooks below...\ndcg scan uninstall-pre-commit\n```\n\nThis only removes hooks installed by dcg (detected via sentinel comment).\n\nThe output includes:\n\n```\nscripts/deploy.sh:42:5: [ERROR] core.git:reset-hard\n  Command: git reset --hard HEAD\n  Reason: git reset --hard destroys uncommitted changes\n  Suggestion: Consider using 'git stash' first to save changes.\n```\n\n**File:Line:Col**: Location in the source file** Severity**:`ERROR`\n\n(catastrophic) or`WARNING`\n\n(concerning)**Rule ID**: Stable identifier like`core.git:reset-hard`\n\n**Command**: The extracted command (may be redacted/truncated)** Reason**: Why this command is flagged** Suggestion**: How to make it safer\n\nReplace the dangerous command with a safer alternative:\n\n```\n# Instead of:\ngit reset --hard\n\n# Use:\ngit stash push -m \"before reset\"\ngit reset --hard\n```\n\nGet detailed analysis:\n\n```\ndcg explain \"git reset --hard HEAD\"\n```\n\nIf the command is genuinely needed:\n\n```\n# Project-level allowlist (committed, code-reviewed)\ndcg allowlist add core.git:reset-hard --reason \"Required for CI cleanup\" --project\n\n# Or for a specific command\ndcg allowlist add-command \"rm -rf ./build\" --reason \"Build cleanup\" --project\n```\n\nThe finding output includes a copy-paste allowlist command for convenience.\nHeredoc rules use stable IDs like `heredoc.python.shutil_rmtree`\n\n.\n\nScan supports redaction of potentially sensitive content in output. Use `--redact quoted`\n\nto hide quoted strings that may contain secrets:\n\n```\n# Original command:\ncurl -H \"Authorization: Bearer $TOKEN\" https://api.example.com\n\n# With --redact quoted:\ncurl -H \"...\" https://api.example.com\n```\n\nOptions:\n\n`--redact none`\n\n: Show full commands (default)`--redact quoted`\n\n: Hide quoted strings (recommended for CI logs)`--redact aggressive`\n\n: Hide more potential secrets\n\n`.dcg/hooks.toml`\n\n(project-level, committed):\n\n```\n[scan]\n# Exit non-zero when findings meet this threshold\nfail_on = \"error\"      # Options: none, warning, error\n\n# Output format\nformat = \"pretty\"      # Options: pretty, json, markdown\n\n# Maximum file size to scan (bytes)\nmax_file_size = 1000000\n\n# Stop after this many findings\nmax_findings = 50\n\n# Redaction level for sensitive content\nredact = \"quoted\"      # Options: none, quoted, aggressive\n\n# Truncate long commands (chars; 0 = no truncation)\ntruncate = 120\n\n[scan.paths]\n# Only scan files matching these patterns\ninclude = [\n    \"scripts/**\",\n    \".github/workflows/**\",\n    \"Dockerfile*\",\n    \"Makefile\",\n]\n\n# Skip files matching these patterns\nexclude = [\n    \"target/**\",\n    \"node_modules/**\",\n    \"*.md\",\n]\n```\n\nCLI flags override config file values.\n\n```\nname: Security Scan\non: [pull_request]\n\njobs:\n  scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n\n      - name: Install dcg\n        run: |\n          curl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh\" | bash\n          echo \"$HOME/.local/bin\" >> $GITHUB_PATH\n\n      - name: Scan changed files\n        run: |\n          dcg scan --git-diff origin/${{ github.base_ref }}..HEAD \\\n            --format markdown \\\n            --fail-on error\nscan:\n  stage: test\n  script:\n    - curl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh\" | bash\n    - ~/.local/bin/dcg scan --git-diff origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME..HEAD --fail-on error\n  rules:\n    - if: $CI_MERGE_REQUEST_ID\n```\n\nIf you need to bypass the pre-commit hook temporarily:\n\n```\ngit commit --no-verify -m \"Emergency fix\"\n```\n\nThis is logged and visible in git history. For permanent exceptions, use allowlists instead.\n\nYour 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:\n\n**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`\n\nbecomes`git`\n\n) 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.\n\nIf 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.\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│   Claude / Codex / Gemini / Copilot / Cursor / Hermes hooks      │\n│                                                                  │\n│  User: \"delete the build artifacts\"                             │\n│  Agent: executes `rm -rf ./build`                               │\n│                                                                  │\n└─────────────────────┬───────────────────────────────────────────┘\n                      │\n                      ▼ PreToolUse hook (stdin: JSON)\n┌─────────────────────────────────────────────────────────────────┐\n│                     dcg                             │\n│                                                                  │\n│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐       │\n│  │    Parse     │───▶│  Normalize   │───▶│ Quick Reject │       │\n│  │    JSON      │    │   Command    │    │   Filter     │       │\n│  └──────────────┘    └──────────────┘    └──────┬───────┘       │\n│                                                  │               │\n│                      ┌───────────────────────────┘               │\n│                      ▼                                           │\n│  ┌──────────────────────────────────────────────────────────┐   │\n│  │                   Pattern Matching                        │   │\n│  │                                                           │   │\n│  │   1. Check SAFE_PATTERNS (whitelist) ──▶ Allow if match  │   │\n│  │   2. Check DESTRUCTIVE_PATTERNS ──────▶ Deny if match    │   │\n│  │   3. No match ────────────────────────▶ Allow (default)  │   │\n│  │                                                           │   │\n│  └──────────────────────────────────────────────────────────┘   │\n│                                                                  │\n└─────────────────────┬───────────────────────────────────────────┘\n                      │\n                      ▼ stdout: JSON deny / empty allow\n                        stderr: rich human output / Codex deny reason\n┌─────────────────────────────────────────────────────────────────┐\n│   Claude / Codex / Gemini / Copilot / Cursor / Hermes hooks      │\n│                                                                  │\n│  If denied: Shows block message, does NOT execute command       │\n│  If allowed: Proceeds with command execution                    │\n│                                                                  │\n└─────────────────────────────────────────────────────────────────┘\n```\n\nNot every occurrence of a dangerous pattern is actually dangerous. The string `git reset --hard`\n\nappearing 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.\n\n**SpanKind Classification**\n\nEvery token in a command is classified into one of these categories:\n\n| SpanKind | Description | Treatment |\n|---|---|---|\n`Executed` |\nCommand words and unquoted arguments | MUST check - highest priority |\n`InlineCode` |\nContent inside `-c` /`-e` flags (bash -c, python -c) |\nMUST check - code will be executed |\n`Argument` |\nQuoted arguments to known-safe commands | Lower priority, context-dependent |\n`Data` |\nSingle-quoted strings (shell cannot interpolate) | Can skip - treated as literal data |\n`HeredocBody` |\nContent inside heredocs | Escalated to Tier 2/3 heredoc scanning |\n`Comment` |\nShell comments (`# ...` ) |\nSkip - never executed |\n`Unknown` |\nCannot determine context | Conservative treatment as `Executed` |\n\n**Why Context Matters**\n\nConsider these commands:\n\n```\n# Safe: the dangerous pattern is in a comment\necho \"Reminder: never run git reset --hard\"   # git reset --hard destroys changes\n\n# Safe: the dangerous pattern is data being searched for\ngrep \"git reset --hard\" documentation.md\n\n# Safe: the dangerous pattern is in a heredoc being written to a file\ncat <<EOF > safety_guide.md\nWarning: git reset --hard destroys uncommitted changes\nEOF\n\n# DANGEROUS: the pattern will be executed\ngit reset --hard HEAD\n\n# DANGEROUS: the pattern is passed to bash -c for execution\nbash -c \"git reset --hard\"\n```\n\nWithout 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.\n\n**Implementation Details**\n\nThe context classifier uses a multi-pass approach:\n\n**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`\n\n,`-e`\n\n, and similar flags that introduce inline code contexts**Span Annotation**: Tag each character range with its SpanKind\n\nThis approach achieves a significant reduction in false positives while maintaining the zero-false-negatives philosophy for actual command execution.\n\nSafe patterns are checked *before* destructive patterns. This design ensures that explicitly safe commands (like `git checkout -b`\n\n) are never accidentally blocked, even if they partially match a destructive pattern (like `git checkout`\n\n).\n\n```\ngit checkout -b feature    →  Matches SAFE \"checkout-new-branch\"  →  ALLOW\ngit checkout -- file.txt   →  No safe match, matches DESTRUCTIVE  →  DENY\n```\n\nThe hook uses a **default-allow** policy for unrecognized commands. This ensures:\n\n- The hook never breaks legitimate workflows\n- Only\n*known*dangerous patterns are blocked - New git commands are allowed until explicitly categorized\n\nThe pattern set prioritizes **never allowing dangerous commands** over avoiding false positives. A few extra prompts for manual confirmation are acceptable; lost work is not.\n\nThis hook is one layer of protection. It complements (not replaces):\n\n- Regular commits and pushes\n- Git stash before risky operations\n- Proper backup strategies\n- Code review processes\n\nEvery Bash command passes through this hook. Performance is critical:\n\n- Lazy-initialized static regex patterns (compiled once, reused)\n- Quick rejection filter eliminates 99%+ of commands before regex\n- No heap allocations on the hot path for safe commands\n- Sub-millisecond execution for typical commands\n\nThe safe pattern list contains 34 patterns covering:\n\n| Category | Patterns | Purpose |\n|---|---|---|\n| Branch creation | `checkout -b` , `checkout --orphan` |\nCreating branches is safe |\n| Staged-only | `restore --staged` , `restore -S` |\nUnstaging doesn't touch working tree |\n| Dry run | `clean -n` , `clean --dry-run` |\nPreview mode, no actual deletion |\n| Temp cleanup | `rm -rf /tmp/*` , `rm -rf /var/tmp/*` |\nEphemeral directories are safe |\n| Variable expansion | `rm -rf $TMPDIR/*` , `rm -rf ${TMPDIR}/*` |\nShell variable forms |\n| Quoted paths | `rm -rf \"$TMPDIR/*\"` |\nQuoted variable forms |\n| Separate flags | `rm -r -f /tmp/*` , `rm -r -f $TMPDIR/*` |\nFlag ordering variants |\n| Long flags | `rm --recursive --force /tmp/*` , `$TMPDIR/*` |\nGNU-style long options |\n\nThe destructive pattern list contains 16 patterns covering:\n\n| Category | Pattern | Reason |\n|---|---|---|\n| Work destruction | `reset --hard` , `reset --merge` |\nDestroys uncommitted changes |\n| File reversion | `checkout -- <path>` |\nDiscards file modifications |\n| Worktree restore | `restore` (without --staged) |\nDiscards uncommitted changes |\n| Untracked deletion | `clean -f` |\nPermanently removes untracked files |\n| History rewrite | `push --force` , `push -f` |\nCan destroy remote commits |\n| Unsafe branch delete | `branch -D` |\nForce-deletes without merge check |\n| Stash destruction | `stash drop` , `stash clear` |\nPermanently deletes stashed work |\n| Filesystem nuke | `rm -rf` (non-temp paths) |\nRecursive deletion outside temp |\n\nPatterns use [fancy-regex](https://github.com/fancy-regex/fancy-regex) for advanced features:\n\n```\n// Negative lookahead: block restore UNLESS --staged is present\nr\"git\\s+restore\\s+(?!--staged\\b)(?!-S\\b)\"\n\n// Negative lookahead: don't match --force-with-lease\nr\"git\\s+push\\s+.*--force(?![-a-z])\"\n\n// Character class: match any flag ordering\nr\"rm\\s+-[a-zA-Z]*[rR][a-zA-Z]*f[a-zA-Z]*\"\n```\n\n", "url": "https://wpnews.pro/news/show-hn-block-dangerous-git-and-shell-commands-from-being-executed-by-agents", "canonical_source": "https://github.com/Dicklesworthstone/destructive_command_guard", "published_at": "2026-07-12 17:46:09+00:00", "updated_at": "2026-07-12 18:05:22.206933+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "ai-safety"], "entities": ["Claude Code", "Codex CLI", "Gemini CLI", "GitHub Copilot CLI", "Cursor IDE", "Hermes Agent", "Grok (xAI)", "dcg"], "alternates": {"html": "https://wpnews.pro/news/show-hn-block-dangerous-git-and-shell-commands-from-being-executed-by-agents", "markdown": "https://wpnews.pro/news/show-hn-block-dangerous-git-and-shell-commands-from-being-executed-by-agents.md", "text": "https://wpnews.pro/news/show-hn-block-dangerous-git-and-shell-commands-from-being-executed-by-agents.txt", "jsonld": "https://wpnews.pro/news/show-hn-block-dangerous-git-and-shell-commands-from-being-executed-by-agents.jsonld"}}