destructive_command_guard 0.4.3

A Claude Code hook that blocks destructive commands before they execute
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Integration tests for the history system.
//!
//! These tests verify the full history pipeline from command logging
//! to querying, ensuring all components work together correctly.
//!
//! # Running
//!
//! ```bash
//! cargo test --test history_integration
//! ```

mod common;

use chrono::Utc;
use common::db::TestDb;
use common::fixtures;
use common::logging::init_test_logging;
use destructive_command_guard::config::{HistoryConfig, HistoryRedactionMode};
use destructive_command_guard::history::{CommandEntry, HistoryDb, HistoryWriter, Outcome};
use fsqlite_types::value::SqliteValue;
use std::time::{Duration, Instant};
use tempfile::TempDir;

fn sv_to_string(v: &SqliteValue) -> String {
    match v {
        SqliteValue::Text(s) => s.to_string(),
        SqliteValue::Integer(i) => i.to_string(),
        SqliteValue::Float(f) => f.to_string(),
        SqliteValue::Null => String::new(),
        SqliteValue::Blob(_) => String::new(),
    }
}

fn sv_to_i64(v: &SqliteValue) -> i64 {
    match v {
        SqliteValue::Integer(i) => *i,
        SqliteValue::Float(f) => *f as i64,
        SqliteValue::Text(s) => s.parse().unwrap_or(0),
        _ => 0,
    }
}

fn sv_to_opt_string(v: &SqliteValue) -> Option<String> {
    match v {
        SqliteValue::Text(s) => Some(s.to_string()),
        SqliteValue::Null => None,
        SqliteValue::Integer(i) => Some(i.to_string()),
        _ => None,
    }
}

/// Test: Full history pipeline - log -> query cycle
#[test]
fn test_full_history_pipeline() {
    init_test_logging();

    let test_db = TestDb::new();

    // Log a command
    let entry = CommandEntry {
        timestamp: Utc::now(),
        agent_type: "claude_code".to_string(),
        working_dir: "/data/projects/test".to_string(),
        command: "git status".to_string(),
        outcome: Outcome::Allow,
        eval_duration_us: 150,
        ..Default::default()
    };

    let id = test_db.db.log_command(&entry).unwrap();
    assert!(id > 0, "Command ID should be positive");

    // Verify command was logged
    let count = test_db.db.count_commands().unwrap();
    assert_eq!(count, 1, "Should have exactly 1 command");
}

/// Test: Multiple commands maintain correct ordering
#[test]
fn test_command_ordering() {
    init_test_logging();

    let test_db = TestDb::new();
    let now = Utc::now();

    // Log commands with specific timestamps
    for i in 0..10 {
        let offset = chrono::Duration::seconds(i * 60);
        let entry = CommandEntry {
            timestamp: now + offset,
            command: format!("command_{i}"),
            ..Default::default()
        };
        test_db.db.log_command(&entry).unwrap();
    }

    assert_eq!(test_db.db.count_commands().unwrap(), 10);

    // Verify via raw query that timestamps are in order
    let query_rows = test_db
        .db
        .connection()
        .query("SELECT command FROM commands ORDER BY timestamp ASC")
        .unwrap();
    let rows: Vec<String> = query_rows
        .iter()
        .map(|row| sv_to_string(&row.values()[0]))
        .collect();

    for (i, cmd) in rows.iter().enumerate() {
        assert_eq!(cmd, &format!("command_{i}"));
    }
}

/// Test: Standard mix fixture creates valid database
#[test]
fn test_standard_mix_fixture() {
    init_test_logging();

    let test_db = TestDb::with_standard_mix();

    let count = test_db.db.count_commands().unwrap();
    assert!(count > 0, "Standard mix should have commands");

    // Verify we have multiple outcomes
    let query_rows = test_db
        .db
        .connection()
        .query("SELECT DISTINCT outcome FROM commands")
        .unwrap();
    assert!(query_rows.len() >= 2, "Should have multiple outcome types");
}

/// Test: Large dataset performance
#[test]
fn test_large_dataset_insertion() {
    init_test_logging();

    let commands = fixtures::large_dataset(1000);
    let test_db = TestDb::in_memory();
    let now = Utc::now();
    for cmd in &commands {
        let entry = cmd.to_entry(now);
        test_db.log_command(&entry).unwrap();
    }

    assert_eq!(test_db.count_commands().unwrap(), 1000);
}

