mcpField
M
macos-cleaner

macos-cleaner

github.com/julianobarbosa其他14107 次安装3 天前更新
代码仓库

关于 macos-cleaner

macos-cleaner 是一项 macOS 磁盘分析与清理指导技能,帮助用户识别可回收空间并避免误删重要数据。它会说明删除影响,采用保守建议,并要求明确确认后才执行删除。

主要功能

  1. 01使用 Mole 分析磁盘用量
  2. 02通过交互式 TUI 探索目录
  3. 03检查缓存、应用残留、大文件和开发数据
  4. 04说明删除影响并要求确认
  5. 05提供由用户自行运行的清理命令

适用场景

  1. 01查找占用 macOS 存储空间的目录
  2. 02判断应用缓存是否值得保留
  3. 03发现已卸载应用留下的数据
  4. 04检查 Docker 和开发工具的清理候选项

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/julianobarbosa/claude-code-skills --skill macos-cleaner

安装后在 Claude Code 中输入/macos-cleaner确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

.security-scan-passed
references/
cleanup_targets.md
mole_integration.md
safety_rules.md
scripts/
analyze_caches.py
analyze_dev_env.py
analyze_large_files.py
cleanup_report.py
find_app_remnants.py
safe_delete.py

详细介绍

macOS 清理工具

概述

智能分析 macOS 磁盘使用情况,并提供可执行的清理建议以释放存储空间。此技能遵循安全优先原则:进行全面分析,清晰呈现结果,并要求用户明确确认后才执行任何删除操作。

目标用户:具备基本技术知识、了解文件系统,但需要指导来判断在 macOS 上哪些内容可以安全删除的用户。

核心原则

  1. 安全第一,绝不绕过:未经用户明确确认,绝不执行危险命令(rm -rf、mo clean 等)。不走捷径,不用变通方案。
  2. 重视实际价值,而非表面数字:目标不是最大化清理空间,而是找出哪些内容确实无用,哪些是有价值的缓存。为了显示一个大数字而清除 50GB 有用缓存是有害的。
  3. 考虑网络环境:许多用户(尤其是在中国)网络较慢或不稳定。重新下载缓存可能需要数小时。能节省 30 分钟下载时间的缓存值得保留。
  4. 必须分析影响:每条清理建议都必须包含“删除后会发生什么”一栏。绝不能只列出项目而不解释后果。
  5. 耐心胜过速度:磁盘扫描可能需要 5-10 分钟。绝不打断或跳过耗时操作。定期向用户报告进度。
  6. 由用户执行清理:分析后,提供由用户自行运行的清理命令。不要自动执行清理。
  7. 默认采取保守做法:有疑问时就不要删除。宁可谨慎一些。

绝对禁止:

  • ❌ 绝不自动对用户目录运行 rm -rf
  • ❌ 未先进行试运行预览,绝不运行 mo clean
  • ❌ 绝不使用 docker volume prune -f 或 docker system prune -a --volumes
  • ❌ 绝不为节省时间而跳过分析步骤
  • ❌ 绝不在 Mole 命令后添加 --help(mo --help 除外)
  • ❌ 绝不为了夸大清理数字而建议删除有用缓存

工作流决策树

User reports disk space issues
           ↓
    Quick Diagnosis
           ↓
    ┌──────┴──────┐
    │             │
Immediate    Deep Analysis
 Cleanup      (continue below)
    │             │
    └──────┬──────┘
           ↓
  Present Findings
           ↓
   User Confirms
           ↓
   Execute Cleanup
           ↓
  Verify Results

第 1 步:使用 Mole 快速诊断

主要工具:使用 Mole 进行磁盘分析。它会提供全面且分类清晰的结果。

1.1 初步检查
# Check Mole installation and version
which mo && mo --version

# If not installed
brew install tw93/tap/mole

# Check for updates (Mole updates frequently)
brew info tw93/tap/mole | head -5

# Upgrade if outdated
brew upgrade tw93/tap/mole
1.2 选择分析方法

重要:使用 mo analyze 作为主要分析工具,而不是 mo clean --dry-run。

命令用途使用时机
mo analyze交互式磁盘使用情况浏览器(TUI 树形视图)主要方式:了解哪些内容占用了空间
mo clean --dry-run预览清理类别次要方式:仅在运行 mo analyze 后用于查看清理预览

