Release v1.21.0: Add macos-cleaner skill

- Add macos-cleaner v1.0.0 - Intelligent macOS disk space recovery
- Safety-first philosophy with risk categorization (Safe/Caution/Keep)
- Smart analysis: caches, app remnants, large files, dev environments
- Interactive cleanup with explicit user confirmation
- Bundled scripts: analyze_caches, analyze_dev_env, analyze_large_files,
  find_app_remnants, safe_delete, cleanup_report
- Comprehensive references: cleanup_targets, mole_integration, safety_rules
- Update marketplace to v1.21.0
- Update all documentation (README.md, README.zh-CN.md, CHANGELOG.md, CLAUDE.md)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
daymade
2026-01-11 15:59:13 +08:00
parent 3f2f8f02ca
commit 4d6ed53c1e
16 changed files with 3546 additions and 10 deletions

View File

@@ -0,0 +1,430 @@
# macOS Cleanup Targets Reference
Detailed explanations of cleanup targets, their safety levels, and impact.
## System Caches
### ~/Library/Caches
**What it is**: Application-level cache storage for user applications.
**Contents**:
- Browser caches (Chrome, Firefox, Safari)
- Application temporary files
- Download caches
- Thumbnail caches
- Font caches
**Safety**: 🟢 **Safe to delete**
**Impact**:
- Apps may be slower on first launch after deletion
- Websites may load slower on first visit (need to re-download assets)
- No data loss (caches are regenerated)
**Size**: Typically 10-100 GB depending on usage
**Cleanup command**:
```bash
rm -rf ~/Library/Caches/*
```
### /Library/Caches
**What it is**: System-level cache storage (shared across all users).
**Safety**: 🟢 **Safe to delete** (requires sudo)
**Impact**: Same as user caches, but system-wide
**Cleanup command**:
```bash
sudo rm -rf /Library/Caches/*
```
### Package Manager Caches
#### Homebrew Cache
**Location**: `$(brew --cache)` (typically `~/Library/Caches/Homebrew`)
**What it is**: Downloaded package installers and build artifacts
**Safety**: 🟢 **Safe to delete**
**Impact**: Will need to re-download packages on next install/upgrade
**Cleanup**:
```bash
brew cleanup -s # Safe cleanup (removes old versions)
brew cleanup --prune=all # Aggressive cleanup (removes all cached downloads)
```
#### npm Cache
**Location**: `~/.npm` or configured cache directory
**Safety**: 🟢 **Safe to delete**
**Impact**: Packages will be re-downloaded when needed
**Cleanup**:
```bash
npm cache clean --force
```
#### pip Cache
**Location**: `~/Library/Caches/pip` (macOS)
**Safety**: 🟢 **Safe to delete**
**Impact**: Packages will be re-downloaded when needed
**Cleanup**:
```bash
pip cache purge
# or for pip3
pip3 cache purge
```
## Application Logs
### ~/Library/Logs
**What it is**: Application log files
**Safety**: 🟢 **Safe to delete**
**Impact**: Loss of diagnostic information (only matters if debugging)
**Typical size**: 1-20 GB
**Cleanup**:
```bash
rm -rf ~/Library/Logs/*
```
### /var/log (System Logs)
**What it is**: System and service log files
**Safety**: 🟢 **Safe to delete old logs** (requires sudo)
**Impact**: Loss of system diagnostic history
**Note**: macOS automatically rotates logs, manual deletion rarely needed
## Application Data
### ~/Library/Application Support
**What it is**: Persistent application data, settings, and databases
**Safety**: 🟡 **Caution required**
**Contains**:
- Application databases
- User preferences and settings
- Downloaded content
- Plugins and extensions
- Save games
**When safe to delete**:
- Application is confirmed uninstalled
- Folder belongs to trial software no longer used
- Folder is for outdated version of app (check first!)
**When to KEEP**:
- Active applications
- Any folder you're uncertain about
**Recommendation**: Use `find_app_remnants.py` to identify orphaned data
### ~/Library/Containers
**What it is**: Sandboxed application data (for App Store apps)
**Safety**: 🟡 **Caution required**
**Same rules** as Application Support - only delete for uninstalled apps
### ~/Library/Preferences
**What it is**: Application preference files (.plist)
**Safety**: 🟡 **Caution required**
**Impact of deletion**: App returns to default settings
**When to delete**:
- App is confirmed uninstalled
- Troubleshooting a misbehaving app (as last resort)
## Development Environment
### Docker
#### Images
**What it is**: Container images (base OS + application layers)
**Safety**: 🟢 **Safe to delete unused images**
**Check first**:
```bash
docker images
```
**Cleanup**:
```bash
docker image prune -a # Remove all unused images
```
#### Containers
**What it is**: Running or stopped container instances
**Safety**: 🟢 **Safe to delete stopped containers**
**Check first**:
```bash
docker ps -a
```
**Cleanup**:
```bash
docker container prune # Remove stopped containers
```
#### Volumes
**What it is**: Persistent data storage for containers
**Safety**: 🔴 **CAUTION - May contain important data**
**Check first**:
```bash
docker volume ls
docker volume inspect <volume_name>
```
**Cleanup** (only if certain):
```bash
docker volume prune # Remove unused volumes
```
#### Build Cache
**What it is**: Intermediate build layers
**Safety**: 🟢 **Safe to delete**
**Cleanup**:
```bash
docker builder prune -a
```
#### All-in-one cleanup
⚠️ **WARNING**: This removes ALL unused Docker resources including volumes!
```bash
docker system prune -a --volumes
```
### node_modules
**What it is**: Installed npm packages for Node.js projects
**Safety**: 🟢 **Safe to delete** (can be regenerated)
**Impact**: Need to run `npm install` to restore
**Finding large node_modules**:
```bash
find ~ -name "node_modules" -type d -prune -print 2>/dev/null | while read dir; do
du -sh "$dir"
done | sort -hr
```
**Cleanup**:
```bash
# For old projects
rm -rf /path/to/old-project/node_modules
```
### Python Virtual Environments
**What it is**: Isolated Python environments
**Location**: `venv/`, `.venv/`, `env/` in project directories
**Safety**: 🟢 **Safe to delete** (can be recreated)
**Impact**: Need to recreate virtualenv and reinstall packages
**Finding venvs**:
```bash
find ~ -type d -name "venv" -o -name ".venv" 2>/dev/null
```
### Git Repositories (.git directories)
**What it is**: Git version control data
**Safety**: 🟡 **Depends on use case**
**When SAFE to delete**:
- Project is archived and you have remote backup
- You only need final code, not history
**When to KEEP**:
- Active development
- No remote backup exists
- You might need the history
**Cleanup** (convert to plain folder, lose history):
```bash
rm -rf /path/to/old-project/.git
```
## Large Files
### Downloads Folder
**What it is**: Files downloaded from internet
**Safety**: 🟡 **User judgment required**
**Common cleanable items**:
- Old installers (.dmg, .pkg)
- Zip archives already extracted
- Temporary downloads
- Duplicate files
**Check before deleting**: Might contain important downloads
### Disk Images (.dmg, .iso)
**What it is**: Mountable disk images, often installers
**Safety**: 🟢 **Safe to delete after installation**
**Typical location**: ~/Downloads
**Cleanup**: Delete .dmg files for already-installed apps
### Archives (.zip, .tar.gz)
**What it is**: Compressed archives
**Safety**: 🟡 **Check if extracted**
**Before deleting**: Verify contents are extracted elsewhere
### Old iOS Backups
**Location**: `~/Library/Application Support/MobileSync/Backup/`
**What it is**: iTunes/Finder iPhone/iPad backups
**Safety**: 🟡 **Caution - backup data**
**Check**:
```bash
ls -lh ~/Library/Application\ Support/MobileSync/Backup/
```
**Cleanup**: Delete old backups via Finder preferences, not manually
### Old Time Machine Local Snapshots
**What it is**: Local Time Machine backups
**Safety**: 🟢 **Safe - macOS manages automatically**
**macOS automatically deletes** these when disk space is low
**Check**:
```bash
tmutil listlocalsnapshots /
```
**Manual cleanup** (rarely needed):
```bash
tmutil deletelocalsnapshots <snapshot_date>
```
## What to NEVER Delete
### User Data Directories
- `~/Documents`
- `~/Desktop`
- `~/Pictures`
- `~/Movies`
- `~/Music`
### System Files
- `/System`
- `/Library/Apple` (unless you know what you're doing)
- `/private/etc`
### Security & Credentials
- `~/.ssh` (SSH keys)
- `~/Library/Keychains` (passwords, certificates)
- Any files containing credentials
### Active Databases
- `*.db`, `*.sqlite` files for running applications
- Docker volumes in active use
## Safety Checklist
Before deleting ANY directory:
1. ✅ Do you know what it is?
2. ✅ Is the application truly uninstalled?
3. ✅ Have you checked if it's in use? (lsof, Activity Monitor)
4. ✅ Do you have a Time Machine backup?
5. ✅ Have you confirmed with the user?
When in doubt, **DON'T DELETE**.
## Recovery Options
### Trash vs. Permanent Deletion
**Use Trash when possible**:
```bash
# Move to trash (recoverable)
osascript -e 'tell app "Finder" to move POSIX file "/path/to/file" to trash'
```
**Permanent deletion**:
```bash
# Cannot be recovered without Time Machine
rm -rf /path/to/file
```
### Time Machine
If you deleted something important:
1. Open Time Machine
2. Navigate to parent directory
3. Select date before deletion
4. Restore
### File Recovery Tools
If no Time Machine backup:
- Disk Drill (commercial)
- PhotoRec (free, for photos)
- TestDisk (free, for files)
**Note**: Success rate depends on how recently deleted and disk usage since deletion.

View File

@@ -0,0 +1,304 @@
# Mole Integration Guide
How to integrate [Mole](https://github.com/tw93/Mole) with the macOS Cleaner skill.
## About Mole
**Mole** is a visual macOS disk cleanup tool with a native macOS interface. It provides:
- Visual disk usage analysis
- One-click cleanup for common targets
- Safe deletion with preview
- Native macOS design
**Repository**: https://github.com/tw93/Mole
## When to Recommend Mole
Suggest Mole to users in these scenarios:
### 1. User Prefers Visual Interface
```
User: "I prefer clicking buttons rather than running commands"
```
**Response**:
```
I recommend using Mole alongside these scripts:
1. Use the analysis scripts to understand what's using space
2. Install Mole for visual cleanup: https://github.com/tw93/Mole
3. Use Mole's GUI to execute cleanup with visual confirmation
Would you like me to guide you through the analysis first?
```
### 2. Complex Cleanup Needs
```
User: "I have lots of cache files and don't want to run commands for each"
```
**Response**:
```
Mole can help with batch cleanup. It provides visual categories:
- System caches
- Application caches
- Log files
- Trash
Install Mole and you can review and clean multiple categories at once.
```
### 3. Ongoing Maintenance
```
User: "I want to clean my Mac regularly"
```
**Response**:
```
For regular maintenance, I recommend:
1. Keep Mole installed for weekly quick cleanups
2. Use our analysis scripts monthly for deep analysis
3. Use safe_delete.py for specific files/folders
This hybrid approach gives you both convenience and precision.
```
## Installation
### Check if Mole is Installed
```bash
if [ -d "/Applications/Mole.app" ]; then
echo "✅ Mole is installed"
open -a Mole
else
echo "💡 Mole is not installed"
echo " Install from: https://github.com/tw93/Mole"
fi
```
### Installation Methods
**Method 1: Download from GitHub Releases**
```bash
# Guide user to:
# 1. Visit https://github.com/tw93/Mole/releases
# 2. Download latest .dmg file
# 3. Open .dmg and drag Mole.app to /Applications
```
**Method 2: Build from Source** (if user is developer)
```bash
git clone https://github.com/tw93/Mole.git
cd Mole
# Follow build instructions in README
```
## Workflow Integration
### Hybrid Workflow: Scripts + Mole
**Best practice**: Use both tools for their strengths.
#### Step 1: Analysis with Scripts
Run comprehensive analysis:
```bash
# System analysis
python3 scripts/analyze_caches.py
python3 scripts/analyze_large_files.py --threshold 100
python3 scripts/find_app_remnants.py
# Developer analysis (if applicable)
python3 scripts/analyze_dev_env.py
```
This gives detailed reports with safety categorization.
#### Step 2: Review Findings
Present findings to user in readable format (see SKILL.md Step 4).
#### Step 3: Execute Cleanup
For different types of cleanup:
**Option A: Use Mole** (for batch operations)
- System caches: Use Mole's "System" category
- Application caches: Use Mole's "Applications" category
- Trash: Use Mole's "Trash" feature
**Option B: Use Scripts** (for precision)
- Large files: Use `safe_delete.py` with specific paths
- Application remnants: Use `safe_delete.py` with confirmed orphans
- Dev environment: Run cleanup commands directly
**Option C: Manual** (for sensitive items)
- Guide user to review in Finder
- User deletes manually
### Example Integrated Session
```markdown
🔍 Analysis Results
I've analyzed your Mac and found:
- System caches: 45 GB (safe to clean)
- Large files: 38 GB (need review)
- App remnants: 8 GB (medium confidence)
- Docker: 25 GB (requires caution)
Recommended cleanup approach:
1. **Use Mole for safe batch cleanup** (45 GB)
- Open Mole
- Select "System Caches"
- Click "Clean"
- This will clear ~/Library/Caches safely
2. **Use scripts for large file review** (38 GB)
- I found 20 large files >100MB
- Let me show you the list
- We'll use safe_delete.py to delete selected files
3. **Manual review for app remnants** (8 GB)
- 5 folders for possibly uninstalled apps
- Please verify these apps are truly gone:
- Adobe Creative Cloud (3 GB)
- Old Xcode version (2 GB)
- ...
4. **Manual Docker cleanup** (25 GB)
- Requires technical review
- I'll guide you through checking volumes
Shall we proceed with step 1 using Mole?
```
## Mole Feature Mapping
Map Mole's features to our script capabilities:
| Mole Feature | Script Equivalent | Use Case |
|--------------|-------------------|----------|
| System Caches | `analyze_caches.py --user-only` | Quick cache cleanup |
| Application Caches | `analyze_caches.py` | Per-app cache analysis |
| Large Files | `analyze_large_files.py` | Find space hogs |
| Trash | N/A (Finder) | Empty trash |
| Duplicate Files | Manual `fdupes` | Find duplicates |
**Mole's advantages**:
- Visual representation
- One-click cleanup
- Native macOS integration
**Scripts' advantages**:
- Developer-specific tools (Docker, npm, pip)
- Application remnant detection
- Detailed categorization and safety notes
- Batch operations with confirmation
## Coordinated Cleanup Strategy
### For Non-Technical Users
1. **Install Mole** - Primary cleanup tool
2. **Keep scripts** - For occasional deep analysis
3. **Workflow**:
- Monthly: Run `analyze_caches.py` to see what's using space
- Use Mole to execute cleanup
- Special cases: Use scripts
### For Technical Users / Developers
1. **Keep both** - Mole for quick cleanup, scripts for precision
2. **Workflow**:
- Weekly: Mole for routine cache cleanup
- Monthly: Full script analysis for deep cleaning
- As needed: Script-based cleanup for dev environment
### For Power Users
1. **Scripts only** - Full control and automation
2. **Workflow**:
- Schedule analysis scripts with cron/launchd
- Review reports
- Execute cleanup with `safe_delete.py` or direct commands
## Limitations & Complementary Use
### What Mole Does Well
✅ Visual disk usage analysis
✅ Safe cache cleanup
✅ User-friendly interface
✅ Quick routine maintenance
### What Mole Doesn't Do (Use Scripts For)
❌ Docker cleanup
❌ Homebrew cache (command-line only)
❌ npm/pip cache
❌ Application remnant detection with confidence levels
❌ Large .git directory detection
❌ Development environment analysis
### Recommended Approach
**Use Mole for**: 80% of routine cleanup needs
**Use Scripts for**: 20% of specialized/technical cleanup needs
## Troubleshooting
### Mole Not Opening
```bash
# Check if Mole is installed
ls -l /Applications/Mole.app
# Try opening from command line (see error messages)
open -a Mole
# If not installed
echo "Download from: https://github.com/tw93/Mole/releases"
```
### Mole Shows Different Numbers than Scripts
**Explanation**:
- Mole uses different calculation methods
- Scripts use `du` command (more accurate for directory sizes)
- Both are valid, differences typically <5%
**Not a problem**: Use Mole's numbers for decisions
### Mole Can't Delete Some Caches
**Reason**: Permission issues (some caches are protected)
**Solution**:
1. Use scripts with sudo for system caches
2. Or manually delete in Finder with authentication
## Summary
**Best Practice**: Use both tools
- **Mole**: Visual cleanup, routine maintenance, user-friendly
- **Scripts**: Deep analysis, developer tools, precise control
**Workflow**:
1. Analyze with scripts (comprehensive report)
2. Execute with Mole (safe and visual) OR scripts (precise and technical)
3. Maintain with Mole (weekly/monthly routine)
This combination provides the best user experience for macOS cleanup.

View File

@@ -0,0 +1,474 @@
# Safety Rules for macOS Cleanup
Critical safety guidelines to prevent data loss and system damage.
## Golden Rules
### Rule 1: Never Delete Without Confirmation
**ALWAYS** ask user before deleting ANY file or directory.
**Bad**:
```python
shutil.rmtree(cache_dir) # Immediately deletes
```
**Good**:
```python
if confirm_delete(cache_dir, size, description):
shutil.rmtree(cache_dir)
else:
print("Skipped")
```
### Rule 2: Explain Before Deleting
Users should understand:
- **What** is being deleted
- **Why** it's safe (or not safe)
- **Impact** of deletion
- **Recoverability** (can it be restored?)
### Rule 3: When in Doubt, Don't Delete
If uncertain about safety: **DON'T DELETE**.
Ask user to verify instead.
### Rule 4: Suggest Backups for Large Deletions
Before deleting >10 GB, recommend Time Machine backup.
### Rule 5: Use Trash When Possible
Prefer moving to Trash over permanent deletion:
```bash
# Recoverable
osascript -e 'tell app "Finder" to move POSIX file "/path/to/file" to trash'
# Permanent (use only when confirmed safe)
rm -rf /path/to/file
```
## Never Delete These
### System Directories
| Path | Why | Impact if Deleted |
|------|-----|-------------------|
| `/System` | macOS core | System unbootable |
| `/Library/Apple` | Apple frameworks | Apps won't launch |
| `/private/etc` | System config | System unstable |
| `/private/var/db` | System databases | System unstable |
| `/usr` | Unix utilities | Commands won't work |
| `/bin`, `/sbin` | System binaries | System unusable |
### User Data
| Path | Why | Impact if Deleted |
|------|-----|-------------------|
| `~/Documents` | User documents | Data loss |
| `~/Desktop` | User files | Data loss |
| `~/Pictures` | Photos | Data loss |
| `~/Movies` | Videos | Data loss |
| `~/Music` | Music library | Data loss |
| `~/Downloads` | May contain important files | Potential data loss |
### Security & Credentials
| Path | Why | Impact if Deleted |
|------|-----|-------------------|
| `~/.ssh` | SSH keys | Cannot access servers |
| `~/Library/Keychains` | Passwords, certificates | Cannot access accounts/services |
| Any file with "credential", "password", "key" in name | Security data | Cannot authenticate |
### Active Databases
| Pattern | Why | Impact if Deleted |
|---------|-----|-------------------|
| `*.db`, `*.sqlite`, `*.sqlite3` | Application databases | App data loss |
| Any database file for running app | Active data | Data corruption |
### Running Applications
| Path | Why | Impact if Deleted |
|------|-----|-------------------|
| `/Applications` | Installed apps | Apps won't launch |
| `~/Applications` | User-installed apps | Apps won't launch |
| Files in use (check with `lsof`) | Currently open | App crash, data corruption |
## Require Extra Confirmation
### Large Deletions
**Threshold**: >10 GB
**Action**: Warn user and suggest Time Machine backup
**Example**:
```
⚠️ This operation will delete 45 GB of data.
💡 Recommendation:
Create a Time Machine backup first.
Check last backup:
tmutil latestbackup
Create backup now:
tmutil startbackup
Proceed without backup? [y/N]:
```
### System-Wide Caches
**Paths**: `/Library/Caches`, `/var/log`
**Action**: Require manual sudo command (don't execute directly)
**Example**:
```
⚠️ This operation requires administrator privileges.
Please run this command manually:
sudo rm -rf /Library/Caches/*
⚠️ You will be asked for your password.
```
**Reason**:
- Requires elevated privileges
- User should be aware of system-wide impact
- Audit trail (user types password)
### Docker Volumes
**Action**: Always list volumes before cleanup
**Example**:
```
⚠️ Docker cleanup may remove important data.
Current volumes:
postgres_data (1.2 GB) - May contain database
redis_data (500 MB) - May contain cache
app_uploads (3 GB) - May contain user files
Review each volume:
docker volume inspect <volume_name>
Proceed with cleanup? [y/N]:
```
### Application Preferences
**Path**: `~/Library/Preferences/*.plist`
**Action**: Warn that app will reset to defaults
**Example**:
```
⚠️ Deleting preferences will reset the app to defaults.
Impact:
- All settings will be lost
- Custom configurations will be reset
- May need to re-enter license keys
Only delete if:
- App is misbehaving (troubleshooting)
- App is confirmed uninstalled
Proceed? [y/N]:
```
## Safety Checks Before Deletion
### Check 1: Path Exists
```python
if not os.path.exists(path):
print(f"❌ Path does not exist: {path}")
return False
```
### Check 2: Not a System Path
```python
system_paths = [
'/System', '/Library/Apple', '/private/etc',
'/usr', '/bin', '/sbin', '/private/var/db'
]
for sys_path in system_paths:
if path.startswith(sys_path):
print(f"❌ Cannot delete system path: {path}")
return False
```
### Check 3: Not User Data
```python
user_data_paths = [
'~/Documents', '~/Desktop', '~/Pictures',
'~/Movies', '~/Music', '~/.ssh'
]
expanded_path = os.path.expanduser(path)
for data_path in user_data_paths:
if expanded_path.startswith(os.path.expanduser(data_path)):
print(f"⚠️ This is a user data directory: {path}")
print(" Are you ABSOLUTELY sure? [type 'DELETE' to confirm]:")
response = input().strip()
if response != 'DELETE':
return False
```
### Check 4: Not in Use
```python
def is_in_use(path):
"""Check if file/directory is in use."""
try:
result = subprocess.run(
['lsof', path],
capture_output=True,
text=True
)
# If lsof finds processes using the file, returncode is 0
if result.returncode == 0:
return True
return False
except:
return False # Assume not in use if check fails
if is_in_use(path):
print(f"⚠️ Warning: {path} is currently in use")
print(" Close the application first, then try again.")
return False
```
### Check 5: Permissions
```python
def can_delete(path):
"""Check if we have permission to delete."""
try:
# Check parent directory write permission
parent = os.path.dirname(path)
return os.access(parent, os.W_OK)
except:
return False
if not can_delete(path):
print(f"❌ No permission to delete: {path}")
print(" You may need sudo, but be careful!")
return False
```
## Safe Deletion Workflow
```python
def safe_delete(path, size, description):
"""
Safe deletion workflow with all checks.
Args:
path: Path to delete
size: Size in bytes
description: Human-readable description
Returns:
(success, message)
"""
# Safety checks
if not os.path.exists(path):
return (False, "Path does not exist")
if is_system_path(path):
return (False, "Cannot delete system path")
if is_user_data(path):
if not extra_confirm(path):
return (False, "User cancelled")
if is_in_use(path):
return (False, "Path is in use")
if not can_delete(path):
return (False, "No permission")
# Backup warning for large deletions
if size > 10 * 1024 * 1024 * 1024: # 10 GB
if not confirm_large_deletion(size):
return (False, "User cancelled")
# Final confirmation
if not confirm_delete(path, size, description):
return (False, "User cancelled")
# Execute deletion
try:
if os.path.isfile(path):
os.unlink(path)
else:
shutil.rmtree(path)
return (True, f"Deleted successfully ({format_size(size)} freed)")
except Exception as e:
return (False, f"Deletion failed: {str(e)}")
```
## Error Handling
### Permission Denied
```python
except PermissionError:
print(f"❌ Permission denied: {path}")
print(" Try running with sudo (use caution!)")
```
### Operation Not Permitted (SIP)
```python
# macOS System Integrity Protection blocks some deletions
except OSError as e:
if e.errno == 1: # Operation not permitted
print(f"❌ System Integrity Protection prevents deletion: {path}")
print(" This is a protected system file.")
print(" Do NOT attempt to bypass SIP unless you know what you're doing.")
```
### Path Too Long
```python
except OSError as e:
if e.errno == 63: # File name too long
print(f"⚠️ Path too long, trying alternative method...")
# Try using find + rm
```
## Recovery Options
### If User Accidentally Confirmed
**Immediate action**: Check Trash first
```bash
# Files may be in Trash
ls -lh ~/.Trash
```
**Next**: Time Machine
```bash
# Open Time Machine to date before deletion
tmutil browse
```
**Last resort**: File recovery tools
- Disk Drill (commercial)
- PhotoRec (free)
- TestDisk (free)
**Note**: Success rate depends on:
- How recently deleted
- How much disk activity since deletion
- Whether SSD (TRIM) or HDD
### Preventing Accidents
1. **Use Trash instead of rm** when possible
2. **Require Time Machine backup** for >10 GB deletions
3. **Test on small items first** before batch operations
4. **Show dry-run results** before actual deletion
## Red Flags to Watch For
### User Requests
If user asks to:
- "Delete everything in ~/Library"
- "Clear all caches including system"
- "Delete all .log files on the entire system"
- "Remove all databases"
**Response**:
```
⚠️ This request is too broad and risky.
Let me help you with a safer approach:
1. Run analysis to identify specific targets
2. Review each category
3. Delete selectively with confirmation
This prevents accidental data loss.
```
### Script Behavior
If script is about to:
- Delete >100 GB at once
- Delete entire directory trees without listing contents
- Run `rm -rf /` or similar dangerous commands
- Delete from system paths
**Action**: STOP and ask for confirmation
## Testing Guidelines
### Before Packaging
Test safety checks:
1. ✅ Attempt to delete system path → Should reject
2. ✅ Attempt to delete user data → Should require extra confirmation
3. ✅ Attempt to delete in-use file → Should warn
4. ✅ Attempt to delete without permission → Should fail gracefully
5. ✅ Large deletion → Should suggest backup
### In Production
Always:
- Start with smallest items
- Confirm results after each deletion
- Monitor disk space before/after
- Ask user to verify important apps still work
## Summary
### Conservative Approach
When implementing cleanup:
1. **Assume danger** until proven safe
2. **Explain everything** to user
3. **Confirm each step**
4. **Suggest backups** for large operations
5. **Use Trash** when possible
6. **Test thoroughly** before packaging
### Remember
> "It's better to leave 1 GB of unnecessary files than to delete 1 MB of important data."
User trust is fragile. One bad deletion loses it forever.
### Final Checklist
Before any deletion:
- [ ] Path is verified to exist
- [ ] Path is not a system path
- [ ] Path is not user data (or extra confirmed)
- [ ] Path is not in use
- [ ] User has been informed of impact
- [ ] User has explicitly confirmed
- [ ] Backup suggested for large deletions
- [ ] Error handling in place
- [ ] Recovery options documented
Only then: proceed with deletion.