Skip to main content

Crate destructive_command_guard

Crate destructive_command_guard 

Source
Expand description

Destructive Command Guard (dcg) library.

This library provides the core functionality for blocking destructive commands in AI coding agent workflows. It supports modular “packs” of patterns for different use cases (databases, containers, Kubernetes, cloud providers, etc.).

§Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        Configuration                             │
│  (env vars → project config → user config → system → defaults)  │
└─────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────┐
│                         Evaluator                                │
│  (unified entry point for hook mode and CLI)                    │
└─────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────┐
│                         Pack Registry                            │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐           │
│  │   Core   │ │ Database │ │  K8s     │ │  Cloud   │  ...      │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘           │
└─────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Pattern Matching                            │
│  Quick Reject (memchr) → Safe Patterns → Destructive Patterns   │
└─────────────────────────────────────────────────────────────────┘

§Usage

The main entry point for command evaluation is the evaluator module:

use destructive_command_guard::config::Config;
use destructive_command_guard::evaluator::{evaluate_command, EvaluationDecision};

let config = Config::load();
let compiled_overrides = config.overrides.compile();
let enabled_keywords = vec!["git", "rm"];
let allowlists = destructive_command_guard::load_default_allowlists();
let result = evaluate_command(
    "git status",
    &config,
    &enabled_keywords,
    &compiled_overrides,
    &allowlists,
);

if result.is_denied() {
    println!("Blocked: {}", result.reason().unwrap_or("unknown"));
}

Re-exports§

pub use allowlist::AllowEntry;
pub use allowlist::AllowSelector;
pub use allowlist::AllowlistError;
pub use allowlist::AllowlistFile;
pub use allowlist::AllowlistLayer;
pub use allowlist::LayeredAllowlist;
pub use allowlist::LoadedAllowlistLayer;
pub use allowlist::RuleId;
pub use allowlist::load_default_allowlists;
pub use config::Config;
pub use error_codes::DcgError;
pub use error_codes::ErrorCategory;
pub use error_codes::ErrorCode;
pub use error_codes::ErrorResponse;
pub use evaluator::ConfidenceResult;
pub use evaluator::DetailedEvaluationResult;
pub use evaluator::EvaluationDecision;
pub use evaluator::EvaluationResult;
pub use evaluator::LegacyDestructivePattern;
pub use evaluator::LegacySafePattern;
pub use evaluator::MatchSource;
pub use evaluator::MatchSpan;
pub use evaluator::PatternMatch;
pub use evaluator::apply_confidence_scoring;
pub use evaluator::evaluate_command;
pub use evaluator::evaluate_command_with_deadline;
pub use evaluator::evaluate_command_with_pack_order;
pub use evaluator::evaluate_command_with_pack_order_at_path;
pub use evaluator::evaluate_command_with_pack_order_deadline;
pub use evaluator::evaluate_command_with_pack_order_deadline_at_path;
pub use evaluator::evaluate_detailed;
pub use evaluator::evaluate_detailed_with_allowlists;
pub use exit_codes::EXIT_CONFIG_ERROR;
pub use exit_codes::EXIT_DENIED;
pub use exit_codes::EXIT_IO_ERROR;
pub use exit_codes::EXIT_PARSE_ERROR;
pub use exit_codes::EXIT_SUCCESS;
pub use exit_codes::EXIT_WARNING;
pub use exit_codes::ToExitCode;
pub use exit_codes::exit_with;
pub use exit_codes::to_exit_code;
pub use hook::HookInput;
pub use hook::HookOutput;
pub use hook::HookResult;
pub use hook::HookSpecificOutput;
pub use packs::external::ExternalPack;
pub use packs::external::parse_pack_file;
pub use packs::external::parse_pack_string;
pub use packs::Pack;
pub use packs::PackId;
pub use packs::PackRegistry;
pub use packs::PatternSuggestion;
pub use packs::Platform;
pub use pending_exceptions::AllowOnceEntry;
pub use pending_exceptions::AllowOnceScopeKind;
pub use pending_exceptions::AllowOnceStore;
pub use pending_exceptions::PendingExceptionRecord;
pub use pending_exceptions::PendingExceptionStore;
pub use packs::regex_engine::CompiledRegex;
pub use packs::regex_engine::needs_backtracking_engine;
pub use context::CommandSpans;
pub use context::ContextClassifier;
pub use context::SAFE_STRING_REGISTRY;
pub use context::SafeFlagEntry;
pub use context::SafeStringRegistry;
pub use context::Span;
pub use context::SpanKind;
pub use context::classify_command;
pub use context::is_argument_data;
pub use context::sanitize_for_pattern_matching;
pub use heredoc::ExtractedContent;
pub use heredoc::ExtractedShellCommand;
pub use heredoc::ExtractionLimits;
pub use heredoc::ExtractionResult;
pub use heredoc::HeredocType;
pub use heredoc::ScriptLanguage;
pub use heredoc::TriggerResult;
pub use heredoc::check_triggers;
pub use heredoc::extract_content;
pub use heredoc::extract_shell_commands;
pub use heredoc::matched_triggers;
pub use ast_matcher::AstMatcher;
pub use ast_matcher::CompiledPattern;
pub use ast_matcher::DEFAULT_MATCHER;
pub use ast_matcher::MatchError;
pub use ast_matcher::PatternMatch as AstPatternMatch;
pub use ast_matcher::Severity;
pub use trace::AllowlistInfo;
pub use trace::EXPLAIN_JSON_SCHEMA_VERSION;
pub use trace::ExplainJsonOutput;
pub use trace::ExplainTrace;
pub use trace::JsonAllowlistInfo;
pub use trace::JsonMatchInfo;
pub use trace::JsonPackSummary;
pub use trace::JsonSpan;
pub use trace::JsonSuggestion;
pub use trace::JsonTraceDetails;
pub use trace::JsonTraceStep;
pub use trace::MatchInfo;
pub use trace::PackSummary;
pub use trace::TraceCollector;
pub use trace::TraceDetails;
pub use trace::TraceStep;
pub use trace::format_duration;
pub use trace::truncate_utf8;
pub use highlight::HighlightSpan;
pub use highlight::HighlightedCommand;
pub use highlight::configure_colors as configure_highlight_colors;
pub use highlight::format_highlighted_command;
pub use highlight::format_highlighted_command_auto;
pub use highlight::format_highlighted_command_multi;
pub use highlight::should_use_color;
pub use suggest::AllowlistSuggestion;
pub use suggest::CommandCluster;
pub use suggest::CommandEntryInfo;
pub use suggest::ConfidenceTier;
pub use suggest::GeneratedPattern;
pub use suggest::PathPattern;
pub use suggest::RiskLevel;
pub use suggest::SuggestionReason;
pub use suggest::analyze_path_patterns;
pub use suggest::assess_risk_level;
pub use suggest::calculate_confidence_tier;
pub use suggest::calculate_suggestion_score;
pub use suggest::cluster_denied_commands;
pub use suggest::determine_primary_reason;
pub use suggest::filter_by_confidence;
pub use suggest::filter_by_risk;
pub use suggest::generate_enhanced_suggestions;
pub use suggest::generate_pattern_from_cluster;
pub use suggestions::Suggestion;
pub use suggestions::SuggestionKind;
pub use suggestions::get_suggestion_by_kind;
pub use suggestions::get_suggestions;
pub use scan::ExtractedCommand;
pub use scan::ScanDecision;
pub use scan::ScanEvalContext;
pub use scan::ScanFailOn;
pub use scan::ScanFinding;
pub use scan::ScanFormat;
pub use scan::ScanOptions;
pub use scan::ScanReport;
pub use scan::ScanSeverity;
pub use scan::ScanSummary;
pub use scan::extract_docker_compose_from_str;
pub use scan::extract_dockerfile_from_str;
pub use scan::extract_github_actions_workflow_from_str;
pub use scan::extract_gitlab_ci_from_str;
pub use scan::extract_makefile_from_str;
pub use scan::extract_package_json_from_str;
pub use scan::extract_shell_script_from_str;
pub use scan::extract_terraform_from_str;
pub use scan::scan_paths;
pub use scan::should_fail;
pub use scan::sort_findings;
pub use simulate::LimitHit;
pub use simulate::ParseError;
pub use simulate::ParseStats;
pub use simulate::ParsedCommand;
pub use simulate::ParsedLine;
pub use simulate::SIMULATE_SCHEMA_VERSION;
pub use simulate::SimulateInputFormat;
pub use simulate::SimulateLimits;
pub use simulate::SimulateParser;
pub use stats::AggregatedStats;
pub use stats::DEFAULT_PERIOD_SECS;
pub use stats::Decision as StatsDecision;
pub use stats::PackStats;
pub use stats::ParsedLogEntry;
pub use stats::format_stats_json;
pub use stats::format_stats_pretty;
pub use stats::parse_log_file;
pub use perf::ABSOLUTE_MAX;
pub use perf::Budget;
pub use perf::BudgetStatus;
pub use perf::Deadline;
pub use perf::FAIL_OPEN_THRESHOLD_MS;
pub use perf::FAST_PATH;
pub use perf::FAST_PATH_BUDGET_US;
pub use perf::FULL_HEREDOC_PIPELINE;
pub use perf::HEREDOC_EXTRACT;
pub use perf::HEREDOC_TRIGGER;
pub use perf::HOOK_EVALUATION_BUDGET;
pub use perf::HOOK_EVALUATION_BUDGET_MS;
pub use perf::LANGUAGE_DETECT;
pub use perf::PATTERN_MATCH;
pub use perf::QUICK_REJECT;
pub use perf::SLOW_PATH_BUDGET_MS;
pub use perf::should_fail_open;
pub use normalize::NormalizedCommand;
pub use normalize::StrippedWrapper;
pub use normalize::strip_wrapper_prefixes;
pub use confidence::ConfidenceContext;
pub use confidence::ConfidenceScore;
pub use confidence::ConfidenceSignal;
pub use confidence::DEFAULT_WARN_THRESHOLD;
pub use confidence::compute_match_confidence;
pub use confidence::should_downgrade_to_warn;
pub use history::AgentStat;
pub use history::BackupResult;
pub use history::CURRENT_SCHEMA_VERSION;
pub use history::CheckResult;
pub use history::CommandEntry;
pub use history::DEFAULT_DB_FILENAME;
pub use history::ENV_HISTORY_DB_PATH;
pub use history::ENV_HISTORY_DISABLED;
pub use history::HistoryDb;
pub use history::HistoryError;
pub use history::HistoryStats;
pub use history::HistoryWriter;
pub use history::Outcome as HistoryOutcome;
pub use history::OutcomeStats;
pub use history::PatternStat;
pub use history::PerformanceStats;
pub use history::ProjectStat;
pub use history::StatsTrends;
pub use interactive::AllowlistScope;
pub use interactive::InteractiveConfig;
pub use interactive::InteractiveResult;
pub use interactive::NotAvailableReason;
pub use interactive::check_interactive_available;
pub use interactive::generate_verification_code;
pub use interactive::run_interactive_prompt;
pub use git::BranchInfo;
pub use git::clear_cache as clear_git_cache;
pub use git::get_branch_info;
pub use git::get_branch_info_at_path;
pub use git::get_current_branch;
pub use git::is_in_git_repo;
pub use git::is_in_git_repo_at_path;
pub use agent::Agent;
pub use agent::DetectionMethod;
pub use agent::DetectionResult;
pub use agent::clear_cache as clear_agent_cache;
pub use agent::detect_agent;
pub use agent::detect_agent_with_details;
pub use agent::from_explicit as agent_from_explicit;
pub use output::BorderStyle;
pub use output::DenialBox;
pub use output::Severity as OutputSeverity;
pub use output::SeverityColors;
pub use output::Theme;
pub use output::ThemePalette;
pub use output::auto_theme;
pub use output::auto_theme_with_config;
pub use output::init as init_output;
pub use output::should_use_rich_output;
pub use output::supports_256_colors;
pub use output::terminal_height;
pub use output::terminal_width;
pub use update::CACHE_DURATION;
pub use update::VersionCheckError;
pub use update::VersionCheckResult;
pub use update::check_for_update;
pub use update::clear_cache;
pub use update::current_version;
pub use update::format_check_result;
pub use update::format_check_result_json;

