selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
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
//! Confirmation prompts for destructive operations

// Feature-gated module

use std::io::{self, Write};

/// Operations that require confirmation
#[derive(Debug, Clone, PartialEq)]
pub enum DestructiveOperation {
    /// Deleting files
    FileDelete {
        path: String,
    },
    /// Force git operations
    GitForcePush {
        branch: String,
    },
    GitResetHard,
    GitClean,
    /// Shell commands that modify system
    ShellExec {
        command: String,
    },
    /// Overwriting existing files
    FileOverwrite {
        path: String,
    },
    /// Database modifications
    DatabaseModify {
        query: String,
    },
}

impl DestructiveOperation {
    /// Get a human-readable description of the operation
    pub fn description(&self) -> String {
        match self {
            Self::FileDelete { path } => format!("Delete file: {}", path),
            Self::GitForcePush { branch } => format!("Force push to branch: {}", branch),
            Self::GitResetHard => "Reset git repository (discard all changes)".to_string(),
            Self::GitClean => "Clean untracked files from repository".to_string(),
            Self::ShellExec { command } => {
                format!("Execute shell command: {}", truncate(command, 50))
            }
            Self::FileOverwrite { path } => format!("Overwrite existing file: {}", path),
            Self::DatabaseModify { query } => format!("Modify database: {}", truncate(query, 50)),
        }
    }

    /// Get the risk level of this operation
    pub fn risk_level(&self) -> RiskLevel {
        match self {
            Self::GitForcePush { .. } | Self::GitResetHard | Self::GitClean => RiskLevel::High,
            Self::FileDelete { .. } | Self::DatabaseModify { .. } => RiskLevel::Medium,
            Self::ShellExec { .. } | Self::FileOverwrite { .. } => RiskLevel::Low,
        }
    }
}

/// Risk level for operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RiskLevel {
    Low,
    Medium,
    High,
}

impl RiskLevel {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Low => "LOW",
            Self::Medium => "MEDIUM",
            Self::High => "HIGH",
        }
    }

    pub fn color_code(&self) -> &'static str {
        match self {
            Self::Low => "\x1b[33m",    // Yellow
            Self::Medium => "\x1b[35m", // Magenta
            Self::High => "\x1b[31m",   // Red
        }
    }
}

/// Configuration for confirmation behavior
#[derive(Debug, Clone)]
pub struct ConfirmConfig {
    /// Whether to require confirmation at all
    pub enabled: bool,
    /// Minimum risk level that requires confirmation
    pub min_risk_level: RiskLevel,
    /// Whether to auto-approve in non-interactive mode
    pub auto_approve_non_interactive: bool,
    /// Tool names that always require confirmation
    pub always_confirm: Vec<String>,
    /// Tool names that never require confirmation
    pub never_confirm: Vec<String>,
}

impl Default for ConfirmConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            min_risk_level: RiskLevel::Medium,
            auto_approve_non_interactive: false,
            always_confirm: vec!["git_push".to_string(), "file_delete".to_string()],
            never_confirm: vec![
                "file_read".to_string(),
                "directory_tree".to_string(),
                "git_status".to_string(),
                "git_diff".to_string(),
            ],
        }
    }
}

/// Result of a confirmation prompt
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConfirmResult {
    /// User approved the operation
    Approved,
    /// User rejected the operation
    Rejected,
    /// User requested to skip this operation
    Skipped,
    /// Confirmation was not required
    NotRequired,
}

/// Check if an operation requires confirmation
pub fn requires_confirmation(
    tool_name: &str,
    operation: Option<&DestructiveOperation>,
    config: &ConfirmConfig,
) -> bool {
    if !config.enabled {
        return false;
    }

    // Check never_confirm list
    if config.never_confirm.iter().any(|t| t == tool_name) {
        return false;
    }

    // Check always_confirm list
    if config.always_confirm.iter().any(|t| t == tool_name) {
        return true;
    }

    // Check by risk level
    if let Some(op) = operation {
        op.risk_level() >= config.min_risk_level
    } else {
        false
    }
}

/// Prompt the user for confirmation
pub fn prompt_confirmation(operation: &DestructiveOperation) -> io::Result<ConfirmResult> {
    let risk = operation.risk_level();
    let reset = "\x1b[0m";

    eprintln!();
    eprintln!(
        "{}⚠️  CONFIRMATION REQUIRED [{}]{}",
        risk.color_code(),
        risk.as_str(),
        reset
    );
    eprintln!("Operation: {}", operation.description());
    eprintln!();
    eprint!("Do you want to proceed? [y/N/s(kip)]: ");
    io::stderr().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    let input = input.trim().to_lowercase();

    Ok(match input.as_str() {
        "y" | "yes" => ConfirmResult::Approved,
        "s" | "skip" => ConfirmResult::Skipped,
        _ => ConfirmResult::Rejected,
    })
}