/// Test: FTS search works on seeded data
#[test]
fn test_fts_on_seeded_data() {
    init_test_logging();

    let test_db = TestDb::with_standard_mix();

    // Search for git commands
    let git_count = test_db
        .db
        .connection()
        .query("SELECT rowid FROM commands_fts WHERE command LIKE '%git%'")
        .map(|rows| rows.len())
        .unwrap();

    assert!(git_count > 0, "Should find git commands via FTS");
}

/// Test: Outcome distribution queries work correctly
#[test]
fn test_outcome_distribution_queries() {
    init_test_logging();

    let commands = fixtures::outcome_distribution();
    let test_db = TestDb::with_seed_data(&commands);

    // Query outcome distribution
    let allow_count: i64 = test_db
        .db
        .connection()
        .query_row("SELECT COUNT(*) FROM commands WHERE outcome = 'allow'")
        .map(|row| sv_to_i64(&row.values()[0]))
        .unwrap();

    let deny_count: i64 = test_db
        .db
        .connection()
        .query_row("SELECT COUNT(*) FROM commands WHERE outcome = 'deny'")
        .map(|row| sv_to_i64(&row.values()[0]))
        .unwrap();

    assert_eq!(allow_count, 70, "Should have 70 allows");
    assert_eq!(deny_count, 20, "Should have 20 denies");
}

/// Test: Pack analysis queries
#[test]
fn test_pack_analysis_queries() {
    init_test_logging();

    let test_db = TestDb::with_standard_mix();

    // Count commands by pack
    let query_rows = test_db
        .db
        .connection()
        .query("SELECT pack_id, COUNT(*) as cnt FROM commands GROUP BY pack_id ORDER BY cnt DESC")
        .unwrap();
    let pack_counts: Vec<(Option<String>, i64)> = query_rows
        .iter()
        .map(|row| {
            let v = row.values();
            (sv_to_opt_string(&v[0]), sv_to_i64(&v[1]))
        })
        .collect();

    assert!(!pack_counts.is_empty(), "Should have pack counts");

    // Verify we have both NULL (safe commands) and non-NULL (blocked) packs
    let null_count = pack_counts.iter().filter(|(p, _)| p.is_none()).count();
    let non_null_count = pack_counts.iter().filter(|(p, _)| p.is_some()).count();

    assert!(null_count > 0, "Should have commands with no pack (safe)");
    assert!(
        non_null_count > 0,
        "Should have commands with pack (blocked)"
    );
}

/// Test: Working directory filtering
#[test]
fn test_working_dir_filtering() {
    init_test_logging();

    let test_db = TestDb::with_standard_mix();

    // Count distinct working directories
    let dir_count: i64 = test_db
        .db
        .connection()
        .query_row("SELECT COUNT(DISTINCT working_dir) FROM commands")
        .map(|row| sv_to_i64(&row.values()[0]))
        .unwrap();

    assert!(dir_count > 0, "Should have working directories");
}

/// Test: Agent type tracking
#[test]
fn test_agent_type_tracking() {
    init_test_logging();

    let test_db = TestDb::with_standard_mix();

    // Count commands by agent type
    let query_rows = test_db
        .db
        .connection()
        .query("SELECT agent_type, COUNT(*) FROM commands GROUP BY agent_type")
        .unwrap();
    let agent_counts: Vec<(String, i64)> = query_rows
        .iter()
        .map(|row| {
            let v = row.values();
            (sv_to_string(&v[0]), sv_to_i64(&v[1]))
        })
        .collect();

    assert!(!agent_counts.is_empty(), "Should track agent types");

    // Standard mix includes multiple agent types
    assert!(
        agent_counts
            .iter()
            .map(|(a, _)| a.as_str())
            .any(|agent| agent == "claude_code"),
        "Should have claude_code agent"
    );
}

/// Test: Database file persistence
#[test]
fn test_database_persistence() {
    init_test_logging();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let db_path = temp_dir.path().join("persistent_test.db");

    // Create and populate
    {
        let db = HistoryDb::open(Some(db_path.clone())).unwrap();
        for i in 0..5 {
            db.log_command(&CommandEntry {
                command: format!("persist_cmd_{i}"),
                ..Default::default()
            })
            .unwrap();
        }
        assert_eq!(db.count_commands().unwrap(), 5);
    }

    // Reopen and verify
    {
        let db = HistoryDb::open(Some(db_path)).unwrap();
        assert_eq!(db.count_commands().unwrap(), 5);
    }
}