Modules§

agent
AI coding agent detection for agent-specific profiles.
allowlist
Allowlist file parsing and layered loading.
ast_matcher
AST-based pattern matching for heredoc and inline script content.
cli
CLI argument parsing and command handling.
confidence
Confidence scoring for pattern matches.
config
Configuration system for dcg.
context
Execution-context classification for shell commands.
error_codes
Standardized error codes for DCG.
evaluator
Shared command evaluator for hook mode and CLI.
exit_codes
Standardized exit codes for dcg commands.
git
Git branch detection for branch-aware strictness.
heredoc
Two-tier heredoc and inline script detection.
highlight
Terminal highlighting for command spans.
history
Command history database for DCG.
hook
Claude Code hook protocol handling.
interactive
Interactive mode for dcg - allows users to bypass blocks via terminal interaction.
logging
Structured logging for allow/deny decisions.
mcp
MCP server mode for direct agent integration.
normalize
Command normalization for wrapper prefix stripping.
output
Output formatting module for dcg.
packs
Pack system for modular command blocking.
pending_exceptions
Pending exception store for allow-once short-code flow.
perf
Performance budgets for dcg.
sarif
SARIF 2.1.0 output format for scan results.
scan
Repository scanning (dcg scan) for destructive commands.
simulate
Simulation input parsing for dcg simulate.
stats
Statistics collection and display for dcg.
suggest
Suggest-allowlist clustering and pattern generation utilities.
suggestions
Suggestions system for providing actionable guidance when commands are blocked.
trace
Explain trace data model for dcg explain mode.
update
Self-update version check functionality.

Macros§

destructive_pattern
Macro to create a destructive pattern with reason.
safe_pattern
Macro to create a safe pattern with compile-time name checking.