优先使用 mo analyze 的原因:

  • 专用的磁盘分析工具,支持通过交互式树形视图导航
  • 可深入查看特定目录
  • 显示实际磁盘使用情况细分,而不只是清理类别
  • 更有助于了解存储空间的占用情况
1.3 通过 tmux 运行分析

重要:Mole 需要 TTY。使用 Claude Code 时始终通过 tmux 运行。

关键时间提示:主目录扫描速度较慢(大型目录需要 5-10 分钟甚至更久)。提前告知用户,并耐心等待。

# Create tmux session
tmux new-session -d -s mole -x 120 -y 40

# Run disk analysis (PRIMARY tool - interactive TUI)
tmux send-keys -t mole 'mo analyze' Enter

# Wait for scan - BE PATIENT!
# Home directory scanning typically takes 5-10 minutes
# Report progress to user regularly
sleep 60 && tmux capture-pane -t mole -p

# Navigate the TUI with arrow keys
tmux send-keys -t mole Down    # Move to next item
tmux send-keys -t mole Enter   # Expand/select item
tmux send-keys -t mole 'q'     # Quit when done

替代方案:清理预览(在运行 mo analyze 之后使用)

# Run dry-run preview (SAFE - no deletion)
tmux send-keys -t mole 'mo clean --dry-run' Enter

# Wait for scan (report progress to user every 30 seconds)
# Be patient! Large directories take 5-10 minutes
sleep 30 && tmux capture-pane -t mole -p
1.4 进度报告

定期向用户报告扫描进度:

📊 Disk Analysis in Progress...
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⏱️ Elapsed: 2 minutes

Current status:
✅ Applications: 49.5 GB (complete)
✅ System Library: 10.3 GB (complete)
⏳ Home: scanning... (this may take 5-10 minutes)
⏳ App Library: pending

I'm waiting patiently for the scan to complete.
Will report again in 30 seconds...
1.5 呈现最终结果

扫描完成后,按结构化格式呈现结果:

📊 Disk Space Analysis (via Mole)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Free space: 27 GB

🧹 Recoverable Space (dry-run preview):

➤ User Essentials
  • User app cache:     16.67 GB
  • User app logs:      102.3 MB
  • Trash:              642.9 MB

➤ Browser Caches
  • Chrome cache:       1.90 GB
  • Safari cache:       4 KB

➤ Developer Tools
  • uv cache:           9.96 GB
  • npm cache:          (detected)
  • Docker cache:       (detected)
  • Homebrew cache:     (detected)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Total recoverable: ~30 GB

⚠️ This was a dry-run preview. No files were deleted.

第 2 步:深入分析各类别

系统地扫描以下类别。详细说明请参阅 references/cleanup_targets.md。

类别 1:系统和应用缓存

要分析的位置:

  • ~/Library/Caches/* - 用户应用缓存
  • /Library/Caches/* - 系统级缓存(需要 sudo)
  • ~/Library/Logs/* - 应用日志
  • /var/log/* - 系统日志(需要 sudo)

分析脚本:

scripts/analyze_caches.py --user-only

安全级别:🟢 通常可安全删除(应用会重新生成缓存)

需要保留的例外:

  • 浏览器运行期间的浏览器缓存
  • IDE 缓存(可能会拖慢下次启动)
  • 包管理器缓存(Homebrew、pip、npm)
类别 2:应用残留

要分析的位置:

  • ~/Library/Application Support/* - 应用数据
  • ~/Library/Preferences/* - 偏好设置文件
  • ~/Library/Containers/* - 沙盒应用数据

分析方法:

  1. 列出 /Applications 中已安装的应用
  2. 与 ~/Library/Application Support 交叉核对
  3. 找出孤立文件夹(应用已卸载,但数据仍然保留)

分析脚本:

scripts/find_app_remnants.py

安全级别:🟡 需要谨慎

  • ✅ 安全:明确已卸载应用的文件夹
  • ⚠️ 先检查:很少使用的应用对应的文件夹
  • ❌ 保留:正在使用的应用数据
类别 3:大文件和重复文件

分析脚本:

scripts/analyze_large_files.py --threshold 100MB --path ~

查找重复文件(可选,资源消耗较大):

# Use fdupes if installed
if command -v fdupes &> /dev/null; then
  fdupes -r ~/Documents ~/Downloads
fi

呈现分析结果:

📦 Large Files (>100MB):
━━━━━━━━━━━━━━━━━━━━━━━━
1. movie.mp4                    4.2 GB  ~/Downloads
2. dataset.csv                  1.8 GB  ~/Documents/data
3. old_backup.zip               1.5 GB  ~/Desktop
...

🔁 Duplicate Files:
- screenshot.png (3 copies)     15 MB each
- document_v1.docx (2 copies)   8 MB each

安全级别:🟡 需要用户自行判断

类别 4:开发环境清理

目标:

  • Docker:镜像、容器、卷、构建缓存
  • Homebrew:缓存、旧版本
  • Node.js:node_modules、npm 缓存
  • Python:pip 缓存、__pycache__、venv
  • Git:已归档项目中的 .git 文件夹

分析脚本:

scripts/analyze_dev_env.py

分析结果示例:

🐳 Docker Resources:
- Unused images:      12 GB
- Stopped containers:  2 GB
- Build cache:         8 GB
- Orphaned volumes:    3 GB
Total potential:      25 GB

📦 Package Managers:
- Homebrew cache:      5 GB
- npm cache:           3 GB
- pip cache:           1 GB
Total potential:       9 GB

🗂️  Old Projects:
- archived-project-2022/.git  500 MB
- old-prototype/.git          300 MB

清理命令(需要确认):

# Homebrew cleanup (safe)
brew cleanup -s

# npm _npx only (safe - temporary packages)
rm -rf ~/.npm/_npx

# pip cache (use with caution)
pip cache purge

Docker 清理 - 需要特别处理:

⚠️ 切勿使用以下命令:

# ❌ DANGEROUS - deletes ALL volumes without confirmation
docker volume prune -f
docker system prune -a --volumes

✅ 正确做法 - 逐个卷确认:

# 1. List all volumes
docker volume ls

# 2. Identify which projects each volume belongs to
docker volume inspect <volume_name>

# 3. Ask user to confirm EACH project they want to delete
# Example: "Do you want to delete all volumes for 'ragflow' project?"

# 4. Delete specific volumes only after confirmation
docker volume rm ragflow_mysql_data ragflow_redis_data

安全级别:🟢 Homebrew/npm 清理,🔴 Docker 卷需要逐个项目确认

第 3 步:与 Mole 集成

Mole(https://github.com/tw93/Mole)是一款用于全面清理 macOS 的**命令行界面(CLI)**工具。它通过交互式终端提供缓存、日志、开发工具等内容的分析和清理功能。

重要要求:

  1. TTY 环境:Mole 的交互式命令需要 TTY。从 Claude Code 或脚本运行时,请使用 tmux。
  2. 版本检查:使用前务必确认 Mole 已更新至最新版本。
  3. 安全帮助命令:只有 mo --help 是安全的。不要在其他命令后附加 --help。

检查安装并升级:

# Check if installed and get version
which mo && mo --version

# If not installed
brew install tw93/tap/mole

# Check for updates
brew info tw93/tap/mole | head -5

# Upgrade if needed
brew upgrade tw93/tap/mole

通过 tmux 使用 Mole(Claude Code 必须使用):

# Create tmux session for TTY environment
tmux new-session -d -s mole -x 120 -y 40

# Run analysis (safe, read-only)
tmux send-keys -t mole 'mo analyze' Enter

# Wait for scan (be patient - can take 5-10 minutes for large directories)
sleep 60

# Capture results
tmux capture-pane -t mole -p

# Cleanup when done
tmux kill-session -t mole

可用命令(来自 mo --help):

命令安全性描述
mo --help✅ 安全查看所有命令(唯一安全的帮助命令)
mo analyze✅ 安全磁盘使用情况浏览器(只读)
mo status✅ 安全系统健康状况监控器
mo clean --dry-run✅ 安全预览清理内容(不删除)
mo clean⚠️ 危险实际删除文件
mo purge⚠️ 危险移除项目产物
mo uninstall⚠️ 危险移除应用

参考指南: 详细的 tmux 工作流和故障排除方法,请参阅 references/mole_integration.md。

使用 Mole 进行多层深度探索

重要:要进行全面分析,必须执行多层探索,而不只是扫描顶层目录。本节介绍经过验证的 Mole TUI 导航工作流。

导航命令
# Create session
tmux new-session -d -s mole -x 120 -y 40

# Start analysis
tmux send-keys -t mole 'mo analyze' Enter

# Wait for initial scan
sleep 8 && tmux capture-pane -t mole -p

# Navigation keys (send via tmux)
tmux send-keys -t mole Enter    # Enter/expand selected directory
tmux send-keys -t mole Left     # Go back to parent directory
tmux send-keys -t mole Down     # Move to next item
tmux send-keys -t mole Up       # Move to previous item
tmux send-keys -t mole 'q'      # Quit TUI

# Capture current view
tmux capture-pane -t mole -p
多层探索工作流

步骤 1:查看顶层概况

# Start mo analyze, wait for initial menu
tmux send-keys -t mole 'mo analyze' Enter
sleep 8 && tmux capture-pane -t mole -p

# Example output:
# 1. Home           289.4 GB (58.5%)
# 2. App Library    145.2 GB (29.4%)
# 3. Applications    49.5 GB (10.0%)
# 4. System Library  10.3 GB (2.1%)

步骤 2:进入最大的目录(Home)

tmux send-keys -t mole Enter
sleep 10 && tmux capture-pane -t mole -p

# Example output:
# 1. Library       144.4 GB (49.9%)
# 2. Workspace      52.0 GB (18.0%)
# 3. .cache         19.3 GB (6.7%)
# 4. Applications   17.0 GB (5.9%)
# ...

步骤 3:深入特定目录

# Go to .cache (3rd item: Down Down Enter)
tmux send-keys -t mole Down Down Enter
sleep 5 && tmux capture-pane -t mole -p

# Example output:
# 1. uv           10.3 GB (55.6%)
# 2. modelscope    5.5 GB (29.5%)
# 3. huggingface   887.8 MB (4.7%)

步骤 4:返回并探索另一个分支

# Go back to parent
tmux send-keys -t mole Left
sleep 2

# Navigate to different directory
tmux send-keys -t mole Down Down Down Down Enter  # Go to .npm
sleep 5 && tmux capture-pane -t mole -p

步骤 5:深入探索 Library

# Back to Home, then into Library
tmux send-keys -t mole Left
tmux send-keys -t mole Up Up Up Up Up Up Enter  # Go to Library
sleep 10 && tmux capture-pane -t mole -p

# Example output:
# 1. Application Support  37.1 GB
# 2. Containers          35.4 GB
# 3. Developer           17.8 GB  ← Xcode is here
# 4. Caches               8.2 GB
推荐探索路径

要进行全面分析,请按照以下探索树操作:

mo analyze
├── Home (Enter)
│   ├── Library (Enter)
│   │   ├── Developer (Enter) → Xcode/DerivedData, iOS DeviceSupport
│   │   ├── Caches (Enter) → Playwright, JetBrains, etc.
│   │   └── Application Support (Enter) → App data
│   ├── .cache (Enter) → uv, modelscope, huggingface
│   ├── .npm (Enter) → _cacache, _npx
│   ├── Downloads (Enter) → Large files to review
│   ├── .Trash (Enter) → Confirm trash contents
│   └── miniconda3/other dev tools (Enter) → Check last used time
├── App Library → Usually overlaps with ~/Library
└── Applications → Installed apps
时间预估
目录扫描时间备注
顶层菜单5-8 秒快速
主目录5-10 分钟内容较多,请耐心等待
~/Library3-5 分钟小文件很多
子目录2-30 秒视大小而定
完整会话示例
# 1. Create session
tmux new-session -d -s mole -x 120 -y 40

# 2. Start analysis and get overview
tmux send-keys -t mole 'mo analyze' Enter
sleep 8 && tmux capture-pane -t mole -p

# 3. Enter Home
tmux send-keys -t mole Enter
sleep 10 && tmux capture-pane -t mole -p

# 4. Enter .cache to see dev caches
tmux send-keys -t mole Down Down Enter
sleep 5 && tmux capture-pane -t mole -p

# 5. Back to Home, then to .npm
tmux send-keys -t mole Left
sleep 2
tmux send-keys -t mole Down Down Down Down Enter
sleep 5 && tmux capture-pane -t mole -p

# 6. Back to Home, enter Library
tmux send-keys -t mole Left
sleep 2
tmux send-keys -t mole Up Up Up Up Up Up Enter
sleep 10 && tmux capture-pane -t mole -p

# 7. Enter Developer to see Xcode
tmux send-keys -t mole Down Down Down Enter
sleep 5 && tmux capture-pane -t mole -p

# 8. Enter Xcode
tmux send-keys -t mole Enter
sleep 5 && tmux capture-pane -t mole -p

# 9. Enter DerivedData to see projects
tmux send-keys -t mole Enter
sleep 5 && tmux capture-pane -t mole -p

# 10. Cleanup
tmux kill-session -t mole
探查所得的关键信息

经过多层探查,你将发现:

  1. 哪些项目在使用 DerivedData - 具体项目名称
  2. 哪些缓存实际占用空间较大 - uv、npm 或其他缓存
  3. 文件的存放时间 - Mole 会显示“>3mo”“>7mo”“>1yr”标记
  4. 具体卷及其用途 - Docker 项目数据
  5. 可以清理的下载内容 - 旧的 dmg 文件、重复文件

反模式:哪些内容不应删除

重要:以下内容经常被建议清理,但在大多数情况下不应删除。它们带来的价值远超占用的空间。

应保留的内容(反模式)
项目大小不应删除的原因删除的实际影响
Xcode DerivedData10+ GB构建缓存可让每次完整重建节省 10-30 分钟下次构建会多花 10-30 分钟
npm _cacache5+ GB已下载的软件包缓存在本地npm install 会重新下载所有内容(在中国需要 30 分钟至 2 小时)
~/.cache/uv10+ GBPython 软件包缓存每个 Python 项目都要从 PyPI 重新安装依赖
Playwright browsers3-4 GB用于自动化测试的浏览器二进制文件每次都要重新下载 2GB 以上(需要 30 分钟至 1 小时)
iOS DeviceSupport2-3 GB设备调试所需连接设备时需要从 Apple 重新下载
Docker stopped containers<500 MB随时可以用 docker start 重启丢失容器状态,需要重新创建
~/.cache/huggingface不定AI 模型缓存需要重新下载大型模型(耗时数小时)
~/.cache/modelscope不定AI 模型缓存(中国)同上
JetBrains caches1+ GBIDE 索引和缓存IDE 需要 5-10 分钟重新建立索引
这为何重要

虚荣陷阱:看到“已清理 50GB!”会让人很高兴,但:

  • 用户接下来要花 2 小时重新下载 npm 软件包
  • 下次 Xcode 构建需要 30 分钟,而不是 30 秒
  • AI 项目会因需要重新下载模型而失败

正确的思路:“我发现了 50GB 的缓存。以下是为什么其中大部分实际上很有价值、应该保留……”

实际上可以安全删除的内容
项目安全原因影响
废纸篓用户已经删除了这些文件无 - 这是用户的决定
Homebrew 旧版本已被较新版本替代少见:无法回退到旧版本
npm _npx临时的 npx 执行文件影响较小:npx 下次使用时会重新下载
残留的孤立应用文件应用已卸载无 - 应用已不存在
确定未使用的特定 Docker 卷已确认相关项目不再使用无 - 前提是这些项目确实已弃用

报告格式要求

每份清理报告都必须遵循此格式,并进行影响分析:

## Disk Analysis Report

### Classification Legend
| Symbol | Meaning |
|--------|---------|
| 🟢 | **Absolutely Safe** - No negative impact, truly unused |
| 🟡 | **Trade-off Required** - Useful cache, deletion has cost |
| 🔴 | **Do Not Delete** - Contains valuable data or actively used |

### Findings

| Item | Size | Classification | What It Is | Impact If Deleted |
|------|------|----------------|------------|-------------------|
| Trash | 643 MB | 🟢 | Files you deleted | None |
| npm _npx | 2.1 GB | 🟢 | Temp npx packages | Minor redownload |
| npm _cacache | 5 GB | 🟡 | Package cache | 30min-2hr redownload |
| DerivedData | 10 GB | 🟡 | Xcode build cache | 10-30min rebuild |
| Docker volumes | 11 GB | 🔴 | Project databases | **DATA LOSS** |

### Recommendation
Only items marked 🟢 are recommended for cleanup.
Items marked 🟡 require your judgment based on usage patterns.
Items marked 🔴 require explicit confirmation per-item.

高质量报告模板

经过多层探查后,使用这个经过验证的模板呈现发现:

## 📊 磁盘空间深度分析报告

**分析日期**: YYYY-MM-DD
**使用工具**: Mole CLI + 多层目录探索
**分析原则**: 安全第一,价值优于虚荣

---

### 总览

| 区域 | 总占用 | 关键发现 |
|------|--------|----------|
| **Home** | XXX GB | Library占一半(XXX GB) |
| **App Library** | XXX GB | 与Home/Library重叠统计 |
| **Applications** | XXX GB | 应用本体 |

---

### 🟢 绝对安全可删除 (约 X.X GB)

| 项目 | 大小 | 位置 | 删除后影响 | 清理命令 |
|------|------|------|-----------|---------|
| **废纸篓** | XXX MB | ~/.Trash | 无 - 你已决定删除的文件 | 清空废纸篓 |
| **npm _npx** | X.X GB | ~/.npm/_npx | 下次 npx 命令重新下载 | `rm -rf ~/.npm/_npx` |
| **Homebrew 旧版本** | XX MB | /opt/homebrew | 无 - 已被新版本替代 | `brew cleanup --prune=0` |

**废纸篓内容预览**:
- [列出主要文件]

---

### 🟡 需要你确认的项目

#### 1. [项目名] (X.X GB) - [状态描述]

| 子目录 | 大小 | 最后使用 |
|--------|------|----------|
| [子目录1] | X.X GB | >X个月 |
| [子目录2] | X.X GB | >X个月 |

**问题**: [需要用户回答的问题]

---

#### 2. Downloads 中的旧文件 (X.X GB)

| 文件/目录 | 大小 | 年龄 | 建议 |
|-----------|------|------|------|
| [文件1] | X.X GB | - | [建议] |
| [文件2] | XXX MB | >X个月 | [建议] |

**建议**: 手动检查 Downloads,删除已不需要的文件。

---

#### 3. 停用的 Docker 项目 Volumes

| 项目前缀 | 可能包含的数据 | 需要你确认 |
|---------|--------------|-----------|
| `project1_*` | MySQL, Redis | 还在用吗? |
| `project2_*` | Postgres | 还在用吗? |

**注意**: 我不会使用 `docker volume prune -f`,只会在你确认后删除特定项目的 volumes。

---

### 🔴 不建议删除的项目 (有价值的缓存)

| 项目 | 大小 | 为什么要保留 |
|------|------|-------------|
| **Xcode DerivedData** | XX GB | [项目名]的编译缓存,删除后下次构建需要X分钟 |
| **npm _cacache** | X.X GB | 所有下载过的 npm 包,删除后需要重新下载 |
| **~/.cache/uv** | XX GB | Python 包缓存,重新下载在中国网络下很慢 |
| [其他有价值的缓存] | X.X GB | [保留原因] |

---

### 📋 其他发现

| 项目 | 大小 | 说明 |
|------|------|------|
| **OrbStack/Docker** | XX GB | 正常的 VM/容器占用 |
| [其他发现] | X.X GB | [说明] |

---

### 推荐操作

**立即可执行** (无需确认):
```bash
# 1. 清空废纸篓 (XXX MB)
# 手动: Finder → 清空废纸篓

# 2. npm _npx (X.X GB)
rm -rf ~/.npm/_npx

# 3. Homebrew 旧版本 (XX MB)
brew cleanup --prune=0

预计释放:约 X.X GB


需要你确认后执行:

  1. [项目1] - [确认问题]
  2. [项目2] - [确认问题]
  3. Docker 项目 - 告诉我哪些项目确定不再使用

### Report Quality Checklist

Before presenting the report, verify:

- [ ] Every item has "Impact If Deleted" explanation
- [ ] 🟢 items are truly safe (Trash, _npx, old versions)
- [ ] 🟡 items require user decision (age info, usage patterns)
- [ ] 🔴 items explain WHY they should be kept
- [ ] Docker volumes listed by project, not blanket prune
- [ ] Network environment considered (China = slow redownload)
- [ ] No recommendations to delete useful caches just to inflate numbers
- [ ] Clear action items with exact commands

## Step 4: Present Recommendations

Format findings into actionable recommendations with risk levels:

```markdown
# macOS Cleanup Recommendations

## Summary
Total space recoverable: ~XX GB
Current usage: XX%

## Recommended Actions

### 🟢 Safe to Execute (Low Risk)
These are safe to delete and will be regenerated as needed:

1. **Empty Trash** (~12 GB)
   - Location: ~/.Trash
   - Command: `rm -rf ~/.Trash/*`

2. **Clear System Caches** (~45 GB)
   - Location: ~/Library/Caches
   - Command: `rm -rf ~/Library/Caches/*`
   - Note: Apps may be slightly slower on next launch

3. **Remove Homebrew Cache** (~5 GB)
   - Command: `brew cleanup -s`

### 🟡 Review Recommended (Medium Risk)
Review these items before deletion:

1. **Large Downloads** (~38 GB)
   - Location: ~/Downloads
   - Action: Manually review and delete unneeded files
   - Files: [list top 10 largest files]

2. **Application Remnants** (~8 GB)
   - Apps: [list detected uninstalled apps]
   - Locations: [list paths]
   - Action: Confirm apps are truly uninstalled before deleting data

### 🔴 Keep Unless Certain (High Risk)
Only delete if you know what you're doing:

1. **Docker Volumes** (~3 GB)
   - May contain important data
   - Review with: `docker volume ls`

2. **Time Machine Local Snapshots** (~XX GB)
   - Automatic backups, will be deleted when space needed
   - Command to check: `tmutil listlocalsnapshots /`

第 5 步:确认后执行

重要:未经用户明确确认,绝不执行删除操作。

交互式确认流程:

# Example from scripts/safe_delete.py
def confirm_delete(path: str, size: str, description: str) -> bool:
    """
    Ask user to confirm deletion.

    Args:
        path: File/directory path
        size: Human-readable size
        description: What this file/directory is

    Returns:
        True if user confirms, False otherwise
    """
    print(f"\n🗑️  Confirm Deletion")
    print(f"━━━━━━━━━━━━━━━━━━")
    print(f"Path:        {path}")
    print(f"Size:        {size}")
    print(f"Description: {description}")

    response = input("\nDelete this item? [y/N]: ").strip().lower()
    return response == 'y'

批量操作:

def batch_confirm(items: list) -> list:
    """
    Show all items, ask for batch confirmation.

    Returns list of items user approved.
    """
    print("\n📋 Items to Delete:")
    print("━━━━━━━━━━━━━━━━━━")
    for i, item in enumerate(items, 1):
        print(f"{i}. {item['path']} ({item['size']})")

    print("\nOptions:")
    print("  'all'    - Delete all items")
    print("  '1,3,5'  - Delete specific items by number")
    print("  'none'   - Cancel")

    response = input("\nYour choice: ").strip().lower()

    if response == 'none':
        return []
    elif response == 'all':
        return items
    else:
        # Parse numbers
        indices = [int(x.strip()) - 1 for x in response.split(',')]
        return [items[i] for i in indices if 0 <= i < len(items)]

第 6 步:验证结果

清理后,验证结果并向用户汇报:

# Compare before/after
df -h /

# Calculate space recovered
# (handled by scripts/cleanup_report.py)

报告格式:

✅ Cleanup Complete!

Before: 450 GB used (90%)
After:  385 GB used (77%)
━━━━━━━━━━━━━━━━━━━━━━━━
Recovered: 65 GB

Breakdown:
- System caches:        45 GB
- Downloads:            12 GB
- Homebrew cache:        5 GB
- Application remnants:  3 GB

⚠️ Notes:
- Some applications may take longer to launch on first run
- Deleted items cannot be recovered unless you have Time Machine backup
- Consider running this cleanup monthly

💡 Maintenance Tips:
- Set up automatic Homebrew cleanup: `brew cleanup` weekly
- Review Downloads folder monthly
- Enable "Empty Trash Automatically" in Finder preferences

安全指南

始终保留

未经用户明确指示,绝不删除以下内容:

  • ~/Documents、~/Desktop、~/Pictures 中的内容
  • 正在使用的项目目录
  • 数据库文件(.db、.sqlite)
  • 正在使用的应用的配置文件
  • SSH 密钥、凭据、证书
  • Time Machine 备份
需要 Sudo 确认

这些操作需要提升权限。请让用户手动运行命令:

  • 清理 /Library/Caches(整个系统)
  • 清理 /var/log(系统日志)
  • 清理 /private/var/folders(系统临时文件)

提示示例:

⚠️ This operation requires administrator privileges.

Please run this command manually:
  sudo rm -rf /Library/Caches/*

⚠️ You'll be asked for your password.
备份建议

在执行超过 10 GB 的清理之前,建议:

💡 Safety Tip:
Before cleaning XX GB, consider creating a Time Machine backup.

Quick backup check:
  tmutil latestbackup

If no recent backup, run:
  tmutil startbackup

故障排除

“Operation not permitted” 错误

macOS 可能会因 SIP(系统完整性保护)而阻止删除某些系统文件。

解决方案:不要强行删除。这些保护措施是出于安全考虑。

删除缓存后应用崩溃

这种情况很少见,但可能发生。解决方案:重新启动应用,它会重新生成所需的缓存。

Docker 清理删除了重要数据

预防措施:清理之前,务必列出 Docker 卷:

docker volume ls
docker volume inspect <volume_name>

资源

scripts/
  • analyze_caches.py - 扫描并分类缓存目录
  • find_app_remnants.py - 检测残留的应用数据
  • analyze_large_files.py - 使用智能筛选查找大文件
  • analyze_dev_env.py - 扫描开发环境资源
  • safe_delete.py - 通过交互式确认删除文件
  • cleanup_report.py - 生成清理前后的报告
references/
  • cleanup_targets.md - 详细说明每个清理目标
  • mole_integration.md - 如何将 Mole 与此技能搭配使用
  • safety_rules.md - 绝不可删除内容的完整列表

使用示例

示例 1:快速清理缓存

用户请求:“我的 Mac 空间不足了,你能帮忙吗?”

工作流:

  1. 运行快速诊断
  2. 将系统缓存确定为可快速清理的项目
  3. 展示调查结果:“~/Library/Caches 中有 45 GB”
  4. 说明:“这些文件可以安全删除,应用会重新生成它们”
  5. 请求确认
  6. 执行:rm -rf ~/Library/Caches/*
  7. 报告:“已释放 45 GB”
示例 2:清理开发环境

用户请求:“我是开发者,磁盘已满”

工作流:

  1. 运行 scripts/analyze_dev_env.py
  2. 展示 Docker、npm 和 Homebrew 的调查结果
  3. 说明各个类别
  4. 提供清理命令并加以说明
  5. 让用户执行(不要自动执行 Docker 清理)
  6. 验证结果
示例 3:查找大文件

用户请求:“是什么占用了这么多空间?”

工作流:

  1. 运行 scripts/analyze_large_files.py --threshold 100MB
  2. 展示排名前 20 的大文件及其相关信息
  3. 分类:视频、数据集、归档文件、磁盘映像
  4. 让用户决定要删除哪些文件
  5. 执行经确认的删除操作
  6. 建议将文件归档到外部驱动器

最佳实践

  1. 从保守做法开始:先处理显然安全的目标(缓存、废纸篓)
  2. 解释所有操作:用户应了解自己要删除的内容
  3. 展示示例:列出每个类别中的 3-5 个示例文件
  4. 尊重用户节奏:不要催促用户确认
  5. 记录结果:务必展示清理前后的可用空间
  6. 提供指导:在最终报告中附上维护提示
  7. 整合工具:对于偏好图形界面的用户,建议使用 Mole

不应使用此技能的情况

  • 用户希望自动/静默清理(这违背安全优先原则)
  • 用户需要清理 Windows/Linux 系统(此技能专用于 macOS)
  • 用户的磁盘使用率低于 10%(无需清理)
  • 用户想清理需要禁用 SIP 的系统文件(存在安全风险)

遇到这些情况时,请说明限制并提供替代方案。


注意事项

  • APFS 快照无法通过 rm 删除——请使用 tmutil deletelocalsnapshots。如果清理工具通过 df 报告释放的字节数,可能会发现数值没有变化,因为快照仍占用着数据块。
  • iCloud“优化 Mac 储存空间”会静默地重新下载已清理的文件——请将排除路径列入白名单,否则清理工具会陷入循环。
  • TimeMachine 本地快照会与 iCloud 争用相同的数据块——冲突解决方式不确定;“释放”的空间可能会在一小时内再次被占用。
  • 不了解情况时,切勿清理 /private/var/db/ 中的缓存——有些缓存会在重启时重新生成(成本低),有些则需要重新安装(成本高)。
  • 在 APFS 上,du 与 df 显示的数字差异很大,这是克隆文件导致的——du 报告表观大小;df 报告已用数据块。不要只相信其中一个。
  • 已隔离文件(com.apple.quarantine xattr):如果删除时未考虑 Gatekeeper,它可能会重新添加该属性;某些工作流会因此陷入循环。

评论

支持 Markdown