/// Test: In-memory database for fast tests
#[test]
fn test_in_memory_operations() {
    init_test_logging();

    let db = TestDb::in_memory();

    for i in 0..100 {
        db.log_command(&CommandEntry {
            command: format!("mem_cmd_{i}"),
            ..Default::default()
        })
        .unwrap();
    }

    assert_eq!(db.count_commands().unwrap(), 100);
}

/// Test: Command hash is deterministic
#[test]
fn test_command_hash_stored() {
    init_test_logging();

    let test_db = TestDb::new();

    let entry = CommandEntry {
        command: "deterministic_command".to_string(),
        ..Default::default()
    };
    let expected_hash = entry.command_hash();

    test_db.db.log_command(&entry).unwrap();

    let stored_hash: String = test_db
        .db
        .connection()
        .query_row("SELECT command_hash FROM commands WHERE command = 'deterministic_command'")
        .map(|row| sv_to_string(&row.values()[0]))
        .unwrap();

    assert_eq!(stored_hash, expected_hash);
}

/// Test: Concurrent writes (basic thread safety)
#[test]
fn test_concurrent_writes() {
    init_test_logging();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let db_path = temp_dir.path().join("concurrent_test.db");

    // fsqlite uses MVCC within a single connection; multi-connection file
    // writes are not supported.  Test that a single connection can handle
    // many interleaved writes from different "agent" contexts reliably.
    let db = HistoryDb::open(Some(db_path.clone())).unwrap();

    // Initial seed entry
    db.log_command(&CommandEntry {
        command: "init".to_string(),
        ..Default::default()
    })
    .unwrap();

    // Simulate 4 agent streams writing 25 commands each
    for thread_id in 0..4u32 {
        for i in 0..25u32 {
            let entry = CommandEntry {
                command: format!("thread_{thread_id}_cmd_{i}"),
                agent_type: format!("thread_{thread_id}"),
                ..Default::default()
            };
            db.log_command(&entry)
                .unwrap_or_else(|e| panic!("log_command failed: {e:?}"));
        }
    }

    let count = db.count_commands().unwrap();

    // 1 init + 4 agents * 25 commands = 101
    assert_eq!(count, 101, "All writes should succeed");
}

/// Test: VACUUM operation
#[test]
fn test_vacuum_operation() {
    init_test_logging();

    let test_db = TestDb::new();

    // Add some data
    for i in 0..10 {
        test_db
            .db
            .log_command(&CommandEntry {
                command: format!("vacuum_test_{i}"),
                ..Default::default()
            })
            .unwrap();
    }

    // VACUUM should not error
    test_db.db.vacuum().unwrap();

    // Data should still be there
    assert_eq!(test_db.db.count_commands().unwrap(), 10);
}

#[test]
fn test_history_writer_logs_allow() {
    init_test_logging();

    let temp_dir = TempDir::new().expect("temp dir");
    let db_path = temp_dir.path().join("history_writer_allow.db");

    let config = HistoryConfig {
        enabled: true,
        redaction_mode: HistoryRedactionMode::None,
        ..Default::default()
    };
    let writer = HistoryWriter::new(Some(db_path.clone()), &config);

    writer.log(CommandEntry {
        timestamp: Utc::now(),
        agent_type: "claude_code".to_string(),
        working_dir: "/tmp".to_string(),
        command: "git status".to_string(),
        outcome: Outcome::Allow,
        ..Default::default()
    });
    writer.flush_sync();

    let reader = HistoryDb::open(Some(db_path)).expect("open reader");
    assert_eq!(reader.count_commands().unwrap(), 1);
}

#[test]
fn test_history_writer_respects_disabled() {
    init_test_logging();

    let temp_dir = TempDir::new().expect("temp dir");
    let db_path = temp_dir.path().join("history_writer_disabled.db");

    let config = HistoryConfig {
        enabled: false,
        ..Default::default()
    };
    let writer = HistoryWriter::new(Some(db_path.clone()), &config);

    writer.log(CommandEntry {
        timestamp: Utc::now(),
        agent_type: "claude_code".to_string(),
        working_dir: "/tmp".to_string(),
        command: "git status".to_string(),
        outcome: Outcome::Allow,
        ..Default::default()
    });
    writer.flush_sync();

    let reader = HistoryDb::open(Some(db_path)).expect("open reader");
    assert_eq!(reader.count_commands().unwrap(), 0);
}

