[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-74695":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":22,"archived":23,"fork":23,"defaultBranch":24,"hasWiki":25,"hasPages":23,"topics":26,"createdAt":10,"pushedAt":10,"updatedAt":33,"readmeContent":34,"aiSummary":35,"trendingCount":16,"starSnapshotCount":16,"syncStatus":36,"lastSyncTime":37,"discoverSource":38},74695,"destructive_command_guard","Dicklesworthstone\u002Fdestructive_command_guard","Dicklesworthstone","The Destructive Command Guard (dcg) is for blocking dangerous git and shell commands from being executed by agents.","",null,"Rust",1107,65,3,1,0,5,19,94,15,18.46,"Other",false,"main",true,[27,28,29,30,31,32],"ai-agents","cli","developer-tools","git","rust","safety","2026-06-12 02:03:27","# dcg (Destructive Command Guard)\n\n\u003Cdiv align=\"center\">\n  \u003Cimg src=\"illustration.webp\" alt=\"Destructive Command Guard - Protecting your code from accidental destruction\">\n\u003C\u002Fdiv>\n\n\u003Cdiv align=\"center\">\n\n[![Coverage](https:\u002F\u002Fimg.shields.io\u002Fcodecov\u002Fc\u002Fgithub\u002FDicklesworthstone\u002Fdestructive_command_guard?label=coverage)](https:\u002F\u002Fcodecov.io\u002Fgh\u002FDicklesworthstone\u002Fdestructive_command_guard)\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-yellow.svg)](https:\u002F\u002Fopensource.org\u002Flicenses\u002FMIT)\n\n\u003C\u002Fdiv>\n\nA high-performance hook for AI coding agents that blocks destructive commands before they execute, protecting your work from accidental deletion across Claude Code, Codex CLI, Gemini CLI, Copilot, Cursor, Hermes Agent, Grok (xAI), and related tools.\n\n**Supported:** [Claude Code](https:\u002F\u002Fclaude.ai\u002Fcode), [Codex CLI 0.125.0+](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fcodex), [Gemini CLI](https:\u002F\u002Fgithub.com\u002Fgoogle-gemini\u002Fgemini-cli), [GitHub Copilot CLI](https:\u002F\u002Fdocs.github.com\u002Fen\u002Fcopilot\u002Fconcepts\u002Fagents\u002Fcoding-agent\u002Fabout-hooks), [Cursor IDE](https:\u002F\u002Fcursor.com), [Hermes Agent](https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent), [Grok (xAI)](https:\u002F\u002Fx.ai\u002Fnews\u002Fgrok-build-cli) (native `~\u002F.grok\u002Fhooks\u002F` plus Claude compatibility layer), [OpenCode](https:\u002F\u002Fopencode.ai) (via [community plugin](https:\u002F\u002Fgithub.com\u002Faspiers\u002Fai-config\u002Fblob\u002Fmain\u002F.config\u002Fopencode\u002Fplugins\u002Fdcg-guard.js)), [Aider](https:\u002F\u002Faider.chat\u002F) (limited—git hooks only), [Continue](https:\u002F\u002Fcontinue.dev) (detection only)\n\n\u003Cdiv align=\"center\">\n\u003Ch3>Quick Install\u003C\u002Fh3>\n\n```bash\ncurl -fsSL \"https:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh?$(date +%s)\" | bash -s -- --easy-mode\n```\n\n\u003Cp>\u003Cem>Works on Linux, macOS, and Windows (WSL). Auto-detects your platform, downloads the right binary, and configures supported agent hooks including Claude Code, Codex CLI, Gemini CLI, GitHub Copilot CLI, Cursor IDE, Hermes Agent, and Grok (xAI) (via \u003Ccode>dcg install --grok\u003C\u002Fcode> for a native \u003Ccode>~\u002F.grok\u002Fhooks\u002Fdcg.json\u003C\u002Fcode>, or via the Claude compatibility layer automatically picked up by Grok).\u003C\u002Fem>\u003C\u002Fp>\n\u003C\u002Fdiv>\n\n---\n\n## TL;DR\n\n**The Problem**: AI coding agents (Claude, Codex, Gemini, Copilot, etc.) occasionally run catastrophic commands like `git reset --hard`, `rm -rf .\u002Fsrc`, 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\u002Ffilesystem commands out of the box |\n| **50+ Security Packs** | Databases, Kubernetes, Docker, AWS\u002FGCP\u002FAzure, Terraform, and more |\n| **Sub-Millisecond Latency** | SIMD-accelerated filtering—you won't notice it's there |\n| **Heredoc\u002FInline 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 \u002F` (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| **Native Codex Support** | Codex CLI 0.125.0+ uses the strict exit-code-2 + stderr denial path Codex expects |\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# ~\u002F.config\u002Fdcg\u002Fconfig.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\u002Fagents.md](docs\u002Fagents.md) for full documentation on supported agents,\ntrust levels, and configuration options.\n\n### Codex Support\n\ndcg now treats Codex CLI as a first-class hook target, not just a Claude-shaped\ncompatibility path. The installer configures Codex CLI 0.125.0+ automatically\nwhen it detects `codex` on `PATH` or an existing `~\u002F.codex\u002F` directory.\n\n| Codex behavior | dcg handling |\n|----------------|--------------|\n| Hook config | Merges a `PreToolUse` Bash hook into `~\u002F.codex\u002Fhooks.json` |\n| Denied command | Exits with code 2, writes the block reason to stderr, and writes no stdout JSON |\n| Allowed command | Exits 0 with empty stdout and stderr |\n| Existing hooks | Preserves coexisting hooks, keeps dcg first for Bash, and refuses to overwrite malformed JSON |\n| Validation | Covered by subprocess protocol tests plus an opt-in real Codex E2E harness |\n\nCodex's hook input is intentionally close to Claude Code's, but Codex rejects\nunknown fields in hook output. dcg detects Codex payloads from the non-empty\n`turn_id` field and switches to Codex's documented stderr denial path so a\nblocked command is reported as blocked rather than as a failed hook. See\n[docs\u002Fcodex-integration.md](docs\u002Fcodex-integration.md) for protocol details,\nmanual probes, and troubleshooting.\n\n---\n\n## Origins & 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:\u002F\u002Fgithub.com\u002FDicklesworthstone)** - Original concept and Python implementation ([source](https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fmisc_coding_agent_tips_and_scripts\u002Fblob\u002Fmain\u002FDESTRUCTIVE_GIT_COMMAND_CLAUDE_HOOKS_SETUP.md)); substantially expanded the Rust version with the modular pack system (50+ security packs), heredoc\u002Finline-script scanning, the three-tier architecture, context classification, allowlists, scan mode, and the dual regex engine\n- **[Darin Gordon](https:\u002F\u002Fgithub.com\u002FDowwie)** - 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 \u002F 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>` |\n| **Allow-once code** | Single command | Copy the short code from the block message, run `dcg allow-once \u003Ccode>` |\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 `~\u002F.claude\u002Fsettings.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\u002Fpacks\u002FREADME.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\u002FMariaDB 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\u002Fsecret\u002Fstorage 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\u002Fparted), 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\u002Fchown on system directories.\n- `system.services` - Protects against dangerous service operations like stopping critical services and modifying init configuration.\n\n### CI\u002FCD Packs\n- `cicd.circleci` - Protects against destructive CircleCI operations like deleting contexts, removing secrets, deleting orbs\u002Fnamespaces, or removing pipelines.\n- `cicd.github_actions` - Protects against destructive GitHub Actions operations like deleting secrets\u002Fvariables or using gh api DELETE against \u002Factions endpoints.\n- `cicd.gitlab_ci` - Protects against destructive GitLab CI\u002FCD operations like deleting variables, removing artifacts, and unregistering runners.\n- `cicd.jenkins` - Protects against destructive Jenkins CLI\u002FAPI 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\u002Fsecret engines, revoking leases\u002Ftokens, 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.modal` - Protects against destructive Modal serverless platform operations like recursive volume removal, app stops with `--force`, and secret deletion.\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\u002FALB\u002FNLB) 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\u002FJetStream operations like deleting streams, consumers, key-value entries, objects, and accounts.\n- `messaging.rabbitmq` - Protects against destructive RabbitMQ operations like deleting queues\u002Fexchanges, 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\u002FAPI operations like deleting monitors and dashboards.\n- `monitoring.newrelic` - Protects against destructive New Relic CLI\u002FAPI operations like deleting entities or alerting resources.\n- `monitoring.pagerduty` - Protects against destructive PagerDuty CLI\u002FAPI operations like deleting services and schedules (which can break incident routing).\n- `monitoring.prometheus` - Protects against destructive Prometheus\u002FGrafana operations like deleting time series data or dashboards\u002Fdatasources.\n- `monitoring.splunk` - Protects against destructive Splunk CLI\u002FAPI operations like index removal and REST API DELETE calls.\n\n### Payment Packs\n- `payment.braintree` - Protects against destructive Braintree\u002FPayPal payment operations like deleting customers or cancelling subscriptions via API\u002FSDK calls.\n- `payment.square` - Protects against destructive Square CLI\u002FAPI operations like deleting catalog objects or customers (which can break payment flows).\n- `payment.stripe` - Protects against destructive Stripe CLI\u002FAPI 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\u002Fsynonyms, 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 `~\u002F.config\u002Fdcg\u002Fconfig.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\u002FCD\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    \"~\u002F.config\u002Fdcg\u002Fpacks\u002F*.yaml\",      # User packs\n    \".dcg\u002Fpacks\u002F*.yaml\",               # Project-local packs\n]\n```\n\nFor detailed pack authoring guide, schema reference, and examples, see [`docs\u002Fcustom-packs.md`](docs\u002Fcustom-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` \u002F `--no-heredoc-scan`\n- `--heredoc-timeout \u003Cms>`\n- `--heredoc-languages \u003Clang1,lang2,...>`\n\nHeredoc documentation:\n\n- `docs\u002Fadr-001-heredoc-scanning.md` (architecture and rationale)\n- `docs\u002Fpatterns.md` (pattern authoring + inventory)\n- `docs\u002Fsecurity.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\u002FTimeout ──► 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> = LazyLock::new(|| {\n    RegexSet::new([\n        r\"\u003C\u003C-?\\s*(?:['\\x22][^'\\x22]*['\\x22]|[\\w.-]+)\",  \u002F\u002F Heredocs\n        r\"\u003C\u003C\u003C\",                                          \u002F\u002F Here-strings\n        r\"\\bpython[0-9.]*\\b.*\\s+-[A-Za-z]*[ce]\",        \u002F\u002F python -c\u002F-e\n        r\"\\bruby[0-9.]*\\b.*\\s+-[A-Za-z]*e\",             \u002F\u002F ruby -e\n        r\"\\bnode(js)?[0-9.]*\\b.*\\s+-[A-Za-z]*[ep]\",     \u002F\u002F node -e\u002F-p\n        r\"\\b(sh|bash|zsh)\\b.*\\s+-[A-Za-z]*c\",           \u002F\u002F bash -c\n        \u002F\u002F ... 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\u002Fast-grep) and matched against structural patterns:\n\n```rust\n\u002F\u002F 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(&content.content);\n    for inner in inner_commands {\n        \u002F\u002F Re-evaluate inner command against all packs\n        if let Some(result) = evaluate_command(&inner, ...) {\n            if result.decision == Deny {\n                return result; \u002F\u002F 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\u002Fsub-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=\u002Fpath\u002Fto\u002Fconfig.toml`: use explicit config file\n- `DCG_HEREDOC_ENABLED=true|false`: enable\u002Fdisable 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 (~\u002F.config\u002Fdcg\u002Fconfig.toml)\n5. System Config (\u002Fetc\u002Fdcg\u002Fconfig.toml)\n6. Compiled Defaults                              [LOWEST PRIORITY]\n\n### Accessibility & Themes\n\ndcg supports colorblind-safe palettes and high-contrast output. Colors are always paired\nwith symbols\u002Flabels to avoid conveying meaning by color alone.\n\n```toml\n[output]\nhigh_contrast = true       # ASCII borders + black\u002Fwhite 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 | `\u002Fetc\u002Fdcg\u002Fconfig.toml` | Organization-wide defaults |\n| User | `~\u002F.config\u002Fdcg\u002Fconfig.toml` | Personal preferences |\n| Project | `.dcg.toml` (repo root) | Project-specific settings |\n| Explicit | `DCG_CONFIG=\u002Fpath\u002Fto\u002Ffile` | Testing or override |\n\n**Merging Behavior**:\n\nConfiguration layers are merged additively, with higher-priority sources overriding specific fields:\n\n```rust\n\u002F\u002F Only fields explicitly set in higher-priority configs override\n\u002F\u002F Missing fields retain values from lower-priority sources\nfn merge_layer(&mut self, other: ConfigLayer) {\n    if let Some(verbose) = other.general.verbose {\n        self.general.verbose = verbose;  \u002F\u002F Override if present\n    }\n    \u002F\u002F Unset fields retain previous values\n}\n```\n\nThis means you can set organization defaults in `\u002Fetc\u002Fdcg\u002Fconfig.toml`, personal preferences in `~\u002F.config\u002Fdcg\u002Fconfig.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.\"\u002Fhome\u002Fuser\u002Fwork\u002Fproduction-api\"]\npacks = { enabled = [\"database.postgresql\", \"cloud.aws\"], disabled = [] }\n\n[projects.\"\u002Fhome\u002Fuser\u002Fpersonal\u002Fexperiments\"]\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> = 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        \u002F\u002F ... 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:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh?$(date +%s)\" | bash -s -- --easy-mode\n```\n\nEasy mode auto-detects your platform, downloads the right binary, verifies SHA256 checksums, configures all supported AI agent hooks (Claude Code, Codex CLI, Gemini CLI, GitHub Copilot CLI, Cursor IDE, Hermes Agent, Aider), and updates your PATH. For Codex CLI 0.125.0+, the installer merges a `PreToolUse` Bash hook into `~\u002F.codex\u002Fhooks.json`; invalid JSON or malformed existing Codex hook shapes are left unchanged and reported instead of being overwritten.\n\n**Other options:**\n\nInteractive mode (prompts for each step):\n\n```bash\ncurl -fsSL \"https:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh?$(date +%s)\" | bash\n```\n\nInstall specific version:\n\n```bash\ncurl -fsSL \"https:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh?$(date +%s)\" | bash -s -- --version v0.5.0\n```\n\nInstall to \u002Fusr\u002Flocal\u002Fbin (system-wide, requires sudo):\n\n```bash\ncurl -fsSL \"https:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh?$(date +%s)\" | sudo bash -s -- --system\n```\n\nBuild from source instead of downloading binary:\n\n```bash\ncurl -fsSL \"https:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh?$(date +%s)\" | bash -s -- --from-source\n```\n\nDownload\u002Finstall only (skip agent hook configuration):\n\n```bash\ncurl -fsSL \"https:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh?$(date +%s)\" | bash -s -- --no-configure\n```\n\n> **Note:** If you have [gum](https:\u002F\u002Fgithub.com\u002Fcharmbracelet\u002Fgum) 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>\n\u003Csummary>Agent-specific notes\u003C\u002Fsummary>\n\n- **Aider:** No PreToolUse-style interception. The installer enables `git-commit-verify: true` in `~\u002F.aider.conf.yml` so git hooks run. For full protection, install dcg as a [git pre-commit hook](docs\u002Fscan-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\u002Fscan-precommit-guide.md) instead.\n- **Codex CLI:** PreToolUse hooks via `~\u002F.codex\u002Fhooks.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 and switches to Codex's documented stderr deny path with exit code 2; the block message goes to stderr where Codex shows it to the model, without self-service allowlist or allow-once commands. The Unix installer and `install.ps1` both merge dcg's hook into the existing hooks object, detect an already-current dcg hook exactly, leave invalid JSON or malformed hook shapes untouched, and surface the failure reason in the install summary. `uninstall.sh` and `uninstall.ps1` remove only dcg-owned Codex hooks and preserve coexisting entries. See the [Codex integration notes](docs\u002Fcodex-integration.md). Caveat: the model can still write scripts to disk to bypass hook-based blocking.\n- **GitHub Copilot CLI:** Hooks are repository-local (`.github\u002Fhooks\u002F*.json`). Run the installer from each repository where you want protection. The generated hook covers both Unix `bash` and Windows `powershell` tool payloads.\n- **Cursor IDE:** Hooks are configured through `~\u002F.cursor\u002Fhooks.json` plus a generated `~\u002F.cursor\u002Fhooks\u002Fdcg-pre-shell.py` bridge. The installer inserts dcg first in `beforeShellExecution`, collapses duplicate dcg entries, and preserves coexisting Cursor hooks.\n- **Hermes Agent:** [NousResearch's Hermes Agent](https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent) declares shell hooks in `~\u002F.hermes\u002Fconfig.yaml` under `hooks.pre_tool_call`. The installer merges a single `matcher: \"terminal\"` entry that invokes dcg directly — no wrapper script — because Hermes' input JSON (`hook_event_name: \"pre_tool_call\"`, `tool_name: \"terminal\"`, `tool_input.command`) deserializes straight into dcg's existing `HookInput`. Hermes [explicitly documents](https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent\u002Fblob\u002Fmain\u002Fwebsite\u002Fdocs\u002Fuser-guide\u002Ffeatures\u002Fhooks.md) that \"non-zero exit codes... never abort the agent loop\", so dcg switches to Hermes' JSON block protocol on output: `{\"decision\":\"block\",\"reason\":...}` (plus the alternate `{\"action\":\"block\",\"message\":...}` form for cross-version compatibility). The installer also sets `hooks_auto_accept: true` if not already set; Hermes silently drops un-allowlisted hooks in non-TTY runs (gateway\u002Fcron) without it. `unconfigure_hermes` in `uninstall.sh` removes only the dcg-owned entry and leaves `hooks_auto_accept` alone (other Hermes hooks may rely on it).\n- **Grok (xAI):** [Grok Build \u002F Grok CLI](https:\u002F\u002Fx.ai\u002Fnews\u002Fgrok-build-cli) auto-discovers every `*.json` under `~\u002F.grok\u002Fhooks\u002F`. `dcg install --grok` writes a self-contained `~\u002F.grok\u002Fhooks\u002Fdcg.json` with a `PreToolUse` \u002F `matcher: \"Bash\"` entry — Grok internally aliases Claude-style `\"Bash\"` to its own `run_terminal_cmd` tool, so a single rule covers every shell command. dcg detects Grok at runtime from the camelCase wire shape (`hookEventName: \"pre_tool_use\"`, `toolName: \"run_terminal_cmd\"`) or from the `GROK_SESSION_ID` \u002F `GROK_HOOK_EVENT` \u002F `GROK_WORKSPACE_ROOT` environment variables, and switches its output to Grok's JSON contract: `{\"decision\":\"deny\",\"reason\":...}` (note `\"deny\"`, not Hermes' `\"block\"`). Grok also picks up dcg automatically through its `~\u002F.claude\u002Fsettings.json` compatibility layer, so existing Claude Code users get protection with no additional install step. Add `--project` to write `\u003Crepo>\u002F.grok\u002Fhooks\u002Fdcg.json` for a per-repo install (Grok requires `\u002Fhooks-trust` the first time it opens a repo with hooks).\n- **OpenCode:** Not auto-configured. Requires a Bun-based plugin with `\"tool.execute.before\"` hook key. A working community plugin: [aspiers\u002Fai-config\u002Fdcg-guard.js](https:\u002F\u002Fgithub.com\u002Faspiers\u002Fai-config\u002Fblob\u002Fmain\u002F.config\u002Fopencode\u002Fplugins\u002Fdcg-guard.js).\n\n\u003C\u002Fdetails>\n\n> **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 `~\u002F.claude\u002Fsettings.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:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fdestructive_command_guard destructive_command_guard\n```\n\n### Manual build\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fdestructive_command_guard\ncd destructive_command_guard\n# rust-toolchain.toml automatically selects nightly\ncargo build --release\ncp target\u002Frelease\u002Fdcg ~\u002F.local\u002Fbin\u002F\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` \u002F `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:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Freleases) 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:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Funinstall.sh | bash\n```\n\nOn Windows:\n\n```powershell\nirm https:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Funinstall.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), Hermes Agent, and Aider\n- Removes the dcg binary\n- Removes configuration (`~\u002F.config\u002Fdcg\u002F`) and history (`~\u002F.local\u002Fshare\u002Fdcg\u002F`)\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\u002Fhistory 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 `~\u002F.claude\u002Fsettings.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## Codex CLI Configuration\n\nCodex CLI 0.125.0+ supports stable `PreToolUse` hooks. The installer writes or\nmerges this automatically, but the manual configuration lives at\n`~\u002F.codex\u002Fhooks.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\nCodex denials intentionally differ from Claude-compatible denials: dcg exits\nwith code 2, writes the block reason to stderr, and leaves stdout empty. Allowed\ncommands stay silent with exit code 0.\n\n## Gemini CLI Configuration\n\nAdd to `~\u002F.gemini\u002Fsettings.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 .\u002Fbuild\"\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>`: use a specific config file\n- `--with-packs \u003CID1,ID2>`: temporarily enable extra packs\n- `--explain`: print detailed decision trace\n- `-f, --format \u003Cpretty|json|toon>`: output format (default: `pretty`)\n- `--no-color`: disable ANSI color output\n- `--heredoc-scan`: force-enable heredoc\u002Finline-script scanning\n- `--no-heredoc-scan`: force-disable heredoc\u002Finline-script scanning\n- `--heredoc-timeout \u003CMS>`: override heredoc extraction timeout budget\n- `--heredoc-languages \u003CLANG1,LANG2>`: 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\u002FCI; includes metadata like `schema_version`, `dcg_version`, `command`, `decision`, rule\u002Fpack fields, and allowlist\u002Fagent context when present\n- `toon`: token-efficient structured encoding of the same payload used by `json` (useful for agent-to-agent\u002Ftool pipelines)\n\n#### CI\u002FCD Integration Examples\n\nFail fast in shell pipelines:\n\n```bash\ndcg test --format json \"rm -rf \u002F\" > \u002Ftmp\u002Fdcg.json\njq -e '.decision == \"allow\"' \u002Ftmp\u002Fdcg.json\n```\n\nMinimal GitHub Actions step:\n\n```yaml\n- name: Validate dangerous command policy\n  run: |\n    ~\u002F.local\u002Fbin\u002Fdcg test --format json \"git reset --hard HEAD~1\" > \u002Ftmp\u002Fdcg-test.json\n    jq -e '.decision == \"allow\"' \u002Ftmp\u002Fdcg-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\u002Fsystem 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>\"` (or `dcg explain \"\u003Ccommand>\"`).\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 \u002Ftmp\u002Fbuild\"\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` \u002F `--hash`)\n2. The code is tied to the exact command that was blocked\n3. Running `dcg allow-once \u003Ccode>` creates a temporary exception\n4. The exception is stored in `~\u002F.config\u002Fdcg\u002Fpending_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>`, 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\u002Frebase-merge\u002F` or `.git\u002Frebase-apply\u002F` 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\u002Frebase-recovery-permit` at the repo root. For the next N seconds (or until the first matching allow, whichever comes first), `git checkout -- \u003Cpath>` and `git restore \u003Cpaths>` 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\u002F` 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:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fissues\u002F104) 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:\u002F\u002Fgithub.com\u002Frustyhorde\u002Fvergen), 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 \u002F\"` 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\u002Fworkflows\u002F*.yml`, `.github\u002Fworkflows\u002F*.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\u002Fconfig.yml`, `.circleci\u002Fconfig.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 . \u002Fapp                 # ← 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: `#`, `\u002F\u002F`, 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\u002F .github\u002Fworkflows\u002F\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\u002Fhooks.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\u002Fworkflows\u002F**\",  # Start with CI configs\n    \"Dockerfile\",            # Container builds\n    \"Makefile\",              # Build scripts\n]\nexclude = [\n    \"target\u002F**\",\n    \"node_modules\u002F**\",\n    \"vendor\u002F**\",\n]\n```\n\n**Gradual expansion:**\n\n1. **Week 1-2**: Start with workflows\u002FDockerfiles only, `--fail-on error`\n2. **Week 3-4**: Add Makefiles and shell scripts in `scripts\u002F`\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\u002Fhooks\u002Fpre-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#!\u002Fbin\u002Fbash\n# .git\u002Fhooks\u002Fpre-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\u002Fdeploy.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\u002Ftruncated)\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 .\u002Fbuild\" --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:\u002F\u002Fapi.example.com\n\n# With --redact quoted:\ncurl -H \"...\" https:\u002F\u002Fapi.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\u002Fhooks.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\u002F**\",\n    \".github\u002Fworkflows\u002F**\",\n    \"Dockerfile*\",\n    \"Makefile\",\n]\n\n# Skip files matching these patterns\nexclude = [\n    \"target\u002F**\",\n    \"node_modules\u002F**\",\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\u002Fcheckout@v4\n        with:\n          fetch-depth: 0\n\n      - name: Install dcg\n        run: |\n          curl -fsSL \"https:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh\" | bash\n          echo \"$HOME\u002F.local\u002Fbin\" >> $GITHUB_PATH\n\n      - name: Scan changed files\n        run: |\n          dcg scan --git-diff origin\u002F${{ 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:\u002F\u002Fraw.githubusercontent.com\u002FDicklesworthstone\u002Fdestructive_command_guard\u002Fmain\u002Finstall.sh\" | bash\n    - ~\u002F.local\u002Fbin\u002Fdcg scan --git-diff origin\u002F$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\u002FGemini\u002FCopilot variants), extracts the command string. Non-shell tools are immediately allowed.\n2. **Normalization** -- Strips absolute paths (`\u002Fusr\u002Fbin\u002Fgit` 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 \u002F Codex \u002F Gemini \u002F Copilot \u002F Cursor \u002F Hermes hooks      │\n│                                                                  │\n│  User: \"delete the build artifacts\"                             │\n│  Agent: executes `rm -rf .\u002Fbuild`                               │\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 \u002F empty allow\n                   ","Destructive Command Guard (dcg) 是一个用于阻止危险的 Git 和 Shell 命令执行的安全工具。该项目使用 Rust 语言开发，具有高性能和低延迟的特点，能够在命令执行前拦截并阻止潜在的破坏性操作，如 `git reset --hard` 或 `rm -rf .\u002Fsrc`，从而保护代码免受意外删除。它支持多种 AI 编码助手（例如 Claude Code、Codex CLI、GitHub Copilot CLI 等），并且提供了超过 50 种安全包来覆盖数据库、Kubernetes、Docker、云服务等场景。此外，dcg 还具备智能上下文检测功能，可以扫描 Heredoc 和内联脚本中的危险指令。适用于任何需要防止代码或数据被误删的开发环境。",2,"2026-06-11 03:50:28","high_star"]