/// Non-interactive confirmation (for testing or automation)
pub fn auto_confirm(operation: &DestructiveOperation, config: &ConfirmConfig) -> ConfirmResult {
    if config.auto_approve_non_interactive {
        tracing::warn!(
            "Auto-approving operation in non-interactive mode: {}",
            operation.description()
        );
        ConfirmResult::Approved
    } else {
        tracing::error!(
            "Operation rejected in non-interactive mode: {}",
            operation.description()
        );
        ConfirmResult::Rejected
    }
}

/// Detect if a shell command is potentially destructive
pub fn detect_destructive_shell_command(command: &str) -> Option<DestructiveOperation> {
    let dangerous_patterns = [
        ("rm -rf", true),
        ("rm -r", true),
        ("rmdir", true),
        ("git push -f", true),
        ("git push --force", true),
        ("git reset --hard", true),
        ("git clean", true),
        ("DROP TABLE", true),
        ("DROP DATABASE", true),
        ("DELETE FROM", true),
        ("TRUNCATE", true),
        ("> /dev/", true),
        ("dd if=", true),
        ("mkfs", true),
    ];

    for (pattern, _) in &dangerous_patterns {
        if command.to_lowercase().contains(&pattern.to_lowercase()) {
            return Some(DestructiveOperation::ShellExec {
                command: command.to_string(),
            });
        }
    }

    None
}

/// Detect if a git operation is destructive
pub fn detect_destructive_git_operation(
    tool_name: &str,
    args: &serde_json::Value,
) -> Option<DestructiveOperation> {
    match tool_name {
        "git_push" => {
            if args.get("force").and_then(|v| v.as_bool()).unwrap_or(false) {
                let branch = args
                    .get("branch")
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown")
                    .to_string();
                Some(DestructiveOperation::GitForcePush { branch })
            } else {
                None
            }
        }
        "git_reset" => {
            if args.get("hard").and_then(|v| v.as_bool()).unwrap_or(false) {
                Some(DestructiveOperation::GitResetHard)
            } else {
                None
            }
        }
        "git_clean" => Some(DestructiveOperation::GitClean),
        _ => None,
    }
}