#[test]
fn test_history_writer_full_redaction() {
    init_test_logging();

    let temp_dir = TempDir::new().expect("temp dir");
    let db_path = temp_dir.path().join("history_writer_redaction.db");

    let config = HistoryConfig {
        enabled: true,
        redaction_mode: HistoryRedactionMode::Full,
        ..Default::default()
    };
    let writer = HistoryWriter::new(Some(db_path.clone()), &config);

    writer.log(CommandEntry {
        timestamp: Utc::now(),
        agent_type: "claude_code".to_string(),
        working_dir: "/tmp".to_string(),
        command: "curl -H 'Bearer secret'".to_string(),
        outcome: Outcome::Allow,
        ..Default::default()
    });
    writer.flush_sync();

    let reader = HistoryDb::open(Some(db_path)).expect("open reader");
    let stored: String = reader
        .connection()
        .query_row("SELECT command FROM commands LIMIT 1")
        .map(|row| sv_to_string(&row.values()[0]))
        .unwrap();
    assert_eq!(stored, "[REDACTED]");
}

#[test]
fn test_history_writer_logs_deny_with_match_info() {
    init_test_logging();

    let temp_dir = TempDir::new().expect("temp dir");
    let db_path = temp_dir.path().join("history_writer_deny.db");

    let config = HistoryConfig {
        enabled: true,
        redaction_mode: HistoryRedactionMode::None,
        ..Default::default()
    };
    let writer = HistoryWriter::new(Some(db_path.clone()), &config);

    writer.log(CommandEntry {
        timestamp: Utc::now(),
        agent_type: "claude_code".to_string(),
        working_dir: "/tmp".to_string(),
        command: "git reset --hard".to_string(),
        outcome: Outcome::Deny,
        pack_id: Some("core.git".to_string()),
        pattern_name: Some("reset-hard".to_string()),
        ..Default::default()
    });
    writer.flush_sync();

    let reader = HistoryDb::open(Some(db_path)).expect("open reader");
    let row = reader
        .connection()
        .query_row("SELECT outcome, pack_id, pattern_name FROM commands LIMIT 1")
        .unwrap();
    let vals = row.values();
    let stored = (
        sv_to_string(&vals[0]),
        sv_to_string(&vals[1]),
        sv_to_string(&vals[2]),
    );
    assert_eq!(stored.0, "deny");
    assert_eq!(stored.1, "core.git");
    assert_eq!(stored.2, "reset-hard");
}

#[test]
fn test_history_writer_flushes_on_drop() {
    init_test_logging();

    let temp_dir = TempDir::new().expect("temp dir");
    let db_path = temp_dir.path().join("history_writer_drop.db");

    let config = HistoryConfig {
        enabled: true,
        redaction_mode: HistoryRedactionMode::None,
        ..Default::default()
    };

    {
        let writer = HistoryWriter::new(Some(db_path.clone()), &config);
        writer.log(CommandEntry {
            timestamp: Utc::now(),
            agent_type: "claude_code".to_string(),
            working_dir: "/tmp".to_string(),
            command: "git status".to_string(),
            outcome: Outcome::Allow,
            ..Default::default()
        });
    }

    let reader = HistoryDb::open(Some(db_path)).expect("open reader");
    assert_eq!(reader.count_commands().unwrap(), 1);
}

#[test]
fn test_history_writer_async_performance() {
    init_test_logging();

    let temp_dir = TempDir::new().expect("temp dir");
    let db_path = temp_dir.path().join("history_writer_perf.db");

    let config = HistoryConfig {
        enabled: true,
        redaction_mode: HistoryRedactionMode::None,
        ..Default::default()
    };
    let writer = HistoryWriter::new(Some(db_path.clone()), &config);

    // Keep this test below the known io_uring instability threshold observed on
    // constrained CI kernels while still exercising the async batching path.
    let entry_count = 200;

    let start = Instant::now();
    for i in 0..entry_count {
        writer.log(CommandEntry {
            timestamp: Utc::now(),
            agent_type: "claude_code".to_string(),
            working_dir: "/tmp".to_string(),
            command: format!("command_{i}"),
            outcome: Outcome::Allow,
            ..Default::default()
        });
    }
    let elapsed = start.elapsed();

    // Keep this generous to avoid CI variance while ensuring async path is fast.
    assert!(
        elapsed < Duration::from_secs(2),
        "Logging too slow: {elapsed:?}"
    );

    writer.flush_sync();
    let reader = HistoryDb::open(Some(db_path)).expect("open reader");
    assert_eq!(reader.count_commands().unwrap(), entry_count);
}