DCG: Destructive Command Guard — Safety Philosophy and Design Principles

Research Date: 2026-01-26 Source URL: https://x.com/doodlestein/status/2015510232869245033

Reference URLs

Summary

DCG (Destructive Command Guard) is a high-performance Rust-based safety tool developed by Jeffrey Emanuel that intercepts and blocks dangerous shell commands before execution in Claude Code workflows. The tool represents a systematic approach to AI agent safety, prioritizing prevention of data loss through a whitelist-first architecture with SIMD-accelerated pattern matching for sub-millisecond latency.

DCG operates on three critical design principles: whitelist-first architecture (safe patterns checked before destructive ones), fail-safe defaults (unrecognized commands allowed by default), and zero false negatives philosophy (prioritizing blocking all dangerous commands over avoiding false positives). The tool integrates natively with Claude Code via PreToolUse hooks and forms part of a broader “Agentic Coding Flywheel” ecosystem of 14 interconnected tools for multi-agent AI coding workflows.

This analysis examines DCG’s safety philosophy, design principles, detailed pattern matching implementation, integration patterns, and comparative analysis with similar safety tools in the AI coding agent ecosystem.

Safety Philosophy

Threat Model: Well-Intentioned but Fallible Agents

DCG’s fundamental assumption is that AI coding agents are well-intentioned but fallible. The tool protects against honest mistakes rather than adversarial attacks. This distinction shapes every design decision:

Threat TypeProtection LevelRationale
Accidental commandsFull protectionPrimary use case: typos, misunderstandings
Malicious actorsNot protectedCan bypass hooks; requires different security
Non-Bash commandsNot protectedPython/JS file operations outside scope
Scripted commandsNot protected./deploy.sh contents not inspected

The threat model acknowledges that perfect security is impossible—malicious actors can always bypass hooks, and non-shell operations require different protection mechanisms. DCG focuses on the high-probability, high-impact scenario: an AI agent making an honest mistake that destroys uncommitted work.

Zero False Negatives Philosophy

DCG explicitly prioritizes never allowing dangerous commands over avoiding false positives. This philosophy accepts that occasional manual confirmation prompts are preferable to allowing work to be destroyed. The trade-off calculation:

  • Cost of false positive: User must manually run command (minor inconvenience)
  • Cost of false negative: Permanent data loss (catastrophic)

The tool errs on the side of caution, blocking commands that might be safe in specific contexts but are dangerous in general. For example, git reset --hard is always blocked, even though it might be safe if the user has no uncommitted changes—the tool cannot reliably determine this without complex git state analysis.

Fail-Safe Defaults: Default-Allow Architecture

Despite the zero false negatives philosophy, DCG uses a default-allow approach for unrecognized commands. This ensures:

  1. Legitimate workflows remain unbroken: New git commands or tools work until explicitly categorized
  2. Only known dangerous patterns are blocked: The tool doesn’t attempt to guess what might be dangerous
  3. Explicit safety over implicit restrictions: Users can trust that if DCG doesn’t block something, it’s been explicitly evaluated

This creates a tension between safety and usability that DCG resolves through comprehensive pattern coverage rather than broad restrictions.

Design Principles

Principle 1: Whitelist-First Architecture

Safe patterns are checked before destructive patterns. This ordering ensures that explicitly safe commands are never accidentally blocked:

Example: git checkout -b feature matches the safe “checkout-new-branch” pattern and is allowed immediately, without checking destructive patterns. If safe patterns were checked second, a hypothetical destructive pattern matching “checkout” might incorrectly block this safe operation.

Principle 2: Path Normalization

Commands are normalized before pattern matching to handle absolute paths and various command invocation styles:

InputNormalized OutputRationale
/usr/bin/git statusgit statusStrip absolute paths
/usr/local/bin/git reset --hardgit reset --hardPreserve arguments, normalize path
/bin/rm -rf /home/userrm -rf /home/userExtract command name

This normalization ensures that pattern matching works regardless of how the command is invoked—whether through PATH resolution, absolute paths, or system-specific binary locations.

Principle 3: SIMD-Accelerated Quick Rejection

Before expensive regex pattern matching, DCG performs a SIMD-accelerated substring search for “git” or “rm”. Commands without these keywords bypass regex entirely, handling 99%+ of commands in microseconds:

This optimization ensures that DCG adds negligible latency to the vast majority of commands while still providing comprehensive protection for dangerous operations.

Detailed Pattern Matching Examples

Git Command Patterns

Safe Patterns (Whitelist)

DCG maintains 34 safe patterns that are checked first:

PatternExample CommandWhy Safe
git checkout -b <branch>git checkout -b featureCreates new branch, no data loss
git checkout --orphangit checkout --orphan mainCreates orphan branch
git restore --stagedgit restore --staged fileUnstaging only, preserves worktree
git restore -S <file>git restore -S file.txtShort flag for staged-only
git clean -ngit clean -nDry-run mode, preview only
git clean --dry-rungit clean --dry-runExplicit dry-run flag

Pattern Matching Logic:

// Pseudo-code representation
safe_patterns = [
    r"^git checkout -b \S+",           // New branch creation
    r"^git checkout --orphan \S+",     // Orphan branch
    r"^git restore --staged",           // Unstaging only
    r"^git restore -S",                 // Short staged flag
    r"^git clean -(n|--dry-run)",      // Preview mode
    // ... 29 more patterns
]

destructive_patterns = [
    r"^git reset --hard",               // Destroys uncommitted changes
    r"^git reset --merge",              // Destroys uncommitted changes
    r"^git checkout -- \S+",           // Discards file modifications
    r"^git restore(?!.*--staged)(?!.*-S)", // Restore without staged flag
    r"^git clean -f",                   // Force clean untracked files
    r"^git push --force",                // Overwrites remote history
    r"^git push -f",                    // Short force flag
    r"^git branch -D",                  // Force delete branch
    r"^git stash drop",                  // Permanently deletes stash
    r"^git stash clear",                // Deletes all stashes
    // ... 6 more patterns
]

Destructive Patterns (Blacklist)

DCG blocks 16 destructive git patterns:

Commands That Destroy Uncommitted Work:

Command PatternExampleBlocked Because
git reset --hardgit reset --hard HEAD~1Permanently discards uncommitted changes
git reset --mergegit reset --mergeAbandons merge, loses uncommitted work
git checkout -- <file>git checkout -- file.txtDiscards modifications to file
git restore <file>git restore file.txtRestores file, discarding changes
git clean -fgit clean -fPermanently deletes untracked files
git clean --forcegit clean --forceExplicit force flag

Edge Case Handling:

The git restore command demonstrates sophisticated pattern matching:

Commands That Destroy Remote History:

Command PatternExampleBlocked Because
git push --forcegit push --force origin mainOverwrites remote commits
git push -fgit push -fShort flag for force push
git branch -Dgit branch -D featureForce-deletes without merge check

Safe Alternative: git push --force-with-lease is explicitly allowed because it refuses to push if the remote has commits you haven’t seen, preventing accidental overwrites.

Commands That Destroy Stashed Work:

Command PatternExampleBlocked Because
git stash dropgit stash dropPermanently deletes a stash
git stash cleargit stash clearPermanently deletes all stashes

Safe Alternative: git stash (create), git stash pop (apply and remove), and git stash list (view) are all allowed.

Filesystem Command Patterns

Recursive Deletion Protection

DCG blocks rm -rf operations outside temporary directories:

Command PatternExampleStatusRationale
rm -rf /tmp/*rm -rf /tmp/buildALLOWEDTemp directories are ephemeral
rm -rf $TMPDIR/*rm -rf $TMPDIR/buildALLOWEDShell variable temp directories
rm -rf ${TMPDIR}/buildrm -rf ${TMPDIR}/buildALLOWEDVariable expansion variants
rm -rf /home/user/projectrm -rf /home/user/projectBLOCKEDOutside temp, dangerous
rm -rf ./srcrm -rf ./srcBLOCKEDCould be typo, blocks all non-temp

Flag Ordering Variants:

DCG handles all common flag ordering patterns:

VariantPattern Recognition
rm -rf /pathCombined flags
rm -fr /pathReversed order
rm -r -f /pathSeparate flags
rm --recursive --force /pathLong flags

All variants are normalized and checked against the same pattern.

Modular Pack System

DCG uses a modular “pack” system to organize patterns by category, allowing users to enable only relevant protections:

Core Packs (Always Enabled)

PackPatterns Covered
core.gitDestructive git commands
core.filesystemDangerous rm -rf outside temp

Database Packs

PackDestructive Operations Blocked
database.postgresqlDROP DATABASE, TRUNCATE TABLE
database.mysqlDROP DATABASE, TRUNCATE TABLE
database.mongodbdropDatabase(), collection.drop()
database.redisFLUSHALL, FLUSHDB
database.sqliteDROP TABLE, DROP INDEX

Container Packs

PackDestructive Operations Blocked
containers.dockerdocker system prune, docker rm -f
containers.composedocker-compose down —volumes
containers.podmanpodman system prune

Kubernetes Packs

PackDestructive Operations Blocked
kubernetes.kubectlkubectl delete namespace
kubernetes.helmhelm uninstall
kubernetes.kustomizekustomize delete patterns

Cloud Provider Packs

PackDestructive Operations Blocked
cloud.awsDestructive AWS CLI commands
cloud.gcpDestructive gcloud commands
cloud.azureDestructive az commands

Configuration Example:

# ~/.config/dcg/config.toml
[packs]
enabled = [
    "database.postgresql",
    "containers.docker",
    "kubernetes",  # Enables all kubernetes sub-packs
]

This modular approach allows developers to enable protections relevant to their stack without unnecessary restrictions.

Integration Examples

Claude Code Integration

DCG integrates natively with Claude Code via PreToolUse hooks:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "dcg"
          }
        ]
      }
    ]
  }
}

Processing Pipeline:

Hook Input Format:

{
  "tool_name": "Bash",
  "tool_input": {
    "command": "git reset --hard HEAD~1"
  }
}

Hook Output (Blocked):

{
  "error": "BLOCKED dcg",
  "reason": "git reset --hard destroys uncommitted changes. Use 'git stash' first.",
  "command": "git reset --hard HEAD~1",
  "tip": "If you need to run this command, execute it manually in a terminal."
}

Hook Output (Allowed):

Empty stdout, exit code 0. Claude Code proceeds with command execution.

Integration with Flywheel Ecosystem

DCG integrates with multiple tools in the Agentic Coding Flywheel:

Agent Mail Integration

When DCG blocks a command, agents can report the block to a coordinator via Agent Mail:

BV (Beads Viewer) Integration

Tasks that repeatedly trigger DCG blocks can be flagged in BV for review:

MetricIndication
High DCG block rateTask may require manual intervention
Repeated patternsSuggests workflow improvement needed
Block frequencyHelps prioritize task complexity

CASS (Coding Agent Session Search) Integration

DCG block patterns are searchable across sessions:

  • Search for “git reset —hard” to find all instances where agents attempted destructive operations
  • Analyze patterns to identify common mistakes
  • Extract lessons learned for agent prompt improvements

NTM (Named Tmux Manager) Integration

DCG protects all commands in NTM-managed sessions:

Multi-Layer Safety Architecture

DCG works alongside SLB (Simultaneous Launch Button) for layered protection:

LayerToolProtection MechanismUse Case
Layer 1DCGPattern-based blockingPrevent accidental execution
Layer 2SLBTwo-person rule approvalHigh-risk operations

Example Workflow:

  1. DCG blocks git push --force → Agent cannot execute
  2. Agent requests manual approval via SLB
  3. Human reviewer evaluates context
  4. Approval granted → Command executes with DCG_BYPASS=1

This layered approach provides defense in depth: DCG catches obvious mistakes, while SLB provides human oversight for edge cases.

Comparison with Similar Safety Tools

SafeExec (Agentify)

Architecture Comparison:

AspectDCGSafeExec
LanguageRustBash
PerformanceSIMD-accelerated, sub-millisecondTTY-based, interactive prompt
IntegrationClaude Code PreToolUse hookPATH shims, dpkg-divert
Bypass difficultyEasy (environment variable)Hard (requires absolute paths)
Pattern matchingRegex-based, modular packsString matching, git-specific
Default behaviorDefault-allow (fail-safe)Default-block (interactive)

Design Philosophy Differences:

DCG: Optimized for AI agent workflows with minimal latency. Uses default-allow to avoid breaking legitimate operations. Focuses on known dangerous patterns.

SafeExec: Optimized for human + AI workflows with interactive confirmation. Uses hard-mode installation (dpkg-divert) to catch non-interactive execution. More aggressive blocking.

Use Case Recommendations:

  • Choose DCG if: Working primarily with Claude Code, need sub-millisecond latency, want modular pack system, prefer default-allow philosophy
  • Choose SafeExec if: Need hard-mode protection against non-interactive execution, want TTY-based confirmation, working with multiple AI agents beyond Claude Code

Project CodeGuard

Scope Comparison:

AspectDCGProject CodeGuard
Protection scopeShell command executionCode generation + review
Stage of protectionPre-execution (runtime)Pre-generation + post-generation
Threat modelAccidental destructive commandsSecurity vulnerabilities
Pattern typeCommand patternsCode patterns, security rules
IntegrationClaude Code hooksMultiple agent translators

Complementary Use:

DCG and Project CodeGuard address different threat vectors:

DCG: Prevents data loss from destructive commands Project CodeGuard: Prevents security vulnerabilities in generated code

These tools can be used together for comprehensive protection.

SLB (Simultaneous Launch Button)

Approach Comparison:

AspectDCGSLB
Approval mechanismAutomatic pattern blockingTwo-person rule (human/AI)
LatencySub-millisecondHuman-in-the-loop (seconds)
Use casePrevent obvious mistakesHigh-stakes operations
BypassEnvironment variableRequires second approval
IntegrationPreToolUse hookCommand queue system

Layered Protection Model:

DCG and SLB form complementary layers:

  1. DCG (Layer 1): Blocks obviously dangerous commands automatically
  2. SLB (Layer 2): Requires human approval for edge cases that pass DCG

This creates a defense-in-depth strategy where DCG handles the common cases, and SLB provides oversight for ambiguous situations.

Anthropic’s Built-in Safety

Comparison with Claude Code Defaults:

AspectDCGClaude Code Defaults
Permission modelPattern-based blockingRead-only by default
GranularityCommand-levelTool-level
CustomizationModular packs, configurablePersistent permissions
PerformanceSub-millisecondNative (no overhead)
ScopeShell commands onlyAll tool operations

Complementary Relationship:

Claude Code’s read-only defaults provide broad protection, while DCG adds granular command-level safety:

DCG adds an additional safety layer specifically for shell commands, complementing Claude Code’s broader permission system.

Performance Characteristics

Latency Analysis

DCG is optimized for zero perceived latency in AI agent workflows:

Optimization TechniqueImpactImplementation
Lazy Static RegexOne-time compilation costLazyLock for pattern compilation
SIMD Quick Reject99%+ commands: ~1μsmemchr crate for vector ops
Early ExitSafe matches: immediate returnShort-circuit on first match
Zero-Copy JSONAvoids allocation overheadserde_json on input buffer
Zero-AllocationPath normalization via Cow<str>Borrowed strings where possible
Release ProfileOptimized binary size + speedopt-level="z", LTO, single unit

Performance Profile:

Command TypeLatencyPath Through System
Non-git/rm command~1μsSIMD quick reject → allow
Safe git command~100-200μsSIMD → regex safe match → allow
Destructive command~200-500μsSIMD → regex destructive match → block
Unrecognized git command~200-500μsSIMD → regex (no match) → allow

These latencies are imperceptible to users and add minimal overhead to Claude Code workflows.

Pattern Matching Efficiency

The whitelist-first architecture ensures that safe commands (the majority) are checked with minimal overhead:

Pattern SetCountCheck OrderTypical Match Rate
Safe patterns34First~60% of git commands
Destructive patterns16Second~5% of git commands
Default allowN/AFallback~35% of git commands

By checking safe patterns first, DCG can short-circuit on the majority of commands without evaluating destructive patterns.

Key Findings

Safety Philosophy Insights

  1. Default-allow with comprehensive patterns provides better UX than default-deny: Legitimate workflows remain unbroken while dangerous operations are blocked.

  2. Zero false negatives philosophy accepts occasional false positives as preferable to data loss: The cost of manual confirmation is orders of magnitude lower than the cost of lost work.

  3. Whitelist-first architecture ensures safe operations are never accidentally blocked: Ordering matters when both safe and destructive patterns could match.

Design Principle Validation

  1. SIMD quick rejection handles 99%+ of commands in microseconds: Most commands aren’t git or rm operations, so expensive regex matching is unnecessary.

  2. Modular pack system allows targeted protection: Developers can enable only relevant protections (e.g., database packs for backend developers, Kubernetes packs for DevOps).

  3. Path normalization ensures consistent pattern matching: Commands work the same whether invoked via PATH, absolute paths, or system-specific locations.

Integration Patterns

  1. Native Claude Code integration via PreToolUse hooks provides seamless protection: No manual intervention required, blocks happen automatically.

  2. Layered safety architecture with SLB provides defense in depth: DCG handles obvious cases, SLB provides human oversight for edge cases.

  3. Ecosystem integration amplifies value: DCG blocks become searchable (CASS), reportable (Mail), and analyzable (BV).

Comparative Analysis Conclusions

  1. DCG vs SafeExec: DCG optimized for AI agent latency, SafeExec optimized for human confirmation. Complementary use cases.

  2. DCG vs Project CodeGuard: Different threat vectors (data loss vs security vulnerabilities). Can be used together.

  3. DCG vs Claude Code defaults: DCG adds granular command-level safety to Claude Code’s tool-level permissions.

References

  1. DCG Agent Skills Documentation - Comprehensive technical documentation
  2. Agentic Coding Flywheel TL;DR - Ecosystem context and integration patterns
  3. GitHub - destructive_command_guard - Source code repository
  4. SafeExec - Agentify Command Guard - Alternative safety tool comparison
  5. Project CodeGuard - Security-focused code generation protection
  6. Original X Post - Jeffrey Emanuel - January 26, 2026