/// Truncate a string for display (UTF-8 safe)
fn truncate(s: &str, max_len: usize) -> String {
    if s.chars().count() <= max_len {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max_len).collect();
        format!("{}...", truncated)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_destructive_operation_description() {
        let op = DestructiveOperation::FileDelete {
            path: "/tmp/test.txt".to_string(),
        };
        assert!(op.description().contains("/tmp/test.txt"));
    }

    #[test]
    fn test_risk_level_ordering() {
        assert!(RiskLevel::High > RiskLevel::Medium);
        assert!(RiskLevel::Medium > RiskLevel::Low);
    }

    #[test]
    fn test_requires_confirmation_disabled() {
        let config = ConfirmConfig {
            enabled: false,
            ..Default::default()
        };
        assert!(!requires_confirmation("git_push", None, &config));
    }

    #[test]
    fn test_requires_confirmation_always_list() {
        let config = ConfirmConfig::default();
        assert!(requires_confirmation("git_push", None, &config));
    }

    #[test]
    fn test_requires_confirmation_never_list() {
        let config = ConfirmConfig::default();
        assert!(!requires_confirmation("file_read", None, &config));
    }

    #[test]
    fn test_detect_destructive_shell_rm() {
        let result = detect_destructive_shell_command("rm -rf /tmp/test");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_shell_safe() {
        let result = detect_destructive_shell_command("ls -la");
        assert!(result.is_none());
    }

    #[test]
    fn test_detect_destructive_git_force_push() {
        let args = serde_json::json!({"force": true, "branch": "main"});
        let result = detect_destructive_git_operation("git_push", &args);
        assert!(matches!(
            result,
            Some(DestructiveOperation::GitForcePush { .. })
        ));
    }

    #[test]
    fn test_detect_destructive_git_normal_push() {
        let args = serde_json::json!({"branch": "main"});
        let result = detect_destructive_git_operation("git_push", &args);
        assert!(result.is_none());
    }

    #[test]
    fn test_truncate_short() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_long() {
        assert_eq!(truncate("hello world", 5), "hello...");
    }

    #[test]
    fn test_auto_confirm_non_interactive() {
        let op = DestructiveOperation::FileDelete {
            path: "test.txt".to_string(),
        };

        let config = ConfirmConfig {
            auto_approve_non_interactive: true,
            ..Default::default()
        };
        assert_eq!(auto_confirm(&op, &config), ConfirmResult::Approved);

        let config = ConfirmConfig {
            auto_approve_non_interactive: false,
            ..Default::default()
        };
        assert_eq!(auto_confirm(&op, &config), ConfirmResult::Rejected);
    }

    #[test]
    fn test_risk_level_color() {
        assert!(RiskLevel::High.color_code().contains("31")); // Red
        assert!(RiskLevel::Medium.color_code().contains("35")); // Magenta
        assert!(RiskLevel::Low.color_code().contains("33")); // Yellow
    }

    #[test]
    fn test_risk_level_as_str() {
        assert_eq!(RiskLevel::High.as_str(), "HIGH");
        assert_eq!(RiskLevel::Medium.as_str(), "MEDIUM");
        assert_eq!(RiskLevel::Low.as_str(), "LOW");
    }

    #[test]
    fn test_destructive_operation_git_reset() {
        let op = DestructiveOperation::GitResetHard;
        assert!(op.description().contains("Reset"));
        assert_eq!(op.risk_level(), RiskLevel::High);
    }

    #[test]
    fn test_destructive_operation_git_clean() {
        let op = DestructiveOperation::GitClean;
        assert!(op.description().contains("Clean"));
        assert_eq!(op.risk_level(), RiskLevel::High);
    }

    #[test]
    fn test_destructive_operation_file_overwrite() {
        let op = DestructiveOperation::FileOverwrite {
            path: "config.json".to_string(),
        };
        assert!(op.description().contains("config.json"));
        assert_eq!(op.risk_level(), RiskLevel::Low);
    }

    #[test]
    fn test_destructive_operation_database_modify() {
        let op = DestructiveOperation::DatabaseModify {
            query: "DELETE FROM users WHERE id = 1".to_string(),
        };
        assert!(op.description().contains("DELETE"));
        assert_eq!(op.risk_level(), RiskLevel::Medium);
    }

    #[test]
    fn test_destructive_operation_shell_exec() {
        let op = DestructiveOperation::ShellExec {
            command: "rm -rf /very/long/path/to/delete/some/files".to_string(),
        };
        let desc = op.description();
        assert!(desc.contains("rm -rf"));
        assert_eq!(op.risk_level(), RiskLevel::Low);
    }

    #[test]
    fn test_detect_destructive_shell_rmdir() {
        let result = detect_destructive_shell_command("rmdir /tmp/empty");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_shell_git_force() {
        let result = detect_destructive_shell_command("git push --force origin main");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_shell_git_reset() {
        let result = detect_destructive_shell_command("git reset --hard HEAD~1");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_shell_git_clean() {
        let result = detect_destructive_shell_command("git clean -fd");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_shell_drop_table() {
        let result = detect_destructive_shell_command("psql -c 'DROP TABLE users'");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_shell_truncate() {
        let result = detect_destructive_shell_command("mysql -e 'TRUNCATE logs'");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_shell_dd() {
        let result = detect_destructive_shell_command("dd if=/dev/zero of=/dev/sda");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_shell_dev_redirect() {
        let result = detect_destructive_shell_command("echo test > /dev/sda");
        assert!(result.is_some());
    }

    #[test]
    fn test_detect_destructive_git_reset_hard() {
        let args = serde_json::json!({"hard": true});
        let result = detect_destructive_git_operation("git_reset", &args);
        assert!(matches!(result, Some(DestructiveOperation::GitResetHard)));
    }

    #[test]
    fn test_detect_destructive_git_reset_soft() {
        let args = serde_json::json!({"hard": false});
        let result = detect_destructive_git_operation("git_reset", &args);
        assert!(result.is_none());
    }

    #[test]
    fn test_detect_destructive_git_clean_operation() {
        let args = serde_json::json!({});
        let result = detect_destructive_git_operation("git_clean", &args);
        assert!(matches!(result, Some(DestructiveOperation::GitClean)));
    }

    #[test]
    fn test_detect_destructive_git_unknown() {
        let args = serde_json::json!({});
        let result = detect_destructive_git_operation("git_status", &args);
        assert!(result.is_none());
    }

    #[test]
    fn test_requires_confirmation_by_risk_level() {
        let config = ConfirmConfig {
            min_risk_level: RiskLevel::High,
            ..Default::default()
        };

        let medium_op = DestructiveOperation::FileDelete {
            path: "test.txt".to_string(),
        };
        // Medium risk should not require confirmation when min is High
        assert!(!requires_confirmation(
            "some_tool",
            Some(&medium_op),
            &config
        ));
    }

    #[test]
    fn test_requires_confirmation_high_risk() {
        let config = ConfirmConfig::default();

        let high_op = DestructiveOperation::GitResetHard;
        assert!(requires_confirmation("some_tool", Some(&high_op), &config));
    }

    #[test]
    fn test_confirm_result_equality() {
        assert_eq!(ConfirmResult::Approved, ConfirmResult::Approved);
        assert_eq!(ConfirmResult::Rejected, ConfirmResult::Rejected);
        assert_eq!(ConfirmResult::Skipped, ConfirmResult::Skipped);
        assert_eq!(ConfirmResult::NotRequired, ConfirmResult::NotRequired);
        assert_ne!(ConfirmResult::Approved, ConfirmResult::Rejected);
    }

    #[test]
    fn test_confirm_config_default_lists() {
        let config = ConfirmConfig::default();

        assert!(config.always_confirm.contains(&"git_push".to_string()));
        assert!(config.always_confirm.contains(&"file_delete".to_string()));
        assert!(config.never_confirm.contains(&"file_read".to_string()));
        assert!(config.never_confirm.contains(&"git_status".to_string()));
    }

    #[test]
    fn test_destructive_operation_git_force_push_description() {
        let op = DestructiveOperation::GitForcePush {
            branch: "main".to_string(),
        };
        let desc = op.description();
        assert!(desc.contains("Force push"));
        assert!(desc.contains("main"));
    }
}