{"id":37230246,"url":"https://github.com/dicklesworthstone/destructive_command_guard","last_synced_at":"2026-05-01T03:02:20.992Z","repository":{"id":331934423,"uuid":"1130004860","full_name":"Dicklesworthstone/destructive_command_guard","owner":"Dicklesworthstone","description":"The Destructive Command Guard (dcg) is for blocking dangerous git and shell commands from being executed by agents.","archived":false,"fork":false,"pushed_at":"2026-04-28T00:20:21.000Z","size":10997,"stargazers_count":924,"open_issues_count":0,"forks_count":53,"subscribers_count":3,"default_branch":"main","last_synced_at":"2026-04-28T01:26:13.038Z","etag":null,"topics":["ai-agents","cli","developer-tools","git","rust","safety"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Dicklesworthstone.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"docs/security-model.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2026-01-07T22:27:34.000Z","updated_at":"2026-04-28T01:25:38.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/Dicklesworthstone/destructive_command_guard","commit_stats":null,"previous_names":["dicklesworthstone/destructive_command_guard"],"tags_count":23,"template":false,"template_full_name":null,"purl":"pkg:github/Dicklesworthstone/destructive_command_guard","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fdestructive_command_guard","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fdestructive_command_guard/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fdestructive_command_guard/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fdestructive_command_guard/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Dicklesworthstone","download_url":"https://codeload.github.com/Dicklesworthstone/destructive_command_guard/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fdestructive_command_guard/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32483406,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-30T13:12:12.517Z","status":"online","status_checked_at":"2026-05-01T02:00:05.856Z","response_time":64,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-agents","cli","developer-tools","git","rust","safety"],"created_at":"2026-01-15T03:37:26.758Z","updated_at":"2026-05-01T03:02:20.976Z","avatar_url":"https://github.com/Dicklesworthstone.png","language":"Rust","readme":"# dcg (Destructive Command Guard)\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"illustration.webp\" alt=\"Destructive Command Guard - Protecting your code from accidental destruction\"\u003e\n\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n\n[![Coverage](https://img.shields.io/codecov/c/github/Dicklesworthstone/destructive_command_guard?label=coverage)](https://codecov.io/gh/Dicklesworthstone/destructive_command_guard)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n\u003c/div\u003e\n\nA high-performance hook for AI coding agents that blocks destructive commands before they execute, protecting your work from accidental deletion.\n\n**Supported:** [Claude Code](https://claude.ai/code), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/concepts/agents/coding-agent/about-hooks), [Cursor IDE](https://cursor.com), [OpenCode](https://opencode.ai) (via [community plugin](https://github.com/aspiers/ai-config/blob/main/.config/opencode/plugins/dcg-guard.js)), [Aider](https://aider.chat/) (limited—git hooks only), [Continue](https://continue.dev) (detection only), [Codex CLI](https://github.com/openai/codex)\n\n\u003cdiv align=\"center\"\u003e\n\u003ch3\u003eQuick Install\u003c/h3\u003e\n\n```bash\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash -s -- --easy-mode\n```\n\n\u003cp\u003e\u003cem\u003eWorks on Linux, macOS, and Windows (WSL). Auto-detects your platform and downloads the right binary.\u003c/em\u003e\u003c/p\u003e\n\u003c/div\u003e\n\n---\n\n## TL;DR\n\n**The Problem**: AI coding agents (Claude, GPT, etc.) occasionally run catastrophic commands like `git reset --hard`, `rm -rf ./src`, or `DROP TABLE users`—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### Why Use dcg?\n\n| Feature | What It Does |\n|---------|--------------|\n| **Zero-Config Protection** | Blocks dangerous git/filesystem commands out of the box |\n| **50+ Security Packs** | Databases, Kubernetes, Docker, AWS/GCP/Azure, Terraform, and more |\n| **Sub-Millisecond Latency** | SIMD-accelerated filtering—you won't notice it's there |\n| **Heredoc/Inline Script Scanning** | Catches `python -c \"os.remove(...)\"` and embedded shell scripts |\n| **Smart Context Detection** | Won't block `grep \"rm -rf\"` (data) but will block `rm -rf /` (execution) |\n| **Rich Terminal Output** | Human-readable denial panels, rule context, and suggestions on stderr |\n| **Agent-Safe Streams** | Machine-readable hook output stays on stdout while rich UI stays on stderr |\n| **Graceful Degradation** | Plain output for CI, pipes, dumb terminals, and no-color environments |\n| **Scan Mode for CI** | Pre-commit hooks and CI integration to catch dangerous commands in code review |\n| **Fail-Open Design** | Never blocks your workflow due to timeouts or parse errors |\n| **Explain Mode** | `dcg explain \"command\"` shows exactly why something is blocked |\n\n### Quick Example\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```\n\n### Enable More Protection\n\n```toml\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\n### Agent-Specific Profiles\n\ndcg automatically detects which AI coding agent is invoking it and can apply\nagent-specific configuration. The `trust_level` field 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` | Removes rule packs from evaluation |\n| `extra_packs` | Adds rule packs to evaluation |\n| `additional_allowlist` | Adds command patterns that bypass deny rules |\n| `disabled_allowlist` | When `true`, ignores all allowlist entries |\n\n```toml\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](docs/agents.md) for full documentation on supported agents,\ntrust levels, and configuration options.\n\n---\n\n## Origins \u0026 Authors\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- **[Jeffrey Emanuel](https://github.com/Dicklesworthstone)** - Original concept and Python implementation ([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\n- **[Darin Gordon](https://github.com/Dowwie)** - Initial Rust port with performance optimizations\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\n## Escape Hatch / Bypass\n\nIf dcg is blocking something you genuinely need to run:\n\n| Method | Scope | How |\n|--------|-------|-----|\n| **Env var bypass** | Single command | `DCG_BYPASS=1 \u003ccommand\u003e` |\n| **Allow-once code** | Single command | Copy the short code from the block message, run `dcg allow-once \u003ccode\u003e` |\n| **Permanent allowlist** | Rule or command | `dcg allowlist add core.git:reset-hard -r \"reason\"` |\n| **Remove the hook** | All commands | Delete or comment out the dcg entry in `~/.claude/settings.json` (or equivalent for your agent) |\n\n`DCG_BYPASS=1` disables all protection for that invocation. Use it sparingly and prefer allowlists for recurring needs.\n\n## Modular Pack System\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: `docs/packs/README.md`\n- Canonical descriptions + pattern counts: `dcg packs --verbose`\n\n### Core Packs (enabled by default)\n- `core.filesystem` - Protects against dangerous rm -rf commands outside temp directories\n- `core.git` - Protects against destructive git commands that can lose uncommitted work, rewrite history, or destroy stashes\n\n**Common packs enabled by default:**\n- `database.postgresql` - Protects against destructive PostgreSQL operations\n- `containers.docker` - Protects against destructive Docker operations like system prune\n\n### Storage Packs\n- `storage.s3` - Protects against destructive S3 operations like bucket removal, recursive deletes, and sync --delete.\n- `storage.gcs` - Protects against destructive GCS operations like bucket removal, object deletion, and recursive deletes.\n- `storage.minio` - Protects against destructive MinIO Client (mc) operations like bucket removal, object deletion, and admin operations.\n- `storage.azure_blob` - Protects against destructive Azure Blob Storage operations like container deletion, blob deletion, and azcopy remove.\n\n### Remote Packs\n- `remote.rsync` - Protects against destructive rsync operations like --delete and its variants.\n- `remote.scp` - Protects against destructive SCP operations like overwrites to system paths.\n- `remote.ssh` - Protects against destructive SSH operations like remote command execution and key management.\n\n### Database Packs\n- `database.postgresql` - Protects against destructive PostgreSQL operations like DROP DATABASE, TRUNCATE, and dropdb.\n- `database.mysql` - MySQL/MariaDB guard.\n- `database.mongodb` - Protects against destructive MongoDB operations like dropDatabase, dropCollection, and remove without criteria.\n- `database.redis` - Protects against destructive Redis operations like FLUSHALL, FLUSHDB, and mass key deletion.\n- `database.sqlite` - Protects against destructive SQLite operations like DROP TABLE, DELETE without WHERE, and accidental data loss.\n- `database.supabase` - Protects against destructive Supabase CLI operations including database resets, migration rollbacks, function/secret/storage deletion, project removal, and infrastructure changes.\n\n### Container Packs\n- `containers.docker` - Protects against destructive Docker operations like system prune, volume prune, and force removal.\n- `containers.compose` - Protects against destructive Docker Compose operations like down -v which removes volumes.\n- `containers.podman` - Protects against destructive Podman operations like system prune, volume prune, and force removal.\n\n### Kubernetes Packs\n- `kubernetes.kubectl` - Protects against destructive kubectl operations like delete namespace, drain, and mass deletion.\n- `kubernetes.helm` - Protects against destructive Helm operations like uninstall and rollback without dry-run.\n- `kubernetes.kustomize` - Protects against destructive Kustomize operations when combined with kubectl delete or applied without review.\n\n### Cloud Provider Packs\n- `cloud.aws` - Protects against destructive AWS CLI operations like terminate-instances, delete-db-instance, and s3 rm --recursive.\n- `cloud.azure` - Protects against destructive Azure CLI operations like vm delete, storage account delete, and resource group delete.\n- `cloud.gcp` - Protects against destructive gcloud operations like instances delete, sql instances delete, and gsutil rm -r.\n\n### CDN Packs\n- `cdn.cloudflare_workers` - Protects against destructive Cloudflare Workers, KV, R2, and D1 operations via the Wrangler CLI.\n- `cdn.cloudfront` - Protects against destructive AWS CloudFront operations like deleting distributions, cache policies, and functions.\n- `cdn.fastly` - Protects against destructive Fastly CLI operations like service, domain, backend, and VCL deletion.\n\n### API Gateway Packs\n- `apigateway.apigee` - Protects against destructive Google Apigee CLI and apigeecli operations.\n- `apigateway.aws` - Protects against destructive AWS API Gateway CLI operations for both REST APIs and HTTP APIs.\n- `apigateway.kong` - Protects against destructive Kong Gateway CLI, deck CLI, and Admin API operations.\n\n### Infrastructure Packs\n- `infrastructure.ansible` - Protects against destructive Ansible operations like dangerous shell commands and unchecked playbook runs.\n- `infrastructure.pulumi` - Protects against destructive Pulumi operations like destroy and up with -y (auto-approve).\n- `infrastructure.terraform` - Protects against destructive Terraform operations like destroy, taint, and apply with -auto-approve.\n\n### System Packs\n- `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).\n- `system.permissions` - Protects against dangerous permission changes like chmod 777, recursive chmod/chown on system directories.\n- `system.services` - Protects against dangerous service operations like stopping critical services and modifying init configuration.\n\n### CI/CD Packs\n- `cicd.circleci` - Protects against destructive CircleCI operations like deleting contexts, removing secrets, deleting orbs/namespaces, or removing pipelines.\n- `cicd.github_actions` - Protects against destructive GitHub Actions operations like deleting secrets/variables or using gh api DELETE against /actions endpoints.\n- `cicd.gitlab_ci` - Protects against destructive GitLab CI/CD operations like deleting variables, removing artifacts, and unregistering runners.\n- `cicd.jenkins` - Protects against destructive Jenkins CLI/API operations like deleting jobs, nodes, credentials, or build history.\n\n### Secrets Management Packs\n- `secrets.aws_secrets` - Protects against destructive AWS Secrets Manager and SSM Parameter Store operations like delete-secret and delete-parameter.\n- `secrets.doppler` - Protects against destructive Doppler CLI operations like deleting secrets, configs, environments, or projects.\n- `secrets.onepassword` - Protects against destructive 1Password CLI operations like deleting items, documents, users, groups, and vaults.\n- `secrets.vault` - Protects against destructive Vault CLI operations like deleting secrets, disabling auth/secret engines, revoking leases/tokens, and deleting policies.\n\n### Platform Packs\n- `platform.github` - Protects against destructive GitHub CLI operations like deleting repositories, gists, releases, or SSH keys.\n- `platform.gitlab` - Protects against destructive GitLab platform operations like deleting projects, releases, protected branches, and webhooks.\n- `platform.railway` - Protects against destructive Railway CLI and Public API operations that can delete projects, environments, services, functions, volumes, variables, or deployments.\n\n### DNS Packs\n- `dns.cloudflare` - Protects against destructive Cloudflare DNS operations like record deletion, zone deletion, and targeted Terraform destroy.\n- `dns.generic` - Protects against destructive or risky DNS tooling usage (nsupdate deletes, zone transfers).\n- `dns.route53` - Protects against destructive AWS Route53 DNS operations like hosted zone deletion and record set DELETE changes.\n\n### Email Packs\n- `email.mailgun` - Protects against destructive Mailgun API operations like domain deletion, route deletion, and mailing list removal.\n- `email.postmark` - Protects against destructive Postmark API operations like server deletion, template deletion, and sender signature removal.\n- `email.sendgrid` - Protects against destructive SendGrid API operations like template deletion, API key deletion, and domain authentication removal.\n- `email.ses` - Protects against destructive AWS Simple Email Service operations like identity deletion, template deletion, and configuration set removal.\n\n### Feature Flag Packs\n- `featureflags.flipt` - Protects against destructive Flipt CLI and API operations.\n- `featureflags.launchdarkly` - Protects against destructive LaunchDarkly CLI and API operations.\n- `featureflags.split` - Protects against destructive Split.io CLI and API operations.\n- `featureflags.unleash` - Protects against destructive Unleash CLI and API operations.\n\n### Load Balancer Packs\n- `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.\n- `loadbalancer.haproxy` - Protects against destructive HAProxy load balancer operations like stopping the service or disabling backends via runtime API.\n- `loadbalancer.nginx` - Protects against destructive nginx load balancer operations like stopping the service or deleting config files.\n- `loadbalancer.traefik` - Protects against destructive Traefik load balancer operations like stopping containers, deleting config, or API deletions.\n\n### Messaging Packs\n- `messaging.kafka` - Protects against destructive Kafka CLI operations like deleting topics, removing consumer groups, resetting offsets, and deleting records.\n- `messaging.nats` - Protects against destructive NATS/JetStream operations like deleting streams, consumers, key-value entries, objects, and accounts.\n- `messaging.rabbitmq` - Protects against destructive RabbitMQ operations like deleting queues/exchanges, purging queues, deleting vhosts, and resetting cluster state.\n- `messaging.sqs_sns` - Protects against destructive AWS SQS and SNS operations like deleting queues, purging messages, deleting topics, and removing subscriptions.\n\n### Monitoring Packs\n- `monitoring.datadog` - Protects against destructive Datadog CLI/API operations like deleting monitors and dashboards.\n- `monitoring.newrelic` - Protects against destructive New Relic CLI/API operations like deleting entities or alerting resources.\n- `monitoring.pagerduty` - Protects against destructive PagerDuty CLI/API operations like deleting services and schedules (which can break incident routing).\n- `monitoring.prometheus` - Protects against destructive Prometheus/Grafana operations like deleting time series data or dashboards/datasources.\n- `monitoring.splunk` - Protects against destructive Splunk CLI/API operations like index removal and REST API DELETE calls.\n\n### Payment Packs\n- `payment.braintree` - Protects against destructive Braintree/PayPal payment operations like deleting customers or cancelling subscriptions via API/SDK calls.\n- `payment.square` - Protects against destructive Square CLI/API operations like deleting catalog objects or customers (which can break payment flows).\n- `payment.stripe` - Protects against destructive Stripe CLI/API operations like deleting webhook endpoints and customers, or rotating API keys without coordination.\n\n### Search Engine Packs\n- `search.algolia` - Protects against destructive Algolia operations like deleting indices, clearing objects, removing rules/synonyms, and deleting API keys.\n- `search.elasticsearch` - Protects against destructive Elasticsearch REST API operations like index deletion, delete-by-query, index close, and cluster setting changes.\n- `search.meilisearch` - Protects against destructive Meilisearch REST API operations like index deletion, document deletion, delete-batch, and API key removal.\n- `search.opensearch` - Protects against destructive OpenSearch REST API operations and AWS CLI domain deletions.\n\n### Backup Packs\n- `backup.borg` - Protects against destructive borg operations like delete, prune, compact, and recreate.\n- `backup.rclone` - Protects against destructive rclone operations like sync, delete, purge, dedupe, and move.\n- `backup.restic` - Protects against destructive restic operations like forgetting snapshots, pruning data, removing keys, and cache cleanup.\n- `backup.velero` - Protects against destructive velero operations like deleting backups, schedules, and locations.\n\n### Other Packs\n- `package_managers` - Protects against dangerous package manager operations like publishing packages and removing critical system packages.\n- `strict_git` - Stricter git protections: blocks all force pushes, rebases, and history rewriting operations.\n\nEnable packs in `~/.config/dcg/config.toml`:\n\n```toml\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\n### Custom Packs\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```toml\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`](docs/custom-packs.md).\n\nValidate your pack before deployment:\n\n```bash\ndcg pack validate mypack.yaml\n```\n\nHeredoc scanning configuration:\n\n```toml\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` / `--no-heredoc-scan`\n- `--heredoc-timeout \u003cms\u003e`\n- `--heredoc-languages \u003clang1,lang2,...\u003e`\n\nHeredoc documentation:\n\n- `docs/adr-001-heredoc-scanning.md` (architecture and rationale)\n- `docs/patterns.md` (pattern authoring + inventory)\n- `docs/security.md` (threat model and incident response)\n\n#### Heredoc Three-Tier Architecture\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, \u003c100μs)\n│   (RegexSet)    │\n└────────┬────────┘\n         │ Match\n         ▼\n┌─────────────────┐\n│ Tier 2: Extract │ ─── Error/Timeout ──► ALLOW + fallback check\n│   (\u003c1ms)        │\n└────────┬────────┘\n         │ Success\n         ▼\n┌─────────────────┐\n│ Tier 3: AST     │ ─── No match ──► ALLOW\n│   (\u003c5ms)        │ ─── Match ──► BLOCK\n└─────────────────┘\n```\n\n**Tier 1: Trigger Detection** (\u003c100μs)\n\nUltra-fast regex screening to detect heredoc indicators. Uses a compiled `RegexSet` for O(n) matching against all trigger patterns simultaneously:\n\n```rust\nstatic HEREDOC_TRIGGERS: LazyLock\u003cRegexSet\u003e = LazyLock::new(|| {\n    RegexSet::new([\n        r\"\u003c\u003c-?\\s*(?:['\\x22][^'\\x22]*['\\x22]|[\\w.-]+)\",  // Heredocs\n        r\"\u003c\u003c\u003c\",                                          // 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** (\u003c1ms)\n\nFor commands that trigger, extract the actual content to be evaluated:\n\n- **Heredocs**: `cat \u003c\u003cEOF ... EOF` → extracts body between delimiters\n- **Here-strings**: `cat \u003c\u003c\u003c \"content\"` → extracts quoted content\n- **Inline scripts**: `python -c \"code\"` → extracts the code argument\n\nExtraction is bounded by configurable limits:\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```rust\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** (\u003c5ms)\n\nExtracted content is parsed using language-specific AST grammars (via tree-sitter/ast-grep) and matched against structural patterns:\n\n```rust\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\"`), Tier 3 recursively extracts inner commands and re-evaluates them through the full pipeline:\n\n```rust\nif content.language == ScriptLanguage::Bash {\n    let inner_commands = extract_shell_commands(\u0026content.content);\n    for inner in inner_commands {\n        // Re-evaluate inner command against all packs\n        if let Some(result) = evaluate_command(\u0026inner, ...) {\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\n### Environment Variables\n\nEnvironment variables override config files (highest priority):\n\n- `DCG_PACKS=\"containers.docker,kubernetes\"`: enable packs (comma-separated)\n- `DCG_DISABLE=\"kubernetes.helm\"`: disable packs/sub-packs (comma-separated)\n- `DCG_VERBOSE=0-3`: verbosity level (0 = quiet, 3 = trace)\n- `DCG_QUIET=1`: suppress non-error output\n- `DCG_COLOR=auto|always|never`: color mode\n- `DCG_NO_RICH=1`: disable rich terminal formatting and use plain rendering\n- `DCG_NO_COLOR=1`: disable colored output (same as NO_COLOR)\n- `DCG_LEGACY_OUTPUT=1`: force plain output paths (same as `--legacy-output`)\n- `DCG_ROBOT=1`: enable robot mode for JSON stdout and quiet stderr\n- `DCG_HIGH_CONTRAST=1`: enable high-contrast output (ASCII borders + monochrome palette)\n- `DCG_FORMAT=text|json|sarif`: default output format (command-specific; SARIF applies to `dcg scan`)\n- `DCG_BYPASS=1`: bypass dcg entirely (escape hatch; use sparingly)\n- `DCG_CONFIG=/path/to/config.toml`: use explicit config file\n- `DCG_HEREDOC_ENABLED=true|false`: enable/disable heredoc scanning\n- `DCG_HEREDOC_TIMEOUT=50`: heredoc extraction timeout (milliseconds)\n- `DCG_HEREDOC_TIMEOUT_MS=50`: heredoc extraction timeout (milliseconds)\n- `DCG_HEREDOC_LANGUAGES=python,bash`: filter heredoc languages\n- `DCG_POLICY_DEFAULT_MODE=deny|warn|log`: global default decision mode\n- `DCG_HOOK_TIMEOUT_MS=200`: hook evaluation timeout budget (milliseconds)\n\n### Configuration Hierarchy\n\ndcg supports layered configuration from multiple sources, with higher-priority sources overriding lower ones:\n\n1. Environment Variables (DCG_* prefix)           [HIGHEST PRIORITY]\n2. Explicit Config File (DCG_CONFIG env var)\n3. Project Config (.dcg.toml in repo root)\n4. User Config (~/.config/dcg/config.toml)\n5. System Config (/etc/dcg/config.toml)\n6. Compiled Defaults                              [LOWEST PRIORITY]\n\n### Accessibility \u0026 Themes\n\ndcg supports colorblind-safe palettes and high-contrast output. Colors are always paired\nwith symbols/labels to avoid conveying meaning by color alone.\n\n```toml\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` | Organization-wide defaults |\n| User | `~/.config/dcg/config.toml` | Personal preferences |\n| Project | `.dcg.toml` (repo root) | Project-specific settings |\n| Explicit | `DCG_CONFIG=/path/to/file` | Testing or override |\n\n**Merging Behavior**:\n\nConfiguration layers are merged additively, with higher-priority sources overriding specific fields:\n\n```rust\n// Only fields explicitly set in higher-priority configs override\n// Missing fields retain values from lower-priority sources\nfn merge_layer(\u0026mut 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`, 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.\n\n**Project-Specific Pack Configuration**:\n\nThe `[projects]` section allows different pack configurations for different repositories:\n\n```toml\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\n### Fail-Open Philosophy\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\n1. **Workflow Continuity**: A blocked legitimate command is more disruptive than a missed dangerous one\n2. **Performance Guarantees**: The hook must never become a bottleneck\n3. **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\n```toml\n[heredoc]\nfallback_on_parse_error = false  # Block on parse errors\nfallback_on_timeout = false      # Block on timeouts\n```\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```rust\nstatic FALLBACK_PATTERNS: LazyLock\u003cRegexSet\u003e = 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\n## Installation\n\n### Quick Install (Recommended)\n\nThe easiest way to install is using the install script, which downloads a prebuilt binary for your platform:\n\n```bash\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, Gemini CLI, Copilot CLI, Aider, Codex CLI), and updates your PATH.\n\n**Other options:**\n\nInteractive mode (prompts for each step):\n\n```bash\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash\n```\n\nInstall specific version:\n\n```bash\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash -s -- --version v0.1.0\n```\n\nInstall to /usr/local/bin (system-wide, requires sudo):\n\n```bash\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```bash\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```bash\ncurl -fsSL \"https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/install.sh?$(date +%s)\" | bash -s -- --no-configure\n```\n\n\u003e **Note:** If you have [gum](https://github.com/charmbracelet/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`) if present.\n\n\u003cdetails\u003e\n\u003csummary\u003eAgent-specific notes\u003c/summary\u003e\n\n- **Aider:** No PreToolUse-style interception. The installer enables `git-commit-verify: true` in `~/.aider.conf.yml` so git hooks run. For full protection, install dcg as a [git pre-commit hook](docs/scan-precommit-guide.md).\n- **Continue:** No shell command interception hooks. The installer detects Continue but cannot auto-configure protection. Use a [git pre-commit hook](docs/scan-precommit-guide.md) instead.\n- **Codex CLI:** PreToolUse hooks via `~/.codex/hooks.json` (stable in codex 0.125.0+; the `codex_hooks` feature is on by default). Codex's hook input shape mirrors Claude Code's, but its JSON deny parser is strict (`#[serde(deny_unknown_fields)]`), so dcg detects Codex from the `turn_id` stdin field (codex's documented extension over Claude's hook spec) and switches to Codex's documented stderr deny path with exit code 2; the colored block message goes to stderr where codex shows it to the model. See the [Codex integration notes](docs/codex-integration.md). Caveat: the model can still write scripts to disk to bypass hook-based blocking. **Windows note:** `install.ps1` now detects Codex and merges a dcg `PreToolUse` Bash hook into `%USERPROFILE%\\.codex\\hooks.json`; `uninstall.ps1` removes only dcg hooks and preserves coexisting entries.\n- **GitHub Copilot CLI:** Hooks are repository-local (`.github/hooks/*.json`). Run the installer from each repository where you want protection.\n- **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](https://github.com/aspiers/ai-config/blob/main/.config/opencode/plugins/dcg-guard.js).\n\n\u003c/details\u003e\n\n\u003e **Recommended:** After installing, run `dcg setup` to add a [shell startup check](#hook-silently-removed-recommended-add-shell-startup-check) that warns you if the dcg hook is ever silently removed from `~/.claude/settings.json`.\n\n### From source (requires Rust nightly)\n\nThis project uses Rust Edition 2024 features and requires the nightly toolchain. The repository includes a `rust-toolchain.toml` that automatically selects the correct toolchain.\n\n```bash\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\n```\n\n### Manual build\n\n```bash\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\n## Updating\n\nRun the built-in updater to re-run the installer for your platform:\n\n```bash\ndcg update\n```\n\nOptional flags mirror the installer scripts (examples):\n\n```bash\ndcg update --version v0.2.7\ndcg update --system\ndcg update --verify\n```\n\nYou can always re-run `install.sh` / `install.ps1` directly if preferred.\n\n### Prebuilt Binaries\n\nPrebuilt binaries are available for:\n- Linux x86_64 (`x86_64-unknown-linux-gnu`)\n- Linux ARM64 (`aarch64-unknown-linux-gnu`)\n- macOS Intel (`x86_64-apple-darwin`)\n- macOS Apple Silicon (`aarch64-apple-darwin`)\n- Windows (`x86_64-pc-windows-msvc`)\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`) so you can verify provenance with `cosign verify-blob`.\n\n## Uninstalling\n\nRemove dcg and all its hooks from AI agents:\n\n```bash\ncurl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/uninstall.sh | bash\n```\n\nOn Windows:\n\n```powershell\nirm https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/main/uninstall.ps1 | iex\n```\n\nThe Unix uninstaller:\n- Removes dcg hooks from Claude Code, Codex CLI, Cursor IDE, Gemini CLI, GitHub Copilot CLI (repo-local), and Aider\n- Removes the dcg binary\n- Removes configuration (`~/.config/dcg/`) and history (`~/.local/share/dcg/`)\n- Prompts for confirmation before making changes\n\nThe PowerShell uninstaller removes the Windows `dcg.exe` binary, the exact User PATH entry added by `install.ps1`, dcg hooks from Claude Code and Codex CLI, and dcg configuration/history directories.\n\nOptions:\n- `--yes` - Skip confirmation prompt\n- `--keep-config` - Preserve configuration files\n- `--keep-history` - Preserve history database\n- `--purge` - Remove everything (overrides keep flags)\n\n## Claude Code Configuration\n\nAdd to `~/.claude/settings.json`:\n\n```json\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\n## Gemini CLI Configuration\n\nAdd to `~/.gemini/settings.json`:\n\n```json\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\n## CLI Usage\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```bash\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\n### Test Mode (`dcg test`)\n\nUse `dcg test` to evaluate a command **without executing it**. This is useful for CI checks, false-positive debugging, and config validation before rollout.\n\n#### Basic Usage\n\n```bash\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#### Exit Codes\n\n- `0`: command would be allowed\n- `1`: command would be blocked\n\n#### Flags and Options\n\n- `-c, --config \u003cPATH\u003e`: use a specific config file\n- `--with-packs \u003cID1,ID2\u003e`: temporarily enable extra packs\n- `--explain`: print detailed decision trace\n- `-f, --format \u003cpretty|json|toon\u003e`: output format (default: `pretty`)\n- `--no-color`: disable ANSI color output\n- `--heredoc-scan`: force-enable heredoc/inline-script scanning\n- `--no-heredoc-scan`: force-disable heredoc/inline-script scanning\n- `--heredoc-timeout \u003cMS\u003e`: override heredoc extraction timeout budget\n- `--heredoc-languages \u003cLANG1,LANG2\u003e`: limit heredoc AST scanning languages\n\n#### Output Formats\n\n- `pretty`: human-readable output with command context, matched rule info, and suggestions\n- `json`: structured payload for scripts/CI; includes metadata like `schema_version`, `dcg_version`, `command`, `decision`, rule/pack fields, and allowlist/agent context when present\n- `toon`: token-efficient structured encoding of the same payload used by `json` (useful for agent-to-agent/tool pipelines)\n\n#### CI/CD Integration Examples\n\nFail fast in shell pipelines:\n\n```bash\ndcg test --format json \"rm -rf /\" \u003e /tmp/dcg.json\njq -e '.decision == \"allow\"' /tmp/dcg.json\n```\n\nMinimal GitHub Actions step:\n\n```yaml\n- name: Validate dangerous command policy\n  run: |\n    ~/.local/bin/dcg test --format json \"git reset --hard HEAD~1\" \u003e /tmp/dcg-test.json\n    jq -e '.decision == \"allow\"' /tmp/dcg-test.json\n```\n\n#### Troubleshooting\n\n- Use `--format json` (or `DCG_FORMAT=json`) for machine parsing.\n- Add `--no-color` if logs or parsers choke on ANSI output.\n- If results differ between environments, check config precedence (`DCG_CONFIG`, project `.dcg.toml`, user/system config).\n- If a command is unexpectedly allowed, inspect active allowlists (`dcg allowlist list`) and enabled packs (`dcg packs --verbose`).\n- For full decision traces, run `dcg test --explain \"\u003ccommand\u003e\"` (or `dcg explain \"\u003ccommand\u003e\"`).\n\n### Explain Mode\n\nWhen 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:\n\n```bash\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` (currently 2). v2 adds\n`matched_span`, `matched_text_preview`, and `explanation` in the `match`\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- **Normalized command**: How dcg sees the command after path normalization\n- **Decision**: Whether the command would be blocked or allowed\n- **Matching rule**: Which pack and pattern triggered the decision\n- **Evaluation trace**: Step-by-step timing of each evaluation stage\n- **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\n### Allow-Once (Temporary Exceptions)\n\nSometimes you need to run a blocked command temporarily without permanently modifying your allowlist. The allow-once system provides short codes:\n\n```bash\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\n1. When dcg blocks a command, it generates a short code (currently 6 numeric digits; collisions are handled via `--pick` / `--hash`)\n2. The code is tied to the exact command that was blocked\n3. Running `dcg allow-once \u003ccode\u003e` creates a temporary exception\n4. The exception is stored in `~/.config/dcg/pending_exceptions.jsonl`\n5. Exceptions expire after 24 hours (or after first use if `--single-use` is used)\n6. While active, the exception allows the same command in the same directory scope\n\nThis workflow is useful for:\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- Short codes are derived from SHA256 (or optional HMAC-SHA256 when `DCG_ALLOW_ONCE_SECRET` is set)\n- 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\n### Rebase Recovery Mode\n\nAI 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 \u003cpaths\u003e`, 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.\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\n1. **Active rebase state (automatic, zero-config).** When `.git/rebase-merge/` or `.git/rebase-apply/` exists, 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` note on stderr. No permit needed.\n\n2. **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`), run:\n\n   ```bash\n   dcg rebase-recover            # default ttl: 120s\n   dcg rebase-recover --ttl 60   # custom ttl (max: 600s)\n   ```\n\n   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 -- \u003cpath\u003e` and `git restore \u003cpaths\u003e` are 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: `core.git:checkout-discard`, `core.git:checkout-ref-discard`, `core.git:restore-worktree`, `core.git:restore-worktree-explicit`.\n- **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.\n- The permit is scoped to the current repo's `.dcg/` directory. It does not cross repos.\n- 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` output 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\n## Repository Scanning\n\nWhile 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.\n\n### What Scan Is (and Is Not)\n\n**What it is:**\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- 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` 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.\n\n### Supported File Formats\n\ndcg scan includes specialized extractors for each file format, understanding which parts contain executable commands:\n\n| File Type | Detection | Executable Contexts |\n|-----------|-----------|---------------------|\n| **Shell Scripts** | `*.sh`, `*.bash`, `*.zsh`, `*.dash`, `*.ksh` | Non-comment executable command lines |\n| **Dockerfile** | `Dockerfile`, `Dockerfile.*`, `*.dockerfile` | `RUN` instructions (shell and exec forms) |\n| **GitHub Actions** | `.github/workflows/*.yml`, `.github/workflows/*.yaml` | `run:` fields in steps |\n| **GitLab CI** | `.gitlab-ci.yml`, `*.gitlab-ci.yml` | `script:`, `before_script:`, `after_script:` |\n| **Azure Pipelines** | `azure-pipelines.yml`, `azure-pipelines.yaml`, `azure-pipelines-*.yml`, `azure-pipelines-*.yaml` | `script:`, `bash:`, `powershell:`, `pwsh:` tasks |\n| **CircleCI** | `.circleci/config.yml`, `.circleci/config.yaml` | `run:` steps and nested `command:` fields |\n| **Makefile** | `Makefile` | Tab-indented recipe lines |\n| **package.json** | `package.json` | `scripts` object values |\n| **Terraform** | `*.tf` | `provisioner` blocks (`local-exec`, `remote-exec`) |\n| **Docker Compose** | `docker-compose.yml`, `docker-compose.yaml`, `compose.yml`, `compose.yaml` | `command:`, `entrypoint:`, `healthcheck.test:` fields |\n\n**Context-Aware Extraction**:\n\nEach extractor understands its format's semantics:\n\n```yaml\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```\n\n```dockerfile\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```\n\n```makefile\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- **YAML**: `environment:`, `labels:`, `volumes:`, `variables:` blocks\n- **Terraform**: Everything outside `provisioner` blocks\n- **All formats**: Comments (format-appropriate: `#`, `//`, etc.)\n\n### Quick Start\n\n```bash\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### Recommended Rollout Plan\n\n**Start conservative to avoid developer friction:**\n\n```bash\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` with conservative defaults:\n\n```toml\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\n1. **Week 1-2**: Start with workflows/Dockerfiles only, `--fail-on error`\n2. **Week 3-4**: Add Makefiles and shell scripts in `scripts/`\n3. **Month 2**: Add `--fail-on warning` after reviewing findings\n4. **Ongoing**: Add new extractors as team confidence grows\n\n### Pre-Commit Integration\n\n#### One-Command Install\n\n```bash\ndcg scan install-pre-commit\n```\n\nThis creates a `.git/hooks/pre-commit` that runs `dcg scan --staged`.\n\n#### Manual Setup\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...\n```\n\n#### Uninstall\n\n```bash\ndcg scan uninstall-pre-commit\n```\n\nThis only removes hooks installed by dcg (detected via sentinel comment).\n\n### Interpreting Findings\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\n- **Severity**: `ERROR` (catastrophic) or `WARNING` (concerning)\n- **Rule ID**: Stable identifier like `core.git:reset-hard`\n- **Command**: The extracted command (may be redacted/truncated)\n- **Reason**: Why this command is flagged\n- **Suggestion**: How to make it safer\n\n### Fixing Findings\n\n#### Option 1: Change the Code (Preferred)\n\nReplace the dangerous command with a safer alternative:\n\n```bash\n# Instead of:\ngit reset --hard\n\n# Use:\ngit stash push -m \"before reset\"\ngit reset --hard\n```\n\n#### Option 2: Understand with Explain\n\nGet detailed analysis:\n\n```bash\ndcg explain \"git reset --hard HEAD\"\n```\n\n#### Option 3: Allowlist (When Intentional)\n\nIf the command is genuinely needed:\n\n```bash\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### Privacy and Redaction\n\nScan supports redaction of potentially sensitive content in output. Use `--redact quoted` to 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- `--redact none`: Show full commands (default)\n- `--redact quoted`: Hide quoted strings (recommended for CI logs)\n- `--redact aggressive`: Hide more potential secrets\n\n### Configuration Reference\n\n`.dcg/hooks.toml` (project-level, committed):\n\n```toml\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### CI Integration\n\n#### GitHub Actions\n\n```yaml\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\" \u003e\u003e $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\n```\n\n#### GitLab CI\n\n```yaml\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\n### Bypass for Emergencies\n\nIf you need to bypass the pre-commit hook temporarily:\n\n```bash\ngit commit --no-verify -m \"Emergency fix\"\n```\n\nThis is logged and visible in git history. For permanent exceptions, use allowlists instead.\n\n## How It Works\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\n1. **JSON Parsing** -- Validates the hook payload (Claude/Gemini/Copilot variants), extracts the command string. Non-shell tools are immediately allowed.\n2. **Normalization** -- Strips absolute paths (`/usr/bin/git` becomes `git`) while preserving arguments.\n3. **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).\n4. **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\ndenial on stdout and a colorful human-readable warning on stderr. If blocked\nunder Codex CLI 0.125.0+, dcg follows Codex's strict hook contract: no stdout\nJSON, exit code 2, and a stderr reason that Codex shows to the model. If\nallowed, dcg exits silently. Rich formatting is automatically disabled for CI,\nnon-TTY output, dumb terminals, and no-color environments.\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│            Claude Code / Gemini CLI / Copilot CLI                │\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 Code / Gemini CLI / Copilot CLI                │\n│                                                                  │\n│  If denied: Shows block message, does NOT execute command       │\n│  If allowed: Proceeds with command execution                    │\n│                                                                  │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### Context Classification System\n\nNot 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.\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` | Command words and unquoted arguments | **MUST check** - highest priority |\n| `InlineCode` | Content inside `-c`/`-e` flags (bash -c, python -c) | **MUST check** - code will be executed |\n| `Argument` | Quoted arguments to known-safe commands | Lower priority, context-dependent |\n| `Data` | Single-quoted strings (shell cannot interpolate) | **Can skip** - treated as literal data |\n| `HeredocBody` | Content inside heredocs | Escalated to Tier 2/3 heredoc scanning |\n| `Comment` | Shell comments (`# ...`) | **Skip** - never executed |\n| `Unknown` | Cannot determine context | Conservative treatment as `Executed` |\n\n**Why Context Matters**\n\nConsider these commands:\n\n```bash\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 \u003c\u003cEOF \u003e 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\n1. **Lexical Analysis**: Identify quoted strings, comments, and heredoc markers\n2. **Structural Analysis**: Build a tree of command structure, identifying pipes, subshells, and command substitutions\n3. **Flag Analysis**: Detect `-c`, `-e`, and similar flags that introduce inline code contexts\n4. **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\n## Design Principles\n\n### 1. Whitelist-First Architecture\n\nSafe 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`).\n\n```\ngit checkout -b feature    →  Matches SAFE \"checkout-new-branch\"  →  ALLOW\ngit checkout -- file.txt   →  No safe match, matches DESTRUCTIVE  →  DENY\n```\n\n### 2. Fail-Safe Defaults\n\nThe hook uses a **default-allow** policy for unrecognized commands. This ensures:\n- The hook never breaks legitimate workflows\n- Only *known* dangerous patterns are blocked\n- New git commands are allowed until explicitly categorized\n\n### 3. Zero False Negatives Philosophy\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\n### 4. Defense in Depth\n\nThis hook is one layer of protection. It complements (not replaces):\n- Regular commits and pushes\n- Git stash before risky operations\n- Proper backup strategies\n- Code review processes\n\n### 5. Minimal Latency\n\nEvery Bash command passes through this hook. Performance is critical:\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\n## Pattern Matching System\n\n### Safe Patterns (Whitelist)\n\nThe safe pattern list contains 34 patterns covering:\n\n| Category | Patterns | Purpose |\n|----------|----------|---------|\n| Branch creation | `checkout -b`, `checkout --orphan` | Creating branches is safe |\n| Staged-only | `restore --staged`, `restore -S` | Unstaging doesn't touch working tree |\n| Dry run | `clean -n`, `clean --dry-run` | Preview mode, no actual deletion |\n| Temp cleanup | `rm -rf /tmp/*`, `rm -rf /var/tmp/*` | Ephemeral directories are safe |\n| Variable expansion | `rm -rf $TMPDIR/*`, `rm -rf ${TMPDIR}/*` | Shell variable forms |\n| Quoted paths | `rm -rf \"$TMPDIR/*\"` | Quoted variable forms |\n| Separate flags | `rm -r -f /tmp/*`, `rm -r -f $TMPDIR/*` | Flag ordering variants |\n| Long flags | `rm --recursive --force /tmp/*`, `$TMPDIR/*` | GNU-style long options |\n\n### Destructive Patterns (Blacklist)\n\nThe destructive pattern list contains 16 patterns covering:\n\n| Category | Pattern | Reason |\n|----------|---------|--------|\n| Work destruction | `reset --hard`, `reset --merge` | Destroys uncommitted changes |\n| File reversion | `checkout -- \u003cpath\u003e` | Discards file modifications |\n| Worktree restore | `restore` (without --staged) | Discards uncommitted changes |\n| Untracked deletion | `clean -f` | Permanently removes untracked files |\n| History rewrite | `push --force`, `push -f` | Can destroy remote commits |\n| Unsafe branch delete | `branch -D` | Force-deletes without merge check |\n| Stash destruction | `stash drop`, `stash clear` | Permanently deletes stashed work |\n| Filesystem nuke | `rm -rf` (non-temp paths) | Recursive deletion outside temp |\n\n### Pattern Syntax\n\nPatterns use [fancy-regex](https://github.com/fancy-regex/fancy-regex) for advanced features:\n\n```rust\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## Edge Cases Handled\n\n### Path Normalization\n\nCommands may use absolute paths to binaries:\n\n```bash\n/usr/bin/git reset --hard          # Blocked ✓\n/usr/local/bin/git checkout -- .   # Blocked ✓\n/bin/rm -rf /home/user             # Blocked ✓\n```\n\nThe normalizer uses regex to strip paths while preserving arguments:\n\n```bash\ngit add /usr/bin/something         # \"/usr/bin/something\" is an argument, preserved\n```\n\n### Flag Ordering Variants\n\nThe `rm` command accepts flags in many forms:\n\n```bash\nrm -rf /path          # Combined flags\nrm -fr /path          # Reversed order\nrm -r -f /path        # Separate flags\nrm -f -r /path        # Separate, reversed\nrm --recursive --force /path    # Long flags\nrm --force --recursive /path    # Long flags, reversed\nrm -rf --no-preserve-root /     # Additional flags\n```\n\nAll variants are handled by flexible regex patterns.\n\n### Shell Variable Expansion\n\nTemp directory variables come in multiple forms:\n\n```bash\nrm -rf $TMPDIR/build           # Unquoted, simple\nrm -rf ${TMPDIR}/build         # Unquoted, braced\nrm -rf \"$TMPDIR/build\"         # Quoted, simple\nrm -rf \"${TMPDIR}/build\"       # Quoted, braced\nrm -rf \"${TMPDIR:-/tmp}/build\" # With default value\n```\n\n### Git Flag Combinations\n\nGit commands can have flags in various positions:\n\n```bash\ngit push --force                  # Blocked ✓\ngit push origin main --force      # Blocked ✓\ngit push --force origin main      # Blocked ✓\ngit push -f                       # Blocked ✓\ngit push --force-with-lease       # Allowed ✓ (safe alternative)\n```\n\n### Staged vs Worktree Restore\n\nThe restore command has nuanced safety:\n\n```bash\ngit restore --staged file.txt           # Allowed ✓ (unstaging only)\ngit restore -S file.txt                 # Allowed ✓ (short flag)\ngit restore file.txt                    # Blocked (discards changes)\ngit restore --worktree file.txt         # Blocked (explicit worktree)\ngit restore --staged --worktree file    # Blocked (includes worktree)\ngit restore -S -W file.txt              # Blocked (includes worktree)\n```\n\n## Performance Optimizations\n\n### Dual Regex Engine Architecture\n\ndcg uses a sophisticated dual-engine regex system that automatically selects the optimal engine for each pattern. This enables both guaranteed performance and advanced pattern matching features.\n\n**The Two Engines**:\n\n| Engine | Crate | Time Complexity | Features | Use Case |\n|--------|-------|-----------------|----------|----------|\n| **Linear** | `regex` | O(n) guaranteed | Basic regex, character classes, alternation | ~85% of patterns |\n| **Backtracking** | `fancy_regex` | O(2^n) worst case | Lookahead, lookbehind, backreferences | ~15% of patterns |\n\n**Automatic Engine Selection**:\n\nWhen a pattern is compiled, dcg analyzes it to determine which engine to use:\n\n```rust\npub enum CompiledRegex {\n    Linear(regex::Regex),           // O(n) guaranteed, no lookahead\n    Backtracking(fancy_regex::Regex), // Supports lookahead/lookbehind\n}\n\nimpl CompiledRegex {\n    pub fn new(pattern: \u0026str) -\u003e Result\u003cSelf, Error\u003e {\n        // Try linear engine first (faster, predictable)\n        if let Ok(re) = regex::Regex::new(pattern) {\n            return Ok(CompiledRegex::Linear(re));\n        }\n        // Fall back to backtracking for advanced features\n        Ok(CompiledRegex::Backtracking(fancy_regex::Regex::new(pattern)?))\n    }\n}\n```\n\n**Why This Matters**:\n\n1. **Performance predictability**: The linear engine guarantees O(n) matching time, critical for a hook that runs on every command\n2. **Feature completeness**: Some patterns require negative lookahead (e.g., \"match `--force` but not `--force-with-lease`\")\n3. **Automatic optimization**: Pattern authors don't need to think about engine selection—dcg chooses optimally\n\n**Examples of Engine Selection**:\n\n```rust\n// Linear engine (simple pattern)\nr\"git\\s+reset\\s+--hard\"              // No advanced features needed\n\n// Backtracking engine (negative lookahead)\nr\"git\\s+push\\s+.*--force(?![-a-z])\"  // Must NOT be followed by \"-with-lease\"\n\n// Linear engine (character classes)\nr\"rm\\s+-[a-zA-Z]*[rR][a-zA-Z]*f\"     // Complex but no lookahead\n```\n\n### Performance Budget System\n\ndcg operates under strict latency constraints - every Bash command passes through the hook, so even small delays compound into noticeable sluggishness. `src/perf.rs` is the source of truth for performance budgets, CI benchmark expectations, and hook-mode fail-open deadlines.\n\n**Latency Tiers**:\n\n| Tier | Path | Target | Warning Above | Panic Above |\n|------|------|--------|---------------|-------------|\n| 0 | Quick reject | \u003c 1μs | \u003e 5μs | \u003e 50μs |\n| 1 | Fast path | \u003c 75μs | \u003e 150μs | \u003e 500μs |\n| 2 | Pattern match | \u003c 100μs | \u003e 250μs | \u003e 1ms |\n| 3 | Heredoc trigger | \u003c 5μs | \u003e 10μs | \u003e 100μs |\n| 4 | Heredoc extract | \u003c 200μs | \u003e 500μs | \u003e 2ms |\n| 5 | Language detect | \u003c 20μs | \u003e 50μs | \u003e 200μs |\n| 6 | Full heredoc pipeline | \u003c 5ms | \u003e 15ms | \u003e 20ms |\n\nHook mode also has an absolute 200ms deadline. If that deadline is exhausted, expensive analysis fails open so dcg does not hang an interactive workflow.\n\n**Fail-Open Behavior**:\n\nIf any stage exceeds its panic threshold, dcg logs a warning and **allows the command**:\n\n```\n[WARN] Performance budget exceeded: Tier 2 (safe patterns) took 1.2ms (panic threshold: 500μs)\n[WARN] Failing open to avoid blocking workflow\n```\n\nThis design ensures that:\n1. A pathological input cannot hang the user's terminal\n2. Performance regressions are visible in logs\n3. The tool never becomes a productivity bottleneck\n\n**Budget Enforcement**:\n\n```rust\nlet deadline = Deadline::fail_open_default();\n\nif deadline.is_exceeded() || !deadline.has_budget_for(\u0026PATTERN_MATCH) {\n    return EvaluationResult::allowed_due_to_budget();\n}\n```\n\n**Monitoring Performance**:\n\nUse `dcg explain --verbose` to see per-stage timing:\n\n```\nEvaluation Trace:\n  [  0.3μs] Tier 0: Quick reject (PASS - below 1μs target)\n  [  8.7μs] Tier 1: Fast path (PASS - below 75μs target)\n  [ 15.2μs] Tier 2: Pattern match (PASS - below 100μs target)\n  [ 15.4μs] Total: 15.4μs (PASS - below 5ms target)\n```\n\n### Keyword-Based Pack Pre-filtering\n\nBefore expensive regex matching, dcg uses a multi-level keyword filtering system to quickly skip irrelevant packs. This is critical for performance—with 50+ packs available, checking every pattern against every command would be prohibitively slow.\n\n**How Keyword Filtering Works**:\n\nEach pack declares a set of keywords that must appear in a command for that pack to be relevant:\n\n```rust\nPack {\n    id: \"database.postgresql\".to_string(),\n    keywords: \u0026[\"psql\", \"dropdb\", \"createdb\", \"DROP\", \"TRUNCATE\", \"DELETE\"],\n    // ...\n}\n```\n\n**Two-Level Filtering**:\n\n1. **Global Quick Reject**: Before any pack evaluation, dcg checks if the command contains *any* keyword from *any* enabled pack. If not, the entire pack evaluation is skipped.\n\n2. **Per-Pack Quick Reject**: For each enabled pack, dcg checks if the command contains any of that pack's keywords before running expensive regex patterns.\n\n**Aho-Corasick Automaton**:\n\nFor packs with multiple keywords, dcg builds an [Aho-Corasick automaton](https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm) that matches all keywords in a single O(n) pass:\n\n```rust\n// Built lazily on first pack access\npub keyword_matcher: Option\u003caho_corasick::AhoCorasick\u003e,\n\npub fn might_match(\u0026self, cmd: \u0026str) -\u003e bool {\n    if self.keywords.is_empty() {\n        return true; // No keywords = always check patterns\n    }\n\n    // O(n) matching regardless of keyword count\n    if let Some(ref ac) = self.keyword_matcher {\n        return ac.is_match(cmd);\n    }\n\n    // Fallback: sequential memchr search\n    self.keywords.iter()\n        .any(|kw| memmem::find(cmd.as_bytes(), kw.as_bytes()).is_some())\n}\n```\n\n**Context-Aware Keyword Matching**:\n\nKeywords are only matched within executable spans (not in comments, quoted strings, or data):\n\n```rust\npub fn pack_aware_quick_reject(cmd: \u0026str, enabled_keywords: \u0026[\u0026str]) -\u003e bool {\n    // First: fast substring check\n    let any_substring = enabled_keywords.iter()\n        .any(|kw| memmem::find(cmd.as_bytes(), kw.as_bytes()).is_some());\n\n    if !any_substring {\n        return true; // Safe to skip all pack evaluation\n    }\n\n    // Second: verify keyword appears in executable context\n    let spans = classify_command(cmd);\n    for span in spans.executable_spans() {\n        if span_matches_any_keyword(span.text(cmd), enabled_keywords) {\n            return false; // Must evaluate packs\n        }\n    }\n\n    true // Keywords only in non-executable contexts, safe to skip\n}\n```\n\nThis approach ensures that a command like `echo \"psql\" | grep DROP` doesn't trigger PostgreSQL pack evaluation just because keywords appear in the data being processed.\n\n### 1. Lazy Static Initialization\n\nRegex patterns are compiled once on first use via `LazyLock`:\n\n```rust\nstatic SAFE_PATTERNS: LazyLock\u003cVec\u003cPattern\u003e\u003e = LazyLock::new(|| {\n    vec![\n        pattern!(\"checkout-new-branch\", r\"git\\s+checkout\\s+-b\\s+\"),\n        // ... 33 more patterns\n    ]\n});\n```\n\nSubsequent invocations reuse the compiled patterns with zero compilation overhead.\n\n### 2. SIMD-Accelerated Quick Rejection\n\nBefore any regex matching, a SIMD-accelerated substring search filters out irrelevant commands. The [memchr](https://github.com/BurntSushi/memchr) crate uses CPU vector instructions (SSE2, AVX2, NEON) when available:\n\n```rust\nuse memchr::memmem;\n\nstatic GIT_FINDER: LazyLock\u003cmemmem::Finder\u003c'static\u003e\u003e = LazyLock::new(|| memmem::Finder::new(\"git\"));\nstatic RM_FINDER: LazyLock\u003cmemmem::Finder\u003c'static\u003e\u003e = LazyLock::new(|| memmem::Finder::new(\"rm\"));\n\nfn quick_reject(cmd: \u0026str) -\u003e bool {\n    let bytes = cmd.as_bytes();\n    GIT_FINDER.find(bytes).is_none() \u0026\u0026 RM_FINDER.find(bytes).is_none()\n}\n```\n\nFor commands like `ls -la`, `cargo build`, or `npm install`, this check short-circuits the entire matching pipeline. The `memmem::Finder` is pre-compiled once and reused, avoiding repeated setup costs.\n\n### 3. Early Exit on Safe Match\n\nSafe patterns are checked first. On match, the function returns immediately without checking destructive patterns:\n\n```rust\nfor pattern in SAFE_PATTERNS.iter() {\n    if pattern.regex.is_match(\u0026normalized).unwrap_or(false) {\n        return;  // Allow immediately\n    }\n}\n```\n\n### 4. Compile-Time Pattern Validation\n\nThe `pattern!` and `destructive!` macros include the pattern name in panic messages, making invalid patterns fail at first execution with clear diagnostics:\n\n```rust\nmacro_rules! pattern {\n    ($name:literal, $re:literal) =\u003e {\n        Pattern {\n            regex: Regex::new($re).expect(concat!(\"pattern '\", $name, \"' should compile\")),\n            name: $name,\n        }\n    };\n}\n```\n\n### 5. Zero-Copy JSON Parsing\n\nThe `serde_json` parser operates on the input buffer without unnecessary copies. The command string is extracted directly from the parsed JSON value.\n\n### 6. Zero-Allocation Path Normalization\n\nCommand normalization uses `Cow\u003cstr\u003e` (copy-on-write) to avoid heap allocations in the common case:\n\n```rust\nfn normalize_command(cmd: \u0026str) -\u003e Cow\u003c'_, str\u003e {\n    // Fast path: if command doesn't start with '/', no normalization needed\n    if !cmd.starts_with('/') {\n        return Cow::Borrowed(cmd);  // Zero allocation\n    }\n    PATH_NORMALIZER.replace(cmd, \"$1\")  // Allocation only when path is stripped\n}\n```\n\nMost commands don't use absolute paths to `git` or `rm`, so this fast path avoids allocation entirely for 99%+ of inputs.\n\n### 7. Release Profile Optimization\n\nThe release build uses aggressive optimization settings:\n\n```toml\n[profile.release]\nopt-level = \"z\"     # Optimize for size (lean binary)\nlto = true          # Link-time optimization across crates\ncodegen-units = 1   # Single codegen unit for better optimization\npanic = \"abort\"     # Smaller binary, no unwinding overhead\nstrip = true        # Remove debug symbols\n```\n\n## Example Block Message\n\nWhen a destructive command is intercepted, the hook outputs a colorful warning to stderr (shown below without ANSI codes):\n\n```\n════════════════════════════════════════════════════════════════════════\nBLOCKED  dcg\n────────────────────────────────────────────────────────────────────────\nReason:  git reset --hard destroys uncommitted changes. Use 'git stash' first.\n\nCommand:  git reset --hard HEAD~1\n\nTip: If you need to run this command, execute it manually in a terminal.\n     Consider using 'git stash' first to save your changes.\n════════════════════════════════════════════════════════════════════════\n```\n\n## Output Modes\n\ndcg separates agent-facing data from human-facing display. This lets agents\nparse stable output while people watching the terminal still get readable,\nhigh-signal formatting.\n\n| Mode | Trigger | stdout | stderr |\n|------|---------|--------|--------|\n| Hook allow | Safe command | Empty | Empty |\n| JSON-hook deny | Claude Code, Gemini CLI, Copilot CLI, compatible hooks | Denial JSON | Rich or plain warning |\n| Codex deny | Codex CLI 0.125.0+ hook input | Empty | Deny reason with command, rule, and remediation |\n| Robot mode | `--robot` or `DCG_ROBOT=1` | JSON | Silent |\n| Plain fallback | `DCG_NO_RICH=1`, `NO_COLOR=1`, `DCG_NO_COLOR=1`, `TERM=dumb`, `CI=1`, non-TTY output, or `--legacy-output` | Mode-specific data | Plain text only |\n\n### Rich Human Output\n\nRich output is for humans and always belongs on stderr. It includes the blocked\ncommand, severity, rule id, pack id, explanation, and safer alternatives when\navailable:\n\n```text\nBLOCKED  dcg\nReason:  git reset --hard destroys uncommitted changes\nRule:    core.git:reset-hard\nCommand: git reset --hard HEAD~1\nTip:     Use git stash to save your changes first.\n```\n\n### Plain and No-Color Output\n\nUse plain output for logs, terminals with limited capabilities, or tests that\nassert exact strings:\n\n```bash\nDCG_NO_RICH=1 dcg test \"git reset --hard HEAD\"\nNO_COLOR=1 dcg explain \"rm -rf ./build\"\nTERM=dumb dcg scan .\n```\n\n### Build Features\n\nRich terminal output is enabled by default. For a lean build without the\n`rich_rust` dependency, compile with:\n\n```bash\ncargo build --release --no-default-features\n```\n\n### Agent JSON Output\n\nFor automation, prefer robot mode or the hook protocol your agent expects:\n\n```bash\n# Robot-mode scripting: parse stdout JSON, ignore stderr.\ndcg --robot test \"rm -rf /\" \u003edecision.json 2\u003e/dev/null\n\n# Claude-compatible hook integration: parse stdout only when non-empty.\ndcg \u003c hook-input.json \u003ehook-output.json 2\u003ehuman-warning.txt\n```\n\nCodex integrations should treat exit code 2 plus non-empty stderr as a deny.\n\n### Suggestion System\n\ndcg doesn't just block commands—it provides actionable guidance to help users make safer choices. The suggestion system generates context-aware recommendations based on the specific command that was blocked.\n\n**Suggestion Categories**:\n\n| Category | Purpose | Example |\n|----------|---------|---------|\n| `PreviewFirst` | Run a dry-run/preview command first | \"Run `git clean -n` first to preview deletions\" |\n| `SaferAlternative` | Use a safer command that achieves similar goals | \"Use `--force-with-lease` instead of `--force`\" |\n| `WorkflowFix` | Fix the workflow to avoid the dangerous operation | \"Commit your changes before resetting\" |\n| `Documentation` | Link to relevant documentation | \"See `man git-reset` for reset options\" |\n| `AllowSafely` | How to allowlist if the operation is intentional | \"Add to allowlist: `dcg allowlist add core.git:reset-hard`\" |\n\n**Contextual Suggestions by Command Type**:\n\n| Command Type | Suggestion |\n|-------------|------------|\n| `git reset`, `git checkout --` | \"Consider using 'git stash' first to save your changes.\" |\n| `git clean` | \"Use 'git clean -n' first to preview what would be deleted.\" |\n| `git push --force` | \"Consider using '--force-with-lease' for safer force pushing.\" |\n| `rm -rf` | \"Verify the path carefully before running rm -rf manually.\" |\n| `kubectl delete` | \"Use `kubectl delete --dry-run=client` to preview deletions.\" |\n| `docker system prune` | \"Run with `--dry-run` first to see what would be removed.\" |\n| `DROP TABLE` | \"Consider `TRUNCATE` if you only need to remove data, not the schema.\" |\n\n**Custom Suggestions in Packs**:\n\nEach destructive pattern can specify its own suggestion tailored to the specific operation:\n\n```rust\ndestructive_pattern!(\n    \"restic-forget\",\n    r\"restic(?:\\s+--?\\S+(?:\\s+\\S+)?)*\\s+forget\\b\",\n    \"restic forget removes snapshots and can permanently delete backup data.\",\n    suggestion: \"Run 'restic snapshots' first to review what would be affected.\"\n)\n```\n\nThis approach ensures that suggestions are always relevant to the specific context, not generic warnings.\n\nSimultaneously, the hook outputs JSON to stdout for the Claude Code protocol:\n\n```json\n{\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"PreToolUse\",\n    \"permissionDecision\": \"deny\",\n    \"permissionDecisionReason\": \"BLOCKED by dcg\\n\\nReason: ...\"\n  }\n}\n```\n\n## Security Considerations\n\n### What This Protects Against\n\n- **Accidental data loss**: AI agents running `git checkout --` or `git reset --hard` on files with uncommitted changes\n- **Remote history destruction**: Force pushes that overwrite shared branch history\n- **Stash loss**: Dropping or clearing stashes containing important work-in-progress\n- **Filesystem accidents**: Recursive deletion outside designated temp directories\n\n### Inherent Limitations\n\nWhile dcg provides comprehensive protection across many tools and platforms, some attack vectors are inherently difficult or impossible to protect against:\n- **Malicious actors**: A determined attacker can bypass this hook\n- **Non-Bash commands**: Direct file writes via Python/JavaScript, API calls, etc. are not intercepted\n- **Committed but unpushed work**: The hook doesn't prevent loss of local-only commits\n- **Bugs in allowed commands**: A `git commit` that accidentally includes wrong files\n- **Commands in scripts**: If an agent runs `./deploy.sh`, we don't inspect what's inside the script\n\n### Threat Model\n\nThis hook assumes the AI agent is **well-intentioned but fallible**. It's designed to catch honest mistakes, not adversarial attacks. The hook runs with the same permissions as the Claude Code process.\n\n## Troubleshooting\n\n### Hook not blocking commands\n\n1. **Check hook registration**: Verify `~/.claude/settings.json` contains the hook configuration\n2. **Restart Claude Code**: Configuration changes require a restart\n3. **Check binary location**: Ensure `dcg` is in your PATH\n4. **Test manually**: Run `echo '{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"git reset --hard\"}}' | dcg`\n\n### Hook silently removed (recommended: add shell startup check)\n\nClaude Code can silently remove the dcg hook when it rewrites `~/.claude/settings.json`. This means you may lose protection without any warning.\n\n**Automatic setup** -- `dcg setup` installs the hook *and* offers to add a shell startup check:\n\n```bash\ndcg setup               # Interactive — prompts before modifying RC files\ndcg setup --shell-check # Non-interactive — adds the check automatically\n```\n\n**Manual setup** -- add this snippet to your `~/.zshrc` and/or `~/.bashrc`:\n\n```bash\n# dcg: warn if hook was silently removed from Claude Code settings\nif command -v dcg \u0026\u003e/dev/null \u0026\u0026 command -v jq \u0026\u003e/dev/null; then\n  if [ -f \"$HOME/.claude/settings.json\" ] \u0026\u0026 \\\n     ! jq -e '.hooks.PreToolUse[]? | select(.hooks[]?.command | test(\"dcg$\"))' \\\n       \"$HOME/.claude/settings.json\" \u0026\u003e/dev/null; then\n    printf '\\033[1;33m[dcg] Hook missing from ~/.claude/settings.json — run: dcg install\\033[0m\\n'\n  fi\nfi\n```\n\nThis check:\n- Runs in milliseconds (no noticeable shell startup delay)\n- Is completely silent when the hook is present\n- Shows a yellow warning only when the hook is missing\n- Gracefully skips if `dcg`, `jq`, or `settings.json` are absent\n- Works identically in bash and zsh\n\n\u003e **Note:** The `install.sh` installer also offers to add this check during installation.\n\n### Hook blocking safe commands\n\n1. **Check for false positives**: Some edge cases may not be covered by safe patterns\n2. **File an issue**: Report the command that was incorrectly blocked\n3. **Temporary bypass**: Have the user run the command manually in a separate terminal\n4. **Add to allowlist**: Use the allowlist feature below for persistent overrides\n\n### Resolving False Positives with Allowlists\n\nIf dcg blocks a command that is safe in your specific context, you can add it to an allowlist. Allowlists support three layers (checked in order):\n\n1. **Project** (`.dcg/allowlist.toml`): Applies only to the current project\n2. **User** (`~/.config/dcg/allowlist.toml`): Applies to all your projects\n3. **System** (`/etc/dcg/allowlist.toml`): Applies system-wide\n\n**Adding a rule to the allowlist:**\n\n```bash\n# Allow a specific rule by ID (recommended)\ndcg allowlist add core.git:reset-hard -r \"Used for CI cleanup\"\n\n# Allow at project level (default if in a git repo)\ndcg allowlist add core.git:reset-hard -r \"CI cleanup\" --project\n\n# Add to user-level allowlist instead\ndcg allowlist add core.git:reset-hard -r \"Personal workflow\" --user\n\n# Allow with expiration (ISO 8601 format)\ndcg allowlist add core.git:clean-force -r \"Migration\" --expires \"2026-02-01T00:00:00Z\"\n\n# Allow a specific command (exact match) using add-command\ndcg allowlist add-command \"rm -rf ./build\" -r \"Build cleanup\"\n```\n\n**Listing allowlist entries:**\n\n```bash\n# List all entries from all layers\ndcg allowlist list\n\n# List project allowlist only\ndcg allowlist list --project\n\n# List user allowlist only\ndcg allowlist list --user\n\n# Output as JSON\ndcg allowlist list --format json\n```\n\n**Removing entries:**\n\n```bash\n# Remove a rule by ID\ndcg allowlist remove core.git:reset-hard\n\n# Remove from project allowlist specifically\ndcg allowlist remove core.git:reset-hard --project\n```\n\n**Validating allowlist files:**\n\n```bash\n# Check for issues (expired entries, invalid patterns)\ndcg allowlist validate\n\n# Strict mode: treat warnings as errors\ndcg allowlist validate --strict\n```\n\n**Pruning expired entries:**\n\n```bash\n# Preview expired entries without changing files\ndcg allowlist prune --dry-run\n\n# Remove expired entries from project/user allowlists\ndcg allowlist prune\n```\n\n**Example allowlist.toml:**\n\n```toml\n[[allow]]\nrule = \"core.git:reset-hard\"\nreason = \"Used for CI pipeline cleanup\"\nadded_at = \"2026-01-08T12:00:00Z\"\n\n[[allow]]\nexact_command = \"rm -rf ./build\"\nreason = \"Safe build directory cleanup\"\nadded_at = \"2026-01-08T12:00:00Z\"\nexpires_at = \"2026-02-08T12:00:00Z\"  # Optional expiration\n\n[[allow]]\npattern = \"rm -rf .*/build\"\nreason = \"Build directories across projects\"\nrisk_acknowledged = true  # Required for pattern-based entries\nadded_at = \"2026-01-08T12:00:00Z\"\n```\n\n### Performance issues\n\n1. **Check pattern count**: Excessive custom patterns can slow matching\n2. **Profile with `--release`**: Debug builds are significantly slower\n3. **Check stdin buffering**: Slow JSON input can delay processing\n\n## Running Tests\n\n### Unit Tests\n\n```bash\ncargo test\n```\n\nThe test suite includes 80+ tests covering:\n\n- **normalize_command_tests**: Path stripping for git and rm binaries\n- **quick_reject_tests**: Fast-path filtering for non-git/rm commands\n- **safe_pattern_tests**: Whitelist accuracy for all safe pattern variants\n- **destructive_pattern_tests**: Blacklist coverage for all dangerous commands\n- **input_parsing_tests**: JSON parsing robustness and edge cases\n- **deny_output_tests**: Output format validation\n- **integration_tests**: End-to-end pipeline verification\n\n### Test with Coverage\n\n```bash\ncargo install cargo-tarpaulin\ncargo tarpaulin --out Html\n```\n\n### End-to-End Testing\n\nThe repository includes a comprehensive E2E test script with hundreds of command scenarios:\n\n```bash\n# Run full E2E test suite\n./scripts/e2e_test.sh\n\n# With verbose output\n./scripts/e2e_test.sh --verbose\n\n# With specific binary path\n./scripts/e2e_test.sh --binary ./target/release/dcg\n```\n\nCodex CLI integration has a separate opt-in harness because it drives a real\nauthenticated `codex exec` session against hermetic temporary repositories:\n\n```bash\n# Run the real Codex CLI smoke harness\n./scripts/e2e_codex.sh --verbose --dcg-binary ./target/release/dcg\n\n# Capture JSONL trace and failure artifacts for postmortems\n./scripts/e2e_codex.sh --json --artifacts ./artifacts/codex-e2e --dcg-binary ./target/release/dcg\n```\n\nThe Codex harness exits successfully with an explicit skipped status when Codex\nis unavailable or unauthenticated, so CI and developer machines without Codex\naccess can run it without producing false failures. A full local run requires\n`codex` 0.125.0 or newer on `PATH` plus an authenticated `codex login status`;\nwhen Codex is responsive, expect roughly five minutes, with longer runtimes\npossible under rate limiting.\n\nUseful debugging flags:\n\n- `--verbose` mirrors the per-scenario logging style from `scripts/e2e_test.sh`.\n- `--artifacts DIR` writes `trace.jsonl` plus per-failure stdout, stderr,\n  prompts, repository state, manifests, and diffs.\n- `--keep-tempdirs` preserves temporary repositories and isolated Codex homes for\n  manual inspection after a failed run.\n\nCI runs `./scripts/e2e_codex.sh --verbose --json --artifacts\n/tmp/codex_e2e_artifacts` in a dedicated `codex-e2e` job on pushes to `main`\nonly. The job installs Codex with npm, authenticates from the `CODEX_API_KEY`\nsecret, and still goes green with a clear notice when Codex is unavailable,\nunauthenticated, quota-limited, or temporarily unable to reach the API.\n\nThe E2E suite covers:\n- All destructive git commands (reset, checkout, restore, clean, push, branch, stash)\n- All safe git commands (status, log, diff, add, commit, push, branch -d)\n- Filesystem commands (rm -rf with various paths and flag orderings)\n- Absolute path handling (`/usr/bin/git`, `/bin/rm`)\n- Non-Bash tools (Read, Write, Edit, Grep, Glob)\n- Malformed JSON input (empty, missing fields, invalid syntax)\n- Edge cases (sudo prefixes, quoted paths, variable expansion)\n\n## Continuous Integration\n\nThe project uses GitHub Actions for CI/CD:\n\n### CI Workflow (`.github/workflows/ci.yml`)\n\nRuns on every push and pull request:\n\n- **Formatting check**: `cargo fmt --check`\n- **Clippy lints**: `cargo clippy --all-targets -- -D warnings` (pedantic + nursery enabled)\n- **Compilation check**: `cargo check --all-targets`\n- **Unit tests**: `cargo nextest run` with JUnit XML reports\n- **Coverage**: `cargo llvm-cov` with LCOV output\n\n### Release Workflow (`.github/workflows/dist.yml`)\n\nTriggered on version tags (`v*`):\n\n- Builds optimized binaries for 5 platforms:\n  - Linux x86_64 (`x86_64-unknown-linux-gnu`)\n  - Linux ARM64 (`aarch64-unknown-linux-gnu`)\n  - macOS Intel (`x86_64-apple-darwin`)\n  - macOS Apple Silicon (`aarch64-apple-darwin`)\n  - Windows (`x86_64-pc-windows-msvc`)\n- Creates `.tar.xz` archives (Unix) or `.zip` (Windows)\n- Generates SHA256 checksums for verification\n- Publishes to GitHub Releases with auto-generated release notes\n\nTo create a release:\n\n```bash\ngit tag v0.1.0\ngit push origin v0.1.0\n```\n\n## FAQ\n\n**Q: Why block `git branch -D` but allow `git branch -d`?**\n\nThe lowercase `-d` only deletes branches that have been fully merged. The uppercase `-D` force-deletes regardless of merge status, potentially losing commits that exist only on that branch.\n\n**Q: Why is `git push --force-with-lease` allowed?**\n\nForce-with-lease is a safer alternative that refuses to push if the remote has commits you haven't seen. It prevents accidentally overwriting someone else's work.\n\n**Q: Why block all `rm -rf` outside temp directories?**\n\nRecursive forced deletion is one of the most dangerous filesystem operations. Even with good intentions, a typo or wrong variable expansion can delete critical files. Temp directories are designed to be ephemeral.\n\n**Q: Can I add custom patterns?**\n\nYes. Create YAML pack files and point to them in your config. See the [Custom Packs](#custom-packs) section and [`docs/custom-packs.md`](docs/custom-packs.md) for the schema and examples.\n\n**Q: What if I really need to run a blocked command?**\n\nSee [Escape Hatch / Bypass](#escape-hatch--bypass). Options include `DCG_BYPASS=1`, allow-once codes, permanent allowlists, or running the command manually in a separate terminal.\n\n**Q: Does this work with other AI coding tools?**\n\nYes. dcg natively supports Claude Code, Gemini CLI, and GitHub Copilot CLI hook payloads. For other tools, support depends on whether they expose a pre-execution shell hook with compatible JSON input/output.\n\n**Q: What about database, Docker, Kubernetes, and cloud commands?**\n\ndcg includes 50+ packs covering all of these. See the [Modular Pack System](#modular-pack-system) section for the full list. Enable the packs you need in your config.\n\n## Contributing\n\n*About Contributions:* Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other \"stakeholders,\" which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via `gh` and independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.\n\n## License\n\nMIT\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdicklesworthstone%2Fdestructive_command_guard","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdicklesworthstone%2Fdestructive_command_guard","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdicklesworthstone%2Fdestructive_command_guard/lists"}