Skip to content

Implement automatic fixes for doctor command (--fix flag) #75

@rrrodzilla

Description

@rrrodzilla

Context

The doctor command has a --fix flag that currently only prints placeholder text but doesn't implement any automatic remediation of detected issues.

Location: src/commands/doctor.rs:61

Current Behavior

When running crately doctor --fix:

Running system diagnostics...

Auto-fix mode: enabled

Diagnostics to be implemented:
  - Configuration file validation
  - Database connectivity check
  - File system permissions
  - Dependency verification
  - Runtime environment checks

Auto-fix mode would attempt to resolve issues here

Doctor diagnostics complete

Expected Behavior

The --fix flag should automatically attempt to remediate issues detected by the diagnostic checks:

Running system diagnostics...

Auto-fix mode: enabled

Configuration File............... ✗ Missing
  → Creating default configuration...
  ✓ Created: ~/.config/crately/config.toml

Cache Directory.................. ✗ Not writable
  → Fixing permissions...
  ✓ Fixed: chmod 755 ~/.cache/crately

Database Schema.................. ✗ Not initialized
  → Initializing database schema...
  ✓ Schema initialized

Logs Directory................... ✗ Missing
  → Creating directory...
  ✓ Created: ~/.local/share/crately/logs

✓ All issues resolved - system is now healthy

Implementation Requirements

Automatic Fixes to Implement

  1. Create Missing Configuration File

    • Generate default config.toml at XDG_CONFIG_HOME/crately/config.toml
    • Use sensible defaults from Config::default()
    • Preserve existing config if partial
    • Prompt for critical values (API key) or note they need manual setup
  2. Fix File Permissions

    • Make directories readable/writable: chmod 755
    • Only fix permissions for directories owned by current user
    • Skip if insufficient privileges, report to user
  3. Initialize Database Schema

    • Create database if missing
    • Run schema initialization (CREATE TABLE statements)
    • Verify schema after creation
  4. Clean Up Temporary Files

    • Remove stale lock files
    • Clear corrupted cache entries
    • Remove incomplete downloads
  5. Create Missing Directories

    • XDG_CONFIG_HOME/crately
    • XDG_DATA_HOME/crately
    • XDG_DATA_HOME/crately/logs
    • XDG_CACHE_HOME/crately
    • Database directory

What NOT to Auto-Fix

Some issues require manual intervention and should not be auto-fixed:

  • Invalid API keys (must be manually configured)
  • Database locked by another process (user must stop other instance)
  • Insufficient disk space (user must free space)
  • Network connectivity issues (outside application control)

Safety Considerations

  • Never delete user data without explicit confirmation
  • Never modify files outside application directories
  • Never change system-level settings (network, permissions outside app dirs)
  • Always verify fixes succeeded before marking as resolved
  • Log all fixes to logs for audit trail

User Confirmation for Destructive Actions

For potentially destructive operations, require explicit user confirmation even in --fix mode:

Database Corrupted................. ✗ Cannot recover

  The database appears corrupted and cannot be repaired automatically.
  
  Options:
    1. Backup and delete: mv ~/.local/share/crately/db ~/.local/share/crately/db.backup
    2. Keep and investigate: See logs at ~/.local/share/crately/logs/
    
  Auto-fix cannot proceed without confirmation.
  Delete corrupted database and start fresh? [y/N]: 

Files to Modify

  • src/commands/doctor.rs - Implement fix logic (lines 61-66)
  • src/actors/config.rs - May need helper to generate default config
  • src/database.rs - Schema initialization functions
  • CLAUDE.md - Update documentation

Implementation Pattern

// In doctor.rs
if args.fix {
    println!("Auto-fix mode: enabled\n");
    
    let fixes_applied = apply_automatic_fixes(&diagnostics)?;
    
    if fixes_applied > 0 {
        println!("\n✓ Applied {} automatic fixes", fixes_applied);
        println!("\nRe-running diagnostics to verify...");
        
        // Re-run diagnostics to confirm fixes worked
        run_diagnostics(args)?;
    }
}

fn apply_automatic_fixes(diagnostics: &DiagnosticResults) -> Result<usize> {
    let mut fixes_applied = 0;
    
    if diagnostics.config_missing {
        fix_missing_config()?;
        fixes_applied += 1;
    }
    
    if diagnostics.permissions_issues {
        fix_permissions()?;
        fixes_applied += 1;
    }
    
    // ... more fixes
    
    Ok(fixes_applied)
}

fn fix_missing_config() -> Result<()> {
    print!("  → Creating default configuration... ");
    
    let config = Config::default();
    let config_path = get_config_path()?;
    
    std::fs::create_dir_all(config_path.parent().unwrap())?;
    
    let toml = toml::to_string_pretty(&config)?;
    std::fs::write(&config_path, toml)?;
    
    println!("✓ Created: {}", config_path.display());
    
    Ok(())
}

Testing Requirements

  • Automatic fixes implemented for all fixable issues
  • Non-fixable issues report appropriate messages
  • Fixes are verified after application
  • No data loss or corruption from fixes
  • Logs record all fixes applied
  • All tests pass: cargo nextest run
  • No clippy lints: cargo clippy --all-targets

Success Criteria

  • All fixable issues can be automatically remediated
  • Non-fixable issues clearly explain manual steps
  • Fixes are safe (no data loss, no system modifications)
  • Re-running diagnostics after fix shows issues resolved
  • Audit trail of fixes in log files
  • Documentation updated with fix capabilities

Related Files

  • src/commands/doctor.rs - Main implementation needed (lines 61-66)
  • src/actors/config.rs - Config generation
  • CLAUDE.md - Documentation to update

Dependencies

Blocked by: #74 - Implement diagnostic checks for doctor command

This issue requires the diagnostic checks from #74 to be implemented first, as the fix logic depends on knowing what issues exist.

Priority

Low - Nice-to-have automation, diagnostic reporting (#74) is more critical

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions