jpskill.com
🛠️ 開発・MCP コミュニティ

dcg

Destructive Command Guard - High-performance Rust hook for Claude Code that blocks dangerous commands before execution. SIMD-accelerated, modular pack system, whitelist-first architecture. Essential safety layer for agent workflows.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o dcg.zip https://jpskill.com/download/18646.zip && unzip -o dcg.zip && rm dcg.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/18646.zip -OutFile "$d\dcg.zip"; Expand-Archive "$d\dcg.zip" -DestinationPath $d -Force; ri "$d\dcg.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して dcg.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → dcg フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

DCG — 破壊的コマンドガード

実行前に破壊的なコマンドをインターセプトしてブロックする、高性能な Claude Code フックです。Rust で記述され、サブミリ秒のレイテンシを実現するために SIMD で高速化されたフィルタリングを使用しています。

これが存在する理由

AI コーディングエージェントは強力ですが、誤りを犯す可能性があります。誤って破壊的なコマンドを実行する可能性があります。

  • "ビルド成果物をクリーンアップしましょう"rm -rf ./src (タイプミス)
  • "最後のコミットにリセットします"git reset --hard (コミットされていない変更を破棄)
  • "マージコンフリクトを修正しましょう"git checkout -- . (すべての変更を破棄)
  • "追跡されていないファイルをクリーンアップしましょう"git clean -fd (追跡されていないファイルを完全に削除)

DCG は危険なコマンドを 実行前 にインターセプトし、明確な説明とともにブロックすることで、変更を一時退避させる機会を提供します。

重要な設計原則

1. ホワイトリスト優先アーキテクチャ

安全なパターンは、破壊的なパターンの 前に チェックされます。これにより、明示的に安全なコマンドが誤ってブロックされることがなくなります。

git checkout -b feature    →  SAFE "checkout-new-branch" にマッチ  →  許可
git checkout -- file.txt   →  安全なマッチなし、DESTRUCTIVE にマッチ  →  拒否

2. フェイルセーフなデフォルト (デフォルト許可)

認識されないコマンドは、デフォルトで許可 されます。これにより、以下が保証されます。

  • フックが正当なワークフローを壊すことはありません
  • 既知の 危険なパターンのみがブロックされます
  • 新しい git コマンドは、明示的に分類されるまで動作します

3. ゼロ偽陰性哲学

パターンセットは、偽陽性を避けることよりも、危険なコマンドを絶対に許可しないこと を優先します。手動確認のための追加のプロンプトがいくつか表示されるのは許容範囲内です。作業内容の損失は許容できません。

ブロックするもの

コミットされていない作業を破壊する Git コマンド

コマンド 理由
git reset --hard コミットされていない変更を破棄
git reset --merge コミットされていない変更を破棄
git checkout -- <file> ファイルの変更を破棄
git restore <file> ( --staged なし) コミットされていない変更を破棄
git clean -f 追跡されていないファイルを完全に削除

リモート履歴を破壊する Git コマンド

コマンド 理由
git push --force / -f リモートのコミットを上書き
git branch -D マージチェックなしで強制削除

一時退避された作業を破壊する Git コマンド

コマンド 理由
git stash drop 一時退避を完全に削除
git stash clear すべての一時退避を完全に削除

ファイルシステムコマンド

コマンド 理由
rm -rf ( /tmp/var/tmp$TMPDIR の外) 再帰的な削除は危険

許可するもの

安全な操作は、何も表示せずに通過します。

常に安全な Git 操作

git statusgit loggit diffgit addgit commitgit pushgit pullgit fetchgit branch -d (マージチェック付きの安全な削除)、 git stashgit stash popgit stash list

明示的に安全なパターン

