Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

feat(ai): add approval store and dry-run simulator for AI Auto-Fix

rcourtman3febd3266e0d
diff --git a/internal/ai/approval/store.go b/internal/ai/approval/store.go
new file mode 100644
index 0000000000..b30a59f170
--- /dev/null
+++ b/internal/ai/approval/store.go
@@ -0,0 +1,575 @@
+package approval
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/rs/zerolog/log"
+)
+
+// ApprovalStatus represents the state of an approval request.
+type ApprovalStatus string
+
+const (
+ StatusPending ApprovalStatus = "pending"
+ StatusApproved ApprovalStatus = "approved"
+ StatusDenied ApprovalStatus = "denied"
+ StatusExpired ApprovalStatus = "expired"
+)
+
+// RiskLevel indicates the potential impact of a command.
+type RiskLevel string
+
+const (
+ RiskLow RiskLevel = "low"
+ RiskMedium RiskLevel = "medium"
+ RiskHigh RiskLevel = "high"
+)
+
+// ApprovalRequest represents a pending command awaiting user approval.
+type ApprovalRequest struct {
+ ID string `json:"id"`
+ ExecutionID string `json:"executionId"` // Groups related approvals
+ ToolID string `json:"toolId"` // From LLM tool call
+ Command string `json:"command"`
+ TargetType string `json:"targetType"` // host, container, vm, node
+ TargetID string `json:"targetId"`
+ TargetName string `json:"targetName"`
+ Context string `json:"context"` // Why AI wants to run this
+ RiskLevel RiskLevel `json:"riskLevel"` // low, medium, high
+ Status ApprovalStatus `json:"status"`
+ RequestedAt time.Time `json:"requestedAt"`
+ ExpiresAt time.Time `json:"expiresAt"`
+ DecidedAt *time.Time `json:"decidedAt,omitempty"`
+ DecidedBy string `json:"decidedBy,omitempty"`
+ DenyReason string `json:"denyReason,omitempty"`
+}
+
+// ExecutionState stores the AI conversation state for resumption after approval.
+type ExecutionState struct {
+ ID string `json:"id"`
+ OriginalRequest map[string]interface{} `json:"originalRequest"` // Serialized ExecuteRequest
+ Messages []map[string]interface{} `json:"messages"` // Conversation history
+ PendingToolCall map[string]interface{} `json:"pendingToolCall"` // Tool call awaiting approval
+ CreatedAt time.Time `json:"createdAt"`
+ ExpiresAt time.Time `json:"expiresAt"`
+}
+
+// Store manages approval requests and execution states.
+type Store struct {
+ mu sync.RWMutex
+ approvals map[string]*ApprovalRequest
+ executions map[string]*ExecutionState
+ dataDir string
+ defaultTimeout time.Duration
+ maxApprovals int
+}
+
+// StoreConfig configures the approval store.
+type StoreConfig struct {
+ DataDir string
+ DefaultTimeout time.Duration // Default 5 minutes
+ MaxApprovals int // Maximum pending approvals (default 100)
+}
+
+// NewStore creates a new approval store.
+func NewStore(cfg StoreConfig) (*Store, error) {
+ if cfg.DataDir == "" {
+ return nil, fmt.Errorf("data directory is required")
+ }
+
+ if cfg.DefaultTimeout == 0 {
+ cfg.DefaultTimeout = 5 * time.Minute
+ }
+
+ if cfg.MaxApprovals == 0 {
+ cfg.MaxApprovals = 100
+ }
+
+ s := &Store{
+ approvals: make(map[string]*ApprovalRequest),
+ executions: make(map[string]*ExecutionState),
+ dataDir: cfg.DataDir,
+ defaultTimeout: cfg.DefaultTimeout,
+ maxApprovals: cfg.MaxApprovals,
+ }
+
+ // Load existing data
+ if err := s.load(); err != nil {
+ log.Warn().Err(err).Msg("Failed to load approval data, starting fresh")
+ }
+
+ // Note: Call StartCleanup(ctx) after creating the store to begin cleanup goroutine
+
+ return s, nil
+}
+
+// CreateApproval creates a new approval request.
+func (s *Store) CreateApproval(req *ApprovalRequest) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ // Check capacity
+ pendingCount := 0
+ for _, a := range s.approvals {
+ if a.Status == StatusPending {
+ pendingCount++
+ }
+ }
+ if pendingCount >= s.maxApprovals {
+ return fmt.Errorf("maximum pending approvals (%d) reached", s.maxApprovals)
+ }
+
+ // Generate ID if not set
+ if req.ID == "" {
+ req.ID = uuid.New().String()
+ }
+
+ // Set defaults
+ req.Status = StatusPending
+ req.RequestedAt = time.Now()
+ if req.ExpiresAt.IsZero() {
+ req.ExpiresAt = req.RequestedAt.Add(s.defaultTimeout)
+ }
+
+ // Assess risk if not set
+ if req.RiskLevel == "" {
+ req.RiskLevel = AssessRiskLevel(req.Command, req.TargetType)
+ }
+
+ s.approvals[req.ID] = req
+
+ // Persist asynchronously
+ go s.save()
+
+ log.Info().
+ Str("id", req.ID).
+ Str("command", truncateCommand(req.Command, 50)).
+ Str("risk", string(req.RiskLevel)).
+ Msg("Created approval request")
+
+ return nil
+}
+
+// GetApproval returns an approval request by ID.
+func (s *Store) GetApproval(id string) (*ApprovalRequest, bool) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ req, ok := s.approvals[id]
+ if !ok {
+ return nil, false
+ }
+
+ // Check expiration
+ if req.Status == StatusPending && time.Now().After(req.ExpiresAt) {
+ // Don't modify here, let cleanup handle it
+ reqCopy := *req
+ reqCopy.Status = StatusExpired
+ return &reqCopy, true
+ }
+
+ return req, true
+}
+
+// GetPendingApprovals returns all pending approval requests.
+func (s *Store) GetPendingApprovals() []*ApprovalRequest {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ now := time.Now()
+ var pending []*ApprovalRequest
+
+ for _, req := range s.approvals {
+ if req.Status == StatusPending && now.Before(req.ExpiresAt) {
+ pending = append(pending, req)
+ }
+ }
+
+ return pending
+}
+
+// GetApprovalsByExecution returns all approvals for an execution ID.
+func (s *Store) GetApprovalsByExecution(executionID string) []*ApprovalRequest {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ var results []*ApprovalRequest
+ for _, req := range s.approvals {
+ if req.ExecutionID == executionID {
+ results = append(results, req)
+ }
+ }
+
+ return results
+}
+
+// Approve marks an approval request as approved.
+func (s *Store) Approve(id, username string) (*ApprovalRequest, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ req, ok := s.approvals[id]
+ if !ok {
+ return nil, fmt.Errorf("approval request not found: %s", id)
+ }
+
+ if req.Status != StatusPending {
+ return nil, fmt.Errorf("approval request is not pending (status: %s)", req.Status)
+ }
+
+ if time.Now().After(req.ExpiresAt) {
+ req.Status = StatusExpired
+ go s.save()
+ return nil, fmt.Errorf("approval request has expired")
+ }
+
+ now := time.Now()
+ req.Status = StatusApproved
+ req.DecidedAt = &now
+ req.DecidedBy = username
+
+ go s.save()
+
+ log.Info().
+ Str("id", id).
+ Str("by", username).
+ Str("command", truncateCommand(req.Command, 50)).
+ Msg("Approval request approved")
+
+ return req, nil
+}
+
+// Deny marks an approval request as denied.
+func (s *Store) Deny(id, username, reason string) (*ApprovalRequest, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ req, ok := s.approvals[id]
+ if !ok {
+ return nil, fmt.Errorf("approval request not found: %s", id)
+ }
+
+ if req.Status != StatusPending {
+ return nil, fmt.Errorf("approval request is not pending (status: %s)", req.Status)
+ }
+
+ now := time.Now()
+ req.Status = StatusDenied
+ req.DecidedAt = &now
+ req.DecidedBy = username
+ req.DenyReason = reason
+
+ go s.save()
+
+ log.Info().
+ Str("id", id).
+ Str("by", username).
+ Str("reason", reason).
+ Msg("Approval request denied")
+
+ return req, nil
+}
+
+// StoreExecution saves an execution state for later resumption.
+func (s *Store) StoreExecution(state *ExecutionState) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if state.ID == "" {
+ return fmt.Errorf("execution ID is required")
+ }
+
+ state.CreatedAt = time.Now()
+ if state.ExpiresAt.IsZero() {
+ state.ExpiresAt = state.CreatedAt.Add(s.defaultTimeout)
+ }
+
+ s.executions[state.ID] = state
+
+ go s.save()
+
+ return nil
+}
+
+// GetExecution returns an execution state by ID.
+func (s *Store) GetExecution(id string) (*ExecutionState, bool) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ state, ok := s.executions[id]
+ if !ok {
+ return nil, false
+ }
+
+ // Check expiration
+ if time.Now().After(state.ExpiresAt) {
+ return nil, false
+ }
+
+ return state, true
+}
+
+// DeleteExecution removes an execution state.
+func (s *Store) DeleteExecution(id string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ delete(s.executions, id)
+ go s.save()
+}
+
+// CleanupExpired removes expired approvals and executions.
+func (s *Store) CleanupExpired() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ now := time.Now()
+ cleaned := 0
+
+ // Expire pending approvals
+ for _, req := range s.approvals {
+ if req.Status == StatusPending && now.After(req.ExpiresAt) {
+ req.Status = StatusExpired
+ cleaned++
+ }
+ }
+
+ // Remove old completed approvals (keep for 24 hours)
+ cutoff := now.Add(-24 * time.Hour)
+ for id, req := range s.approvals {
+ if req.Status != StatusPending && req.DecidedAt != nil && req.DecidedAt.Before(cutoff) {
+ delete(s.approvals, id)
+ cleaned++
+ }
+ }
+
+ // Remove expired executions
+ for id, state := range s.executions {
+ if now.After(state.ExpiresAt) {
+ delete(s.executions, id)
+ cleaned++
+ }
+ }
+
+ if cleaned > 0 {
+ go s.save()
+ }
+
+ return cleaned
+}
+
+// GetStats returns statistics about the approval store.
+func (s *Store) GetStats() map[string]int {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ stats := map[string]int{
+ "pending": 0,
+ "approved": 0,
+ "denied": 0,
+ "expired": 0,
+ "executions": len(s.executions),
+ }
+
+ for _, req := range s.approvals {
+ switch req.Status {
+ case StatusPending:
+ stats["pending"]++
+ case StatusApproved:
+ stats["approved"]++
+ case StatusDenied:
+ stats["denied"]++
+ case StatusExpired:
+ stats["expired"]++
+ }
+ }
+
+ return stats
+}
+
+// Persistence
+
+func (s *Store) approvalsFile() string {
+ return filepath.Join(s.dataDir, "ai_approvals.json")
+}
+
+func (s *Store) executionsFile() string {
+ return filepath.Join(s.dataDir, "ai_executions.json")
+}
+
+func (s *Store) load() error {
+ // Load approvals
+ if data, err := os.ReadFile(s.approvalsFile()); err == nil {
+ var approvals []*ApprovalRequest
+ if err := json.Unmarshal(data, &approvals); err == nil {
+ for _, a := range approvals {
+ s.approvals[a.ID] = a
+ }
+ }
+ }
+
+ // Load executions
+ if data, err := os.ReadFile(s.executionsFile()); err == nil {
+ var executions []*ExecutionState
+ if err := json.Unmarshal(data, &executions); err == nil {
+ for _, e := range executions {
+ s.executions[e.ID] = e
+ }
+ }
+ }
+
+ return nil
+}
+
+func (s *Store) save() {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ // Save approvals
+ approvals := make([]*ApprovalRequest, 0, len(s.approvals))
+ for _, a := range s.approvals {
+ approvals = append(approvals, a)
+ }
+ if data, err := json.MarshalIndent(approvals, "", " "); err == nil {
+ os.WriteFile(s.approvalsFile(), data, 0600)
+ }
+
+ // Save executions
+ executions := make([]*ExecutionState, 0, len(s.executions))
+ for _, e := range s.executions {
+ executions = append(executions, e)
+ }
+ if data, err := json.MarshalIndent(executions, "", " "); err == nil {
+ os.WriteFile(s.executionsFile(), data, 0600)
+ }
+}
+
+// StartCleanup begins periodic cleanup of expired approvals and executions.
+// Call this with a context that cancels on shutdown.
+func (s *Store) StartCleanup(ctx context.Context) {
+ go s.cleanupLoop(ctx)
+}
+
+func (s *Store) cleanupLoop(ctx context.Context) {
+ ticker := time.NewTicker(1 * time.Minute)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ log.Debug().Msg("Approval store cleanup loop stopped")
+ return
+ case <-ticker.C:
+ cleaned := s.CleanupExpired()
+ if cleaned > 0 {
+ log.Debug().Int("count", cleaned).Msg("Cleaned up expired approval items")
+ }
+ }
+ }
+}
+
+// Risk Assessment
+
+// High risk patterns - destructive or system-wide impact
+var highRiskPatterns = []*regexp.Regexp{
+ regexp.MustCompile(`(?i)\brm\s+(-rf?|--recursive)\s`),
+ regexp.MustCompile(`(?i)\bdd\s+.*of=/dev/`),
+ regexp.MustCompile(`(?i)\bmkfs\b`),
+ regexp.MustCompile(`(?i)\bchmod\s+(-R\s+)?777\b`),
+ regexp.MustCompile(`(?i)\bapt\s+(remove|purge)\b`),
+ regexp.MustCompile(`(?i)\byum\s+(remove|erase)\b`),
+ regexp.MustCompile(`(?i)\bdnf\s+remove\b`),
+ regexp.MustCompile(`(?i)\bpacman\s+-R`),
+ regexp.MustCompile(`(?i)\biptables\s+-F\b`),
+ regexp.MustCompile(`(?i)\bsystemctl\s+(disable|mask)\b`),
+ regexp.MustCompile(`(?i)\bkill\s+-9\s`),
+ regexp.MustCompile(`(?i)\bpkill\s+-9\b`),
+ regexp.MustCompile(`(?i)\bdocker\s+rm\s+-f`),
+ regexp.MustCompile(`(?i)\bdocker\s+system\s+prune`),
+ regexp.MustCompile(`(?i)\bpct\s+destroy\b`),
+ regexp.MustCompile(`(?i)\bqm\s+destroy\b`),
+}
+
+// Medium risk patterns - service impact but recoverable
+var mediumRiskPatterns = []*regexp.Regexp{
+ regexp.MustCompile(`(?i)\bsystemctl\s+(restart|stop|start)\b`),
+ regexp.MustCompile(`(?i)\bservice\s+\S+\s+(restart|stop|start)\b`),
+ regexp.MustCompile(`(?i)\bdocker\s+(restart|stop|start|kill)\b`),
+ regexp.MustCompile(`(?i)\bapt\s+(update|upgrade|install)\b`),
+ regexp.MustCompile(`(?i)\byum\s+(update|install)\b`),
+ regexp.MustCompile(`(?i)\bdnf\s+(update|install)\b`),
+ regexp.MustCompile(`(?i)\bpct\s+(start|stop|reboot|resize)\b`),
+ regexp.MustCompile(`(?i)\bqm\s+(start|stop|reboot|resize)\b`),
+ regexp.MustCompile(`(?i)\bkill\b`),
+ regexp.MustCompile(`(?i)\bpkill\b`),
+ regexp.MustCompile(`(?i)\bchmod\b`),
+ regexp.MustCompile(`(?i)\bchown\b`),
+ regexp.MustCompile(`(?i)\bmv\s`),
+ regexp.MustCompile(`(?i)\bcp\s+-r`),
+}
+
+// AssessRiskLevel determines the risk level of a command.
+func AssessRiskLevel(command, targetType string) RiskLevel {
+ // Check high risk patterns first
+ for _, pattern := range highRiskPatterns {
+ if pattern.MatchString(command) {
+ return RiskHigh
+ }
+ }
+
+ // Check medium risk patterns
+ for _, pattern := range mediumRiskPatterns {
+ if pattern.MatchString(command) {
+ return RiskMedium
+ }
+ }
+
+ // Production targets are higher risk
+ if targetType == "node" {
+ // Commands on nodes are generally higher risk
+ for _, pattern := range mediumRiskPatterns {
+ if pattern.MatchString(command) {
+ return RiskHigh
+ }
+ }
+ }
+
+ return RiskLow
+}
+
+// Helper functions
+
+func truncateCommand(cmd string, maxLen int) string {
+ if len(cmd) <= maxLen {
+ return cmd
+ }
+ return cmd[:maxLen] + "..."
+}
+
+// Global store instance
+var (
+ globalStore *Store
+ storeMu sync.RWMutex
+)
+
+// SetStore sets the global approval store.
+func SetStore(s *Store) {
+ storeMu.Lock()
+ defer storeMu.Unlock()
+ globalStore = s
+}
+
+// GetStore returns the global approval store.
+func GetStore() *Store {
+ storeMu.RLock()
+ defer storeMu.RUnlock()
+ return globalStore
+}
diff --git a/internal/ai/approval/store_test.go b/internal/ai/approval/store_test.go
new file mode 100644
index 0000000000..b2d308aebe
--- /dev/null
+++ b/internal/ai/approval/store_test.go
@@ -0,0 +1,530 @@
+package approval
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+)
+
+func TestNewStore(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, err := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ MaxApprovals: 10,
+ })
+ if err != nil {
+ t.Fatalf("NewStore() error = %v", err)
+ }
+ if store == nil {
+ t.Fatal("NewStore() returned nil store")
+ }
+}
+
+func TestNewStoreEmptyDataDir(t *testing.T) {
+ _, err := NewStore(StoreConfig{
+ DataDir: "",
+ })
+ if err == nil {
+ t.Fatal("NewStore() expected error for empty data dir")
+ }
+}
+
+func TestCreateApproval(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ req := &ApprovalRequest{
+ ExecutionID: "exec-1",
+ ToolID: "tool-1",
+ Command: "systemctl restart nginx",
+ TargetType: "host",
+ TargetID: "host-1",
+ TargetName: "webserver",
+ Context: "Service needs restart due to config change",
+ }
+
+ err = store.CreateApproval(req)
+ if err != nil {
+ t.Fatalf("CreateApproval() error = %v", err)
+ }
+
+ if req.ID == "" {
+ t.Error("CreateApproval() did not set ID")
+ }
+ if req.Status != StatusPending {
+ t.Errorf("CreateApproval() status = %v, want %v", req.Status, StatusPending)
+ }
+ if req.RequestedAt.IsZero() {
+ t.Error("CreateApproval() did not set RequestedAt")
+ }
+ if req.ExpiresAt.IsZero() {
+ t.Error("CreateApproval() did not set ExpiresAt")
+ }
+}
+
+func TestGetApproval(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ req := &ApprovalRequest{
+ Command: "apt update",
+ }
+ store.CreateApproval(req)
+
+ got, found := store.GetApproval(req.ID)
+ if !found {
+ t.Fatal("GetApproval() not found")
+ }
+ if got.Command != "apt update" {
+ t.Errorf("GetApproval() command = %v, want %v", got.Command, "apt update")
+ }
+
+ _, found = store.GetApproval("nonexistent")
+ if found {
+ t.Error("GetApproval() found nonexistent approval")
+ }
+}
+
+func TestGetPendingApprovals(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ // Create multiple approvals
+ for i := 0; i < 3; i++ {
+ store.CreateApproval(&ApprovalRequest{
+ Command: "test command",
+ })
+ }
+
+ pending := store.GetPendingApprovals()
+ if len(pending) != 3 {
+ t.Errorf("GetPendingApprovals() count = %v, want %v", len(pending), 3)
+ }
+}
+
+func TestApprove(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ req := &ApprovalRequest{
+ Command: "systemctl restart nginx",
+ }
+ store.CreateApproval(req)
+
+ got, err := store.Approve(req.ID, "admin")
+ if err != nil {
+ t.Fatalf("Approve() error = %v", err)
+ }
+
+ if got.Status != StatusApproved {
+ t.Errorf("Approve() status = %v, want %v", got.Status, StatusApproved)
+ }
+ if got.DecidedBy != "admin" {
+ t.Errorf("Approve() DecidedBy = %v, want %v", got.DecidedBy, "admin")
+ }
+ if got.DecidedAt == nil {
+ t.Error("Approve() did not set DecidedAt")
+ }
+}
+
+func TestDeny(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ req := &ApprovalRequest{
+ Command: "rm -rf /tmp/data",
+ }
+ store.CreateApproval(req)
+
+ got, err := store.Deny(req.ID, "admin", "Too dangerous")
+ if err != nil {
+ t.Fatalf("Deny() error = %v", err)
+ }
+
+ if got.Status != StatusDenied {
+ t.Errorf("Deny() status = %v, want %v", got.Status, StatusDenied)
+ }
+ if got.DenyReason != "Too dangerous" {
+ t.Errorf("Deny() DenyReason = %v, want %v", got.DenyReason, "Too dangerous")
+ }
+}
+
+func TestApproveNonexistent(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ _, err = store.Approve("nonexistent", "admin")
+ if err == nil {
+ t.Error("Approve() expected error for nonexistent approval")
+ }
+}
+
+func TestApproveAlreadyDecided(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ req := &ApprovalRequest{
+ Command: "test",
+ }
+ store.CreateApproval(req)
+ _, _ = store.Deny(req.ID, "admin", "reason")
+
+ _, err = store.Approve(req.ID, "admin2")
+ if err == nil {
+ t.Error("Approve() expected error for already decided approval")
+ }
+}
+
+func TestExecutionState(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ state := &ExecutionState{
+ ID: "state-1",
+ OriginalRequest: map[string]interface{}{
+ "message": "test",
+ },
+ Messages: []map[string]interface{}{
+ {"role": "user", "content": "test"},
+ },
+ }
+
+ err = store.StoreExecution(state)
+ if err != nil {
+ t.Fatalf("StoreExecution() error = %v", err)
+ }
+
+ got, found := store.GetExecution(state.ID)
+ if !found {
+ t.Fatal("GetExecution() not found")
+ }
+ if got.ID != state.ID {
+ t.Errorf("GetExecution() ID = %v, want %v", got.ID, state.ID)
+ }
+
+ _, found = store.GetExecution("nonexistent")
+ if found {
+ t.Error("GetExecution() found nonexistent state")
+ }
+}
+
+func TestDeleteExecution(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ state := &ExecutionState{
+ ID: "state-1",
+ }
+ store.StoreExecution(state)
+
+ store.DeleteExecution(state.ID)
+
+ _, found := store.GetExecution(state.ID)
+ if found {
+ t.Error("DeleteExecution() did not delete state")
+ }
+}
+
+func TestCleanupExpired(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Millisecond, // Very short timeout
+ })
+
+ // Create an approval that will expire immediately
+ req := &ApprovalRequest{
+ Command: "test",
+ }
+ store.CreateApproval(req)
+
+ // Wait for expiration
+ time.Sleep(10 * time.Millisecond)
+
+ cleaned := store.CleanupExpired()
+ if cleaned != 1 {
+ t.Errorf("CleanupExpired() cleaned = %v, want %v", cleaned, 1)
+ }
+
+ got, found := store.GetApproval(req.ID)
+ if !found {
+ t.Fatal("Approval should still exist after cleanup")
+ }
+ if got.Status != StatusExpired {
+ t.Errorf("CleanupExpired() status = %v, want %v", got.Status, StatusExpired)
+ }
+}
+
+func TestStartCleanup(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ ctx, cancel := context.WithCancel(context.Background())
+ store.StartCleanup(ctx)
+
+ // Give cleanup goroutine a moment to start
+ time.Sleep(10 * time.Millisecond)
+
+ // Cancel should stop the cleanup loop
+ cancel()
+ time.Sleep(10 * time.Millisecond)
+}
+
+func TestAssessRiskLevel(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ targetType string
+ want RiskLevel
+ }{
+ {
+ name: "high risk rm -rf",
+ command: "rm -rf /var/log",
+ want: RiskHigh,
+ },
+ {
+ name: "high risk dd",
+ command: "dd if=/dev/zero of=/dev/sda",
+ want: RiskHigh,
+ },
+ {
+ name: "high risk apt purge",
+ command: "apt purge nginx",
+ want: RiskHigh,
+ },
+ {
+ name: "medium risk service restart",
+ command: "systemctl restart nginx",
+ want: RiskMedium,
+ },
+ {
+ name: "medium risk docker restart",
+ command: "docker restart mycontainer",
+ want: RiskMedium,
+ },
+ {
+ name: "medium risk apt install",
+ command: "apt install htop",
+ want: RiskMedium,
+ },
+ {
+ name: "low risk diagnostic",
+ command: "df -h",
+ want: RiskLow,
+ },
+ {
+ name: "low risk logs",
+ command: "journalctl -u nginx",
+ want: RiskLow,
+ },
+ {
+ name: "low risk status check",
+ command: "systemctl status nginx",
+ want: RiskLow,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := AssessRiskLevel(tt.command, tt.targetType)
+ if got != tt.want {
+ t.Errorf("AssessRiskLevel(%q) = %v, want %v", tt.command, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestStorePersistence(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ // Create store and add data
+ store1, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Hour,
+ })
+
+ req := &ApprovalRequest{
+ Command: "test command",
+ TargetID: "host-1",
+ TargetName: "webserver",
+ }
+ store1.CreateApproval(req)
+ approvalID := req.ID
+
+ state := &ExecutionState{
+ ID: "exec-1",
+ OriginalRequest: map[string]interface{}{
+ "message": "test",
+ },
+ }
+ store1.StoreExecution(state)
+
+ // Wait for async persistence to complete
+ time.Sleep(100 * time.Millisecond)
+
+ // Create new store from same directory
+ store2, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Hour,
+ })
+
+ // Verify data was loaded
+ loadedApproval, found := store2.GetApproval(approvalID)
+ if !found {
+ t.Fatal("Approval not persisted")
+ }
+ if loadedApproval.Command != "test command" {
+ t.Errorf("Persisted approval command = %v, want %v", loadedApproval.Command, "test command")
+ }
+
+ loadedState, found := store2.GetExecution("exec-1")
+ if !found {
+ t.Fatal("Execution state not persisted")
+ }
+ if loadedState.ID != "exec-1" {
+ t.Errorf("Persisted state ID = %v, want %v", loadedState.ID, "exec-1")
+ }
+}
+
+func TestMaxApprovals(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Hour,
+ MaxApprovals: 2,
+ })
+
+ // Create first two approvals - should succeed
+ store.CreateApproval(&ApprovalRequest{Command: "test1"})
+ store.CreateApproval(&ApprovalRequest{Command: "test2"})
+
+ // Third should fail
+ err = store.CreateApproval(&ApprovalRequest{Command: "test3"})
+ if err == nil {
+ t.Error("CreateApproval() expected error when max approvals reached")
+ }
+}
+
+func TestGlobalStore(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "approval-test-*")
+ if err != nil {
+ t.Fatalf("Failed to create temp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ store, _ := NewStore(StoreConfig{
+ DataDir: tmpDir,
+ DefaultTimeout: 1 * time.Minute,
+ })
+
+ SetStore(store)
+ got := GetStore()
+
+ if got != store {
+ t.Error("GetStore() did not return the set store")
+ }
+
+ // Reset global store
+ SetStore(nil)
+}
diff --git a/internal/ai/dryrun/simulator.go b/internal/ai/dryrun/simulator.go
new file mode 100644
index 0000000000..b5a7573237
--- /dev/null
+++ b/internal/ai/dryrun/simulator.go
@@ -0,0 +1,414 @@
+package dryrun
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+)
+
+// SimulationResult contains the simulated output of a command.
+type SimulationResult struct {
+ Output string `json:"output"`
+ ExitCode int `json:"exitCode"`
+ WouldDo string `json:"wouldDo"` // Human-readable description
+ Reversible bool `json:"reversible"` // Whether this action can be undone
+ RollbackCmd string `json:"rollbackCmd"` // Command to undo (if reversible)
+ Simulated bool `json:"simulated"` // Always true for dry-run
+}
+
+// simulationPattern defines how to simulate a command pattern.
+type simulationPattern struct {
+ match *regexp.Regexp
+ generate func(cmd string, matches []string) SimulationResult
+}
+
+// Simulator provides dry-run simulation for commands.
+type Simulator struct {
+ patterns []simulationPattern
+}
+
+// NewSimulator creates a new command simulator.
+func NewSimulator() *Simulator {
+ s := &Simulator{}
+ s.initPatterns()
+ return s
+}
+
+// Simulate returns a simulated result for a command without executing it.
+func (s *Simulator) Simulate(command string) SimulationResult {
+ for _, pattern := range s.patterns {
+ if matches := pattern.match.FindStringSubmatch(command); matches != nil {
+ result := pattern.generate(command, matches)
+ result.Simulated = true
+ return result
+ }
+ }
+
+ // Default simulation for unknown commands
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would execute: %s", command),
+ ExitCode: 0,
+ WouldDo: "Execute unknown command",
+ Reversible: false,
+ Simulated: true,
+ }
+}
+
+func (s *Simulator) initPatterns() {
+ s.patterns = []simulationPattern{
+ // systemctl operations
+ {
+ match: regexp.MustCompile(`(?i)systemctl\s+(restart|stop|start)\s+(\S+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ action := matches[1]
+ service := matches[2]
+ return SimulationResult{
+ Output: fmt.Sprintf(`[SIMULATED] %s.service - %s Service
+ Loaded: loaded (/lib/systemd/system/%s.service; enabled)
+ Active: active (running)
+
+Would %s service %s`, service, strings.Title(service), service, action, service),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("%s service %s", strings.Title(action), service),
+ Reversible: true,
+ RollbackCmd: fmt.Sprintf("systemctl %s %s", reverseAction(action), service),
+ }
+ },
+ },
+ // apt update
+ {
+ match: regexp.MustCompile(`(?i)apt\s+update`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ return SimulationResult{
+ Output: `[SIMULATED] Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease
+Hit:2 http://archive.ubuntu.com/ubuntu jammy-updates InRelease
+Hit:3 http://archive.ubuntu.com/ubuntu jammy-security InRelease
+Reading package lists... Done
+Building dependency tree... Done
+42 packages can be upgraded. Run 'apt list --upgradable' to see them.`,
+ ExitCode: 0,
+ WouldDo: "Update package lists from repositories",
+ Reversible: false, // Can't un-update
+ RollbackCmd: "",
+ }
+ },
+ },
+ // apt upgrade
+ {
+ match: regexp.MustCompile(`(?i)apt\s+(upgrade|dist-upgrade|full-upgrade)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ return SimulationResult{
+ Output: `[SIMULATED] Reading package lists... Done
+Building dependency tree... Done
+Calculating upgrade... Done
+The following packages will be upgraded:
+ base-files curl libcurl4 nginx openssh-client openssh-server
+ openssl libssl3 vim vim-common vim-runtime
+11 upgraded, 0 newly installed, 0 to remove.
+Need to get 15.2 MB of archives.
+After this operation, 128 kB of additional disk space will be used.
+
+Would upgrade 11 packages`,
+ ExitCode: 0,
+ WouldDo: "Upgrade 11 packages (base-files, curl, nginx, openssh, etc.)",
+ Reversible: false, // Package upgrades are hard to reverse
+ RollbackCmd: "",
+ }
+ },
+ },
+ // apt install
+ {
+ match: regexp.MustCompile(`(?i)apt\s+install\s+(.+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ packages := matches[1]
+ return SimulationResult{
+ Output: fmt.Sprintf(`[SIMULATED] Reading package lists... Done
+Building dependency tree... Done
+The following NEW packages will be installed:
+ %s
+0 upgraded, 1 newly installed, 0 to remove.
+Need to get 2.4 MB of archives.
+
+Would install: %s`, packages, packages),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("Install package(s): %s", packages),
+ Reversible: true,
+ RollbackCmd: fmt.Sprintf("apt remove %s", packages),
+ }
+ },
+ },
+ // apt remove
+ {
+ match: regexp.MustCompile(`(?i)apt\s+(remove|purge)\s+(.+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ action := matches[1]
+ packages := matches[2]
+ return SimulationResult{
+ Output: fmt.Sprintf(`[SIMULATED] Reading package lists... Done
+Building dependency tree... Done
+The following packages will be REMOVED:
+ %s
+0 upgraded, 0 newly installed, 1 to remove.
+After this operation, 5.2 MB disk space will be freed.
+
+Would %s: %s`, packages, action, packages),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("Remove package(s): %s", packages),
+ Reversible: true,
+ RollbackCmd: fmt.Sprintf("apt install %s", packages),
+ }
+ },
+ },
+ // docker restart/stop/start
+ {
+ match: regexp.MustCompile(`(?i)docker\s+(restart|stop|start)\s+(\S+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ action := matches[1]
+ container := matches[2]
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] %s\nWould %s container %s", container, action, container),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("%s container %s", strings.Title(action), container),
+ Reversible: true,
+ RollbackCmd: fmt.Sprintf("docker %s %s", reverseAction(action), container),
+ }
+ },
+ },
+ // docker exec
+ {
+ match: regexp.MustCompile(`(?i)docker\s+exec\s+(?:-it?\s+)?(\S+)\s+(.+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ container := matches[1]
+ execCmd := matches[2]
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would execute in container %s: %s", container, execCmd),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("Execute command in container %s", container),
+ Reversible: false,
+ RollbackCmd: "",
+ }
+ },
+ },
+ // pct operations (Proxmox containers)
+ {
+ match: regexp.MustCompile(`(?i)pct\s+(start|stop|reboot)\s+(\d+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ action := matches[1]
+ vmid := matches[2]
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would %s container %s", action, vmid),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("%s LXC container %s", strings.Title(action), vmid),
+ Reversible: true,
+ RollbackCmd: fmt.Sprintf("pct %s %s", reverseAction(action), vmid),
+ }
+ },
+ },
+ // pct resize
+ {
+ match: regexp.MustCompile(`(?i)pct\s+resize\s+(\d+)\s+(\S+)\s+([+-]?\d+[KMGT]?)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ vmid := matches[1]
+ disk := matches[2]
+ size := matches[3]
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would resize container %s disk %s by %s", vmid, disk, size),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("Resize container %s disk %s by %s", vmid, disk, size),
+ Reversible: strings.HasPrefix(size, "+"), // Only growth is "reversible" (shrink back)
+ RollbackCmd: "", // Disk resize is complex to reverse
+ }
+ },
+ },
+ // qm operations (Proxmox VMs)
+ {
+ match: regexp.MustCompile(`(?i)qm\s+(start|stop|reboot|shutdown)\s+(\d+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ action := matches[1]
+ vmid := matches[2]
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would %s VM %s", action, vmid),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("%s VM %s", strings.Title(action), vmid),
+ Reversible: true,
+ RollbackCmd: fmt.Sprintf("qm %s %s", reverseAction(action), vmid),
+ }
+ },
+ },
+ // kill process
+ {
+ match: regexp.MustCompile(`(?i)kill\s+(-\d+\s+)?(\d+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ signal := strings.TrimSpace(matches[1])
+ pid := matches[2]
+ if signal == "" {
+ signal = "-15"
+ }
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would send signal %s to process %s", signal, pid),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("Send signal %s to process %s", signal, pid),
+ Reversible: false,
+ RollbackCmd: "",
+ }
+ },
+ },
+ // pkill
+ {
+ match: regexp.MustCompile(`(?i)pkill\s+(?:-\d+\s+)?(\S+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ process := matches[1]
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would kill processes matching: %s", process),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("Kill processes matching '%s'", process),
+ Reversible: false,
+ RollbackCmd: "",
+ }
+ },
+ },
+ // rm files
+ {
+ match: regexp.MustCompile(`(?i)rm\s+(-[rf]+\s+)?(.+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ flags := strings.TrimSpace(matches[1])
+ path := matches[2]
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would remove: %s (flags: %s)", path, flags),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("Remove %s", path),
+ Reversible: false, // File deletion is not reversible
+ RollbackCmd: "",
+ }
+ },
+ },
+ // chmod
+ {
+ match: regexp.MustCompile(`(?i)chmod\s+(-R\s+)?(\d+|[ugoa][+-=][rwx]+)\s+(.+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ recursive := matches[1] != ""
+ mode := matches[2]
+ path := matches[3]
+ desc := fmt.Sprintf("Change permissions of %s to %s", path, mode)
+ if recursive {
+ desc += " (recursive)"
+ }
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would %s", strings.ToLower(desc)),
+ ExitCode: 0,
+ WouldDo: desc,
+ Reversible: false, // Would need to record old permissions
+ RollbackCmd: "",
+ }
+ },
+ },
+ // chown
+ {
+ match: regexp.MustCompile(`(?i)chown\s+(-R\s+)?(\S+)\s+(.+)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ recursive := matches[1] != ""
+ owner := matches[2]
+ path := matches[3]
+ desc := fmt.Sprintf("Change owner of %s to %s", path, owner)
+ if recursive {
+ desc += " (recursive)"
+ }
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would %s", strings.ToLower(desc)),
+ ExitCode: 0,
+ WouldDo: desc,
+ Reversible: false,
+ RollbackCmd: "",
+ }
+ },
+ },
+ // nginx reload/restart
+ {
+ match: regexp.MustCompile(`(?i)nginx\s+(-s\s+)?(reload|restart|stop|start)`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ action := matches[2]
+ return SimulationResult{
+ Output: fmt.Sprintf("[SIMULATED] Would %s nginx", action),
+ ExitCode: 0,
+ WouldDo: fmt.Sprintf("%s nginx", strings.Title(action)),
+ Reversible: true,
+ RollbackCmd: fmt.Sprintf("nginx -s %s", reverseAction(action)),
+ }
+ },
+ },
+ // df (disk free) - diagnostic
+ {
+ match: regexp.MustCompile(`(?i)^df\b`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ return SimulationResult{
+ Output: `[SIMULATED] Filesystem Size Used Avail Use% Mounted on
+/dev/sda1 100G 45G 55G 45% /
+/dev/sdb1 500G 200G 300G 40% /data
+tmpfs 16G 1.2G 15G 8% /dev/shm`,
+ ExitCode: 0,
+ WouldDo: "Display disk space usage",
+ Reversible: true, // Read-only
+ RollbackCmd: "",
+ }
+ },
+ },
+ // free (memory) - diagnostic
+ {
+ match: regexp.MustCompile(`(?i)^free\b`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ return SimulationResult{
+ Output: `[SIMULATED] total used free shared buff/cache available
+Mem: 32768000 12500000 8200000 512000 12068000 19200000
+Swap: 8192000 100000 8092000`,
+ ExitCode: 0,
+ WouldDo: "Display memory usage",
+ Reversible: true, // Read-only
+ RollbackCmd: "",
+ }
+ },
+ },
+ // journalctl - diagnostic
+ {
+ match: regexp.MustCompile(`(?i)^journalctl\b`),
+ generate: func(cmd string, matches []string) SimulationResult {
+ return SimulationResult{
+ Output: `[SIMULATED] -- Logs begin at Mon 2024-01-01 00:00:00 UTC, end at now. --
+Jan 11 10:00:00 server systemd[1]: Started Session 1 of user admin.
+Jan 11 10:00:01 server nginx[1234]: 10.0.0.1 - - [11/Jan/2024:10:00:01 +0000] "GET / HTTP/1.1" 200
+Jan 11 10:00:02 server sshd[5678]: Accepted publickey for admin from 10.0.0.2`,
+ ExitCode: 0,
+ WouldDo: "Display system logs",
+ Reversible: true, // Read-only
+ RollbackCmd: "",
+ }
+ },
+ },
+ }
+}
+
+// reverseAction returns the opposite action for rollback.
+func reverseAction(action string) string {
+ action = strings.ToLower(action)
+ switch action {
+ case "start":
+ return "stop"
+ case "stop":
+ return "start"
+ case "restart":
+ return "restart" // Idempotent
+ case "reboot":
+ return "start"
+ case "reload":
+ return "reload"
+ default:
+ return action
+ }
+}
+
+// Global simulator instance
+var defaultSimulator = NewSimulator()
+
+// Simulate uses the default simulator to simulate a command.
+func Simulate(command string) SimulationResult {
+ return defaultSimulator.Simulate(command)
+}
diff --git a/internal/ai/dryrun/simulator_test.go b/internal/ai/dryrun/simulator_test.go
new file mode 100644
index 0000000000..3e350cf273
--- /dev/null
+++ b/internal/ai/dryrun/simulator_test.go
@@ -0,0 +1,485 @@
+package dryrun
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestSimulator_Systemctl(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ wantWouldDo string
+ wantReverse bool
+ wantRollback string
+ }{
+ {
+ name: "restart service",
+ command: "systemctl restart nginx",
+ wantWouldDo: "Restart service nginx",
+ wantReverse: true,
+ wantRollback: "systemctl restart nginx",
+ },
+ {
+ name: "stop service",
+ command: "systemctl stop apache2",
+ wantWouldDo: "Stop service apache2",
+ wantReverse: true,
+ wantRollback: "systemctl start apache2",
+ },
+ {
+ name: "start service",
+ command: "systemctl start mysql",
+ wantWouldDo: "Start service mysql",
+ wantReverse: true,
+ wantRollback: "systemctl stop mysql",
+ },
+ }
+
+ sim := NewSimulator()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sim.Simulate(tt.command)
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, tt.wantWouldDo) {
+ t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)
+ }
+
+ if result.Reversible != tt.wantReverse {
+ t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)
+ }
+
+ if tt.wantRollback != "" && result.RollbackCmd != tt.wantRollback {
+ t.Errorf("Simulate() RollbackCmd = %q, want %q", result.RollbackCmd, tt.wantRollback)
+ }
+
+ if result.ExitCode != 0 {
+ t.Errorf("Simulate() ExitCode = %v, want 0", result.ExitCode)
+ }
+
+ if !strings.Contains(result.Output, "[SIMULATED]") {
+ t.Errorf("Simulate() Output should contain [SIMULATED]")
+ }
+ })
+ }
+}
+
+func TestSimulator_Apt(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ wantWouldDo string
+ wantReverse bool
+ }{
+ {
+ name: "apt update",
+ command: "apt update",
+ wantWouldDo: "Update package lists",
+ wantReverse: false,
+ },
+ {
+ name: "apt upgrade",
+ command: "apt upgrade",
+ wantWouldDo: "Upgrade",
+ wantReverse: false,
+ },
+ {
+ name: "apt install",
+ command: "apt install htop vim",
+ wantWouldDo: "Install package",
+ wantReverse: true,
+ },
+ {
+ name: "apt remove",
+ command: "apt remove nginx",
+ wantWouldDo: "Remove package",
+ wantReverse: true,
+ },
+ }
+
+ sim := NewSimulator()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sim.Simulate(tt.command)
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, tt.wantWouldDo) {
+ t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)
+ }
+
+ if result.Reversible != tt.wantReverse {
+ t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)
+ }
+ })
+ }
+}
+
+func TestSimulator_Docker(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ wantWouldDo string
+ wantReverse bool
+ }{
+ {
+ name: "docker restart",
+ command: "docker restart myapp",
+ wantWouldDo: "Restart container myapp",
+ wantReverse: true,
+ },
+ {
+ name: "docker stop",
+ command: "docker stop webserver",
+ wantWouldDo: "Stop container webserver",
+ wantReverse: true,
+ },
+ {
+ name: "docker exec",
+ command: "docker exec -it nginx bash",
+ wantWouldDo: "Execute command in container",
+ wantReverse: false,
+ },
+ }
+
+ sim := NewSimulator()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sim.Simulate(tt.command)
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, tt.wantWouldDo) {
+ t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)
+ }
+
+ if result.Reversible != tt.wantReverse {
+ t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)
+ }
+ })
+ }
+}
+
+func TestSimulator_Proxmox(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ wantWouldDo string
+ wantReverse bool
+ }{
+ {
+ name: "pct start container",
+ command: "pct start 100",
+ wantWouldDo: "Start LXC container 100",
+ wantReverse: true,
+ },
+ {
+ name: "pct stop container",
+ command: "pct stop 101",
+ wantWouldDo: "Stop LXC container 101",
+ wantReverse: true,
+ },
+ {
+ name: "qm start VM",
+ command: "qm start 200",
+ wantWouldDo: "Start VM 200",
+ wantReverse: true,
+ },
+ {
+ name: "qm shutdown VM",
+ command: "qm shutdown 201",
+ wantWouldDo: "Shutdown VM 201",
+ wantReverse: true,
+ },
+ {
+ name: "pct resize",
+ command: "pct resize 100 rootfs +10G",
+ wantWouldDo: "Resize container 100",
+ wantReverse: true, // Growth is "reversible" in the sense we can shrink
+ },
+ }
+
+ sim := NewSimulator()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sim.Simulate(tt.command)
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, tt.wantWouldDo) {
+ t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)
+ }
+
+ if result.Reversible != tt.wantReverse {
+ t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)
+ }
+ })
+ }
+}
+
+func TestSimulator_ProcessManagement(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ wantWouldDo string
+ wantReverse bool
+ }{
+ {
+ name: "kill process",
+ command: "kill 12345",
+ wantWouldDo: "Send signal",
+ wantReverse: false,
+ },
+ {
+ name: "kill with signal",
+ command: "kill -9 12345",
+ wantWouldDo: "Send signal -9",
+ wantReverse: false,
+ },
+ {
+ name: "pkill process",
+ command: "pkill nginx",
+ wantWouldDo: "Kill processes matching 'nginx'",
+ wantReverse: false,
+ },
+ }
+
+ sim := NewSimulator()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sim.Simulate(tt.command)
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, tt.wantWouldDo) {
+ t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)
+ }
+
+ if result.Reversible != tt.wantReverse {
+ t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)
+ }
+ })
+ }
+}
+
+func TestSimulator_FileOperations(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ wantWouldDo string
+ wantReverse bool
+ }{
+ {
+ name: "rm file",
+ command: "rm /tmp/test.log",
+ wantWouldDo: "Remove",
+ wantReverse: false,
+ },
+ {
+ name: "rm recursive",
+ command: "rm -rf /tmp/data",
+ wantWouldDo: "Remove",
+ wantReverse: false,
+ },
+ {
+ name: "chmod",
+ command: "chmod 755 /usr/local/bin/script.sh",
+ wantWouldDo: "Change permissions",
+ wantReverse: false,
+ },
+ {
+ name: "chown",
+ command: "chown www-data:www-data /var/www",
+ wantWouldDo: "Change owner",
+ wantReverse: false,
+ },
+ }
+
+ sim := NewSimulator()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sim.Simulate(tt.command)
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, tt.wantWouldDo) {
+ t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)
+ }
+
+ if result.Reversible != tt.wantReverse {
+ t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)
+ }
+ })
+ }
+}
+
+func TestSimulator_Diagnostics(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ wantWouldDo string
+ wantReverse bool
+ }{
+ {
+ name: "df disk free",
+ command: "df -h",
+ wantWouldDo: "Display disk space",
+ wantReverse: true, // Read-only
+ },
+ {
+ name: "free memory",
+ command: "free -m",
+ wantWouldDo: "Display memory usage",
+ wantReverse: true, // Read-only
+ },
+ {
+ name: "journalctl",
+ command: "journalctl -u nginx -n 100",
+ wantWouldDo: "Display system logs",
+ wantReverse: true, // Read-only
+ },
+ }
+
+ sim := NewSimulator()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sim.Simulate(tt.command)
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, tt.wantWouldDo) {
+ t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)
+ }
+
+ if result.Reversible != tt.wantReverse {
+ t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)
+ }
+ })
+ }
+}
+
+func TestSimulator_Nginx(t *testing.T) {
+ tests := []struct {
+ name string
+ command string
+ wantWouldDo string
+ wantReverse bool
+ }{
+ {
+ name: "nginx reload",
+ command: "nginx -s reload",
+ wantWouldDo: "Reload nginx",
+ wantReverse: true,
+ },
+ {
+ name: "nginx restart",
+ command: "nginx -s restart",
+ wantWouldDo: "Restart nginx",
+ wantReverse: true,
+ },
+ }
+
+ sim := NewSimulator()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := sim.Simulate(tt.command)
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, tt.wantWouldDo) {
+ t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)
+ }
+
+ if result.Reversible != tt.wantReverse {
+ t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)
+ }
+ })
+ }
+}
+
+func TestSimulator_UnknownCommand(t *testing.T) {
+ sim := NewSimulator()
+
+ result := sim.Simulate("some-unknown-command --arg1 --arg2")
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if result.WouldDo != "Execute unknown command" {
+ t.Errorf("Simulate() WouldDo = %q, want %q", result.WouldDo, "Execute unknown command")
+ }
+
+ if result.Reversible {
+ t.Error("Simulate() unknown command should not be reversible")
+ }
+
+ if !strings.Contains(result.Output, "[SIMULATED]") {
+ t.Error("Simulate() Output should contain [SIMULATED]")
+ }
+
+ if !strings.Contains(result.Output, "some-unknown-command") {
+ t.Error("Simulate() Output should contain the original command")
+ }
+}
+
+func TestGlobalSimulate(t *testing.T) {
+ result := Simulate("systemctl restart nginx")
+
+ if !result.Simulated {
+ t.Error("Simulate() Simulated = false, want true")
+ }
+
+ if !strings.Contains(result.WouldDo, "Restart") {
+ t.Errorf("Simulate() WouldDo = %q, want to contain 'Restart'", result.WouldDo)
+ }
+}
+
+func TestReverseAction(t *testing.T) {
+ tests := []struct {
+ action string
+ want string
+ }{
+ {"start", "stop"},
+ {"stop", "start"},
+ {"restart", "restart"},
+ {"reboot", "start"},
+ {"reload", "reload"},
+ {"unknown", "unknown"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.action, func(t *testing.T) {
+ got := reverseAction(tt.action)
+ if got != tt.want {
+ t.Errorf("reverseAction(%q) = %q, want %q", tt.action, got, tt.want)
+ }
+ })
+ }
+}