パターン 安全な理由
git checkout -b <branch> 新しいブランチの作成
git checkout --orphan <branch> 孤立したブランチの作成
git restore --staged <file> ステージング解除のみ、ワーキングツリーには触れない
git restore -S <file> ステージングされたファイルの短いフラグ
git clean -n / --dry-run プレビューモード、実際の削除は行わない
rm -rf /tmp/* 一時ディレクトリは一時的なもの
rm -rf $TMPDIR/* シェル変数の形式

安全な代替手段: --force-with-lease

git push --force-with-lease   # 許可 - リモートに未確認のコミットがある場合は拒否
git push --force              # ブロック - 他の人の作業を上書きする可能性

モジュール式パックシステム

DCG は、カテゴリ別にパターンを整理するために、モジュール式の「パック」システムを使用します。

コアパック (常に有効)

パック 説明
core.git 破壊的な git コマンド
core.filesystem 一時ディレクトリ外の危険な rm -rf

データベースパック

パック 説明
database.postgresql PostgreSQL の DROP/TRUNCATE
database.mysql MySQL/MariaDB の DROP/TRUNCATE
database.mongodb dropDatabase, drop()
database.redis FLUSHALL/FLUSHDB
database.sqlite SQLite の DROP

コンテナパック

パック 説明
containers.docker docker system prune, docker rm -f
containers.compose docker-compose down --volumes
containers.podman podman system prune

Kubernetes パック

パック 説明
kubernetes.kubectl kubectl delete namespace
kubernetes.helm helm uninstall
kubernetes.kustomize kustomize delete patterns

クラウドプロバイダーパック

パック 説明
cloud.aws 破壊的な AWS CLI コマンド
cloud.gcp 破壊的な gcloud コマンド
cloud.azure 破壊的な az コマンド

インフラストラクチャパック

パック 説明
infrastructure.terraform terraform destroy
infrastructure.ansible 危険な ansible パターン
infrastructure.pulumi pulumi destroy

システムパック

パック 説明
system.disk dd, mkfs, fdisk 操作
system.permissions 危険な chmod/chown パターン
system.services systemctl stop/disable パターン

その他のパック

パック 説明
strict_git 極端に用心深い git 保護
package_managers npm unpublish, cargo yank

パックの設定

# ~/.config/dcg/config.toml
[packs]
enabled = [
    "database.postgresql",
    "containers.docker",
    "kubernetes",  # すべての kubernetes サブパックを有効にする
]

環境変数

変数 説明
DCG_PACKS="containers.docker,kubernetes" パックを有効にする (カンマ区切り)
DCG_DISABLE="kubernetes.helm" パック/サブパックを無効にする
DCG_VERBOSE=1 詳細な出力
DCG_COLOR=auto\|always\|never カラーモード
DCG_BYPASS=1 DCG を完全にバイパスする (緊急脱出)

インストール

(原文はここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

DCG — Destructive Command Guard

A high-performance Claude Code hook that intercepts and blocks destructive commands before they execute. Written in Rust with SIMD-accelerated filtering for sub-millisecond latency.

Why This Exists

AI coding agents are powerful but fallible. They can accidentally run destructive commands:

  • "Let me clean up the build artifacts"rm -rf ./src (typo)
  • "I'll reset to the last commit"git reset --hard (destroys uncommitted changes)
  • "Let me fix the merge conflict"git checkout -- . (discards all modifications)
  • "I'll clean up untracked files"git clean -fd (permanently deletes untracked files)

DCG intercepts dangerous commands before execution and blocks them with a clear explanation, giving you a chance to stash your changes first.

Critical Design Principles

1. Whitelist-First Architecture

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

git checkout -b feature    →  Matches SAFE "checkout-new-branch"  →  ALLOW
git checkout -- file.txt   →  No safe match, matches DESTRUCTIVE  →  DENY

2. Fail-Safe Defaults (Default-Allow)

Unrecognized commands are allowed by default. This ensures:

  • The hook never breaks legitimate workflows
  • Only known dangerous patterns are blocked
  • New git commands work until explicitly categorized

3. Zero False Negatives Philosophy

The pattern set prioritizes never allowing dangerous commands over avoiding false positives. A few extra prompts for manual confirmation are acceptable; lost work is not.

What It Blocks

Git Commands That Destroy Uncommitted Work

Command Reason
git reset --hard Destroys uncommitted changes
git reset --merge Destroys uncommitted changes
git checkout -- <file> Discards file modifications
git restore <file> (without --staged) Discards uncommitted changes
git clean -f Permanently deletes untracked files

Git Commands That Destroy Remote History

Command Reason
git push --force / -f Overwrites remote commits
git branch -D Force-deletes without merge check

Git Commands That Destroy Stashed Work

Command Reason
git stash drop Permanently deletes a stash
git stash clear Permanently deletes all stashes

Filesystem Commands

Command Reason
rm -rf (outside /tmp, /var/tmp, $TMPDIR) Recursive deletion is dangerous

What It ALLOWS

Safe operations pass through silently:

Always Safe Git Operations

git status, git log, git diff, git add, git commit, git push, git pull, git fetch, git branch -d (safe delete with merge check), git stash, git stash pop, git stash list

Explicitly Safe Patterns

Pattern Why Safe
git checkout -b <branch> Creating new branches
git checkout --orphan <branch> Creating orphan branches
git restore --staged <file> Unstaging only, doesn't touch working tree
git restore -S <file> Short flag for staged
git clean -n / --dry-run Preview mode, no actual deletion
rm -rf /tmp/* Temp directories are ephemeral
rm -rf $TMPDIR/* Shell variable forms

Safe Alternative: --force-with-lease

git push --force-with-lease   # ALLOWED - refuses if remote has unseen commits
git push --force              # BLOCKED - can overwrite others' work

Modular Pack System

DCG uses a modular "pack" system to organize patterns by category:

Core Packs (Always Enabled)

Pack Description
core.git Destructive git commands
core.filesystem Dangerous rm -rf outside temp

Database Packs

Pack Description
database.postgresql DROP/TRUNCATE in PostgreSQL
database.mysql DROP/TRUNCATE in MySQL/MariaDB
database.mongodb dropDatabase, drop()
database.redis FLUSHALL/FLUSHDB
database.sqlite DROP in SQLite

Container Packs

Pack Description
containers.docker docker system prune, docker rm -f
containers.compose docker-compose down --volumes
containers.podman podman system prune

Kubernetes Packs

Pack Description
kubernetes.kubectl kubectl delete namespace
kubernetes.helm helm uninstall
kubernetes.kustomize kustomize delete patterns

Cloud Provider Packs

Pack Description
cloud.aws Destructive AWS CLI commands
cloud.gcp Destructive gcloud commands
cloud.azure Destructive az commands

Infrastructure Packs

Pack Description
infrastructure.terraform terraform destroy
infrastructure.ansible Dangerous ansible patterns
infrastructure.pulumi pulumi destroy

System Packs

Pack Description
system.disk dd, mkfs, fdisk operations
system.permissions Dangerous chmod/chown patterns
system.services systemctl stop/disable patterns

Other Packs

Pack Description
strict_git Extra paranoid git protections
package_managers npm unpublish, cargo yank

Configuring Packs

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

Environment Variables

Variable Description
DCG_PACKS="containers.docker,kubernetes" Enable packs (comma-separated)
DCG_DISABLE="kubernetes.helm" Disable packs/sub-packs
DCG_VERBOSE=1 Verbose output
DCG_COLOR=auto\|always\|never Color mode
DCG_BYPASS=1 Bypass DCG entirely (escape hatch)

Installation

Quick Install (Recommended)

curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/master/install.sh?$(date +%s)" | bash

# Easy mode: auto-update PATH
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/master/install.sh?$(date +%s)" | bash -s -- --easy-mode

# System-wide (requires sudo)
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/destructive_command_guard/master/install.sh?$(date +%s)" | sudo bash -s -- --system

From Source (Requires Rust Nightly)

cargo +nightly install --git https://github.com/Dicklesworthstone/destructive_command_guard

Prebuilt Binaries

Available for: Linux x86_64, Linux ARM64, macOS Intel, macOS Apple Silicon, Windows

Claude Code Configuration

Add to ~/.claude/settings.json:

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

Important: Restart Claude Code after adding the hook.

How It Works

Processing Pipeline

┌─────────────────────────────────────────────────────────────────┐
│                        Claude Code                               │
│  Agent executes `rm -rf ./build`                                │
└─────────────────────┬───────────────────────────────────────────┘
                      │
                      ▼ PreToolUse hook (stdin: JSON)
┌─────────────────────────────────────────────────────────────────┐
│                          dcg                                     │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐       │
│  │    Parse     │───▶│  Normalize   │───▶│ Quick Reject │       │
│  │    JSON      │    │   Command    │    │   Filter     │       │
│  └──────────────┘    └──────────────┘    └──────┬───────┘       │
│                                                  │               │
│                      ┌───────────────────────────┘               │
│                      ▼                                           │
│  ┌──────────────────────────────────────────────────────────┐   │
│  │                   Pattern Matching                        │   │
│  │   1. Check SAFE_PATTERNS (whitelist) ──▶ Allow if match  │   │
│  │   2. Check DESTRUCTIVE_PATTERNS ──────▶ Deny if match    │   │
│  │   3. No match ────────────────────────▶ Allow (default)  │   │
│  └──────────────────────────────────────────────────────────┘   │
└─────────────────────┬───────────────────────────────────────────┘
                      │
                      ▼ stdout: JSON (deny) or empty (allow)

Stage 1: JSON Parsing

  • Reads hook input from stdin
  • Validates Claude Code's PreToolUse format
  • Non-Bash tools immediately allowed

Stage 2: Command Normalization

  • Strips absolute paths: /usr/bin/git statusgit status
  • Preserves argument paths

Stage 3: Quick Rejection Filter

  • SIMD-accelerated substring search for "git" or "rm"
  • Commands without these bypass regex entirely (99%+ of commands)

Stage 4: Pattern Matching

  • Safe patterns checked first (short-circuit on match → allow)
  • Destructive patterns checked second (match → deny)
  • No match → default allow

Exit Codes

Code Meaning
0 Command is safe, proceed
2 Command is blocked, do not execute

CLI Usage

Test commands manually:

# Show version with build metadata
dcg --version

# Test a command
echo '{"tool_name":"Bash","tool_input":{"command":"git reset --hard"}}' | dcg

Example Block Message

════════════════════════════════════════════════════════════════════════
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.
     Consider using 'git stash' first to save your changes.
════════════════════════════════════════════════════════════════════════

Contextual Suggestions

Command Type Suggestion
git reset, git checkout -- "Consider using 'git stash' first"
git clean "Use 'git clean -n' first to preview"
git push --force "Consider using '--force-with-lease'"
rm -rf "Verify the path carefully before running manually"

Edge Cases Handled

Path Normalization

/usr/bin/git reset --hard          # Blocked
/usr/local/bin/git checkout -- .   # Blocked
/bin/rm -rf /home/user             # Blocked

Flag Ordering Variants

rm -rf /path          # Combined flags
rm -fr /path          # Reversed order
rm -r -f /path        # Separate flags
rm --recursive --force /path    # Long flags

All variants are handled.

Shell Variable Expansion

rm -rf $TMPDIR/build           # Allowed (temp)
rm -rf ${TMPDIR}/build         # Allowed
rm -rf "$TMPDIR/build"         # Allowed
rm -rf "${TMPDIR:-/tmp}/build" # Allowed

Staged vs Worktree Restore

git restore --staged file.txt    # Allowed (unstaging only)
git restore -S file.txt          # Allowed (short flag)
git restore file.txt             # BLOCKED (discards changes)
git restore --worktree file.txt  # BLOCKED (explicit worktree)
git restore -S -W file.txt       # BLOCKED (includes worktree)

Performance Optimizations

DCG is designed for zero perceived latency:

Optimization Technique
Lazy Static Regex patterns compiled once via LazyLock
SIMD Quick Reject memchr crate for CPU vector instructions
Early Exit Safe match returns immediately
Zero-Copy JSON serde_json operates on input buffer
Zero-Allocation Cow<str> for path normalization
Release Profile opt-level="z", LTO, single codegen unit

Result: Sub-millisecond execution for typical commands.

Pattern Counts

Type Count
Safe patterns (whitelist) 34
Destructive patterns (blacklist) 16

Security Considerations

What DCG Protects Against

  • Accidental data loss from git checkout -- or git reset --hard
  • Remote history destruction from force pushes
  • Stash loss from git stash drop/clear
  • Filesystem accidents from rm -rf outside temp directories

What DCG Does NOT Protect Against

  • Malicious actors (can bypass the hook)
  • Non-Bash commands (Python/JavaScript file writes, API calls)
  • Committed but unpushed work
  • Commands inside scripts (./deploy.sh contents not inspected)

Threat Model

DCG assumes the AI agent is well-intentioned but fallible. It catches honest mistakes, not adversarial attacks.

Troubleshooting

Hook not blocking commands

  1. Verify ~/.claude/settings.json has hook configuration
  2. Restart Claude Code
  3. Test manually: echo '{"tool_name":"Bash","tool_input":{"command":"git reset --hard"}}' | dcg

Hook blocking safe commands

  1. Check if there's an edge case not covered
  2. File a GitHub issue
  3. Temporary bypass: DCG_BYPASS=1 or run command manually

FAQ

Q: Why block git branch -D but allow git branch -d?

Lowercase -d only deletes branches fully merged. Uppercase -D force-deletes regardless of merge status, potentially losing commits.

Q: Why is git push --force-with-lease allowed?

Force-with-lease refuses to push if the remote has commits you haven't seen, preventing accidental overwrites.

Q: Why block all rm -rf outside temp directories?

Recursive forced deletion is extremely dangerous. A typo or wrong variable can delete critical files. Temp directories are designed to be ephemeral.

Q: What if I really need to run a blocked command?

DCG instructs the agent to ask for permission. Run the command manually in a separate terminal after making a conscious decision.

Integration with Flywheel

Tool Integration
Claude Code Native PreToolUse hook
Agent Mail Agents can report blocked commands to coordinator
BV Flag tasks that repeatedly trigger DCG
CASS Search DCG block patterns across sessions
RU DCG protects agent-sweep from destructive commits