mcpField
D
disk-cleaner

disk-cleaner

github.com/open-agent-power其他47877 次安装5 周前更新
代码仓库

关于 disk-cleaner

面向 Agent 的磁盘分析与清理 Skill,提供扫描、重复文件检测、安全清理、监控和文件整理脚本。渐进式扫描、快速抽样及默认试运行模式用于处理大磁盘分析和清理。

主要功能

  1. 01渐进式扫描与快速抽样
  2. 02磁盘用量和增长分析
  3. 03重复文件检测
  4. 04试运行清理与交互向导
  5. 05文件整理与用量监控
  6. 06跨平台 Python 脚本

适用场景

  1. 01分析大磁盘前估算扫描时间
  2. 02查找重复文件并跟踪磁盘增长
  3. 03在确认前预览垃圾文件清理
  4. 04归档和整理文件

安装

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

$npx skills add https://github.com/open-agent-power/oh-my-disk-cleaner --skill disk-cleaner

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

包含的文件

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

AGENT_QUICK_REF.txt
disk-cleaner.skill
diskcleaner/
__init__.py
diskcleaner/config/
__init__.py
defaults.py
loader.py
diskcleaner/core/
__init__.py
cache.py
classifier.py
duplicate_finder.py
growth_analyzer.py
interactive.py
organizer.py
process_manager.py
progress.py
safety.py
scanner.py
smart_cleanup.py
diskcleaner/core/rules/
__init__.py
archive_rules.py
diskcleaner/optimization/
__init__.py
concurrency.py
delete.py
hash.py
memory.py
profiler.py
scan.py
diskcleaner/platforms/
__init__.py
linux.py
macos.py

详细介绍

磁盘清理器技能 - 面向所有 Agent 的完整功能指南

🚨 重要:表情符号使用政策

脚本输出(跨平台安全)
  • 绝不要在脚本输出中使用表情符号 - 所有脚本均使用 ASCII 安全字符
  • 脚本使用:[OK]、[X]、[!]、[*]、[i]、[DIR]、[FILE]、[PKG]、[x]
  • 这可确保兼容 Windows GBK 和其他非 UTF-8 控制台
  • 不要修改脚本输出以添加表情符号 - 这会破坏跨平台兼容性
Agent 与用户沟通(推荐)
  • 向用户报告结果时应使用表情符号 - 让输出更易读
  • 在给用户的最终报告中使用以下表情符号:
    • ✅(成功)- 已完成的操作、成功的扫描
    • ❌(错误)- 操作失败、严重错误
    • ⚠️(警告)- 警告、需要注意的问题
    • 🔍(扫描)- 搜索/扫描操作
    • 📊(统计)- 分析结果、统计信息
    • 📁(目录)- 与目录相关的信息
    • 📦(包)- 包/模块信息
    • 🎉(成功)- 成功完成时的庆祝消息
    • 🚨(严重)- 严重警告
    • 💡(提示)- 建议、推荐
    • 📋(列表)- 检查清单、摘要
    • 🔧(工具)- 工具、实用程序
    • 🌐(全局)- 跨平台、通用功能
    • 🛡️(安全)- 安全相关信息
    • ⚡(性能)- 性能改进
    • 📝(文档)- 文档
    • 🎓(学习)- 教育内容
    • 📞(支持)- 帮助、支持信息
    • 📈(增长)- 改进、提升
    • 🎯(目标)- 目标、目的
    • 🚀(启动)- 快速入门、快速操作
    • 🛠️(工具)- 工具相关功能

示例:

Script output (ASCII):    [OK] Scan completed: 50,000 files in 30 seconds
Your report to human:     ✅ Scan completed successfully! Found 50,000 files in 30 seconds

📦 完整功能列表(请先阅读!)

🚨 关键:渐进式扫描(大容量磁盘必须使用)
  • ✅ 快速抽样模式:用 1 秒估算磁盘大小和扫描时间
  • ✅ 渐进式扫描模式:对大容量磁盘,可在 30 秒内获取部分结果
  • ✅ 智能时间限制:避免用户等待数小时
  • ✅ 实时反馈:每 2 秒更新一次进度
  • ✅ 可中断:按 Ctrl+C 获取部分结果
🔧 智能引导(自动检测与导入)
  • ✅ 自动位置检测:搜索 20 多个常见技能包位置
  • ✅ 环境变量支持:可通过 DISK_CLEANER_SKILL_PATH 覆盖
  • ✅ 自动导入模块:自动导入 diskcleaner 模块
  • ✅ 回退机制:即使某些功能不可用,也能正常运行
  • ✅ 跨平台 Python 检测:同时尝试 'python' 和 'python3'
🌐 通用兼容性
  • ✅ 所有 AI IDE:Cursor、Windsurf、Continue、Aider、Claude Code 等
  • ✅ 所有平台:Windows、macOS、Linux(包括 Windows GBK 控制台)
  • ✅ 所有安装级别:全局、项目、用户级别
  • ✅ 无需配置:开箱即用
  • ✅ 跨平台编码:所有脚本均使用 ASCII 安全输出(v2.0+)
🛡️ 安全与可靠性
  • ✅ 诊断工具:check_skill.py - 验证所有功能
  • ✅ 安全编码:所有脚本均使用 ASCII 字符(输出中不含表情符号)
  • ✅ 安全默认设置:清理使用 --dry-run,扫描采用智能限制
  • ✅ 受保护路径:绝不删除系统目录或可执行文件
  • ✅ 错误处理:发生错误时优雅降级
  • ✅ 兼容 GBK/UTF-8:适用于 Windows GBK、UTF-8 及所有其他编码
⚡ 性能优化(全部包含)
  • ✅ QuickProfiler:快速抽样以估算扫描特征
  • ✅ ConcurrentScanner:多线程 I/O,提速 3–5 倍
  • ✅ os.scandir() 优化:比 Path.glob 快 3–5 倍
  • ✅ IncrementalCache:缓存扫描结果,加快重复扫描
  • ✅ 内存监控:根据可用内存自动调整
  • ✅ 提前停止:可配置的文件/时间限制
  • ✅ 增强缓存检测:覆盖 26 个以上的缓存路径(原为 8 个),提升 225%
🆕 v2.2+ 新功能
  • ✅ 重复文件检测:使用自适应策略查找并删除重复文件
  • ✅ 增长趋势分析:跟踪磁盘使用情况随时间的变化,预测磁盘何时会满
  • ✅ 交互式向导:通过逐步引导和安全确认进行清理
  • ✅ 文件整理:智能归档和整理文件(4 种策略)
  • ✅ 增强扫描限制:支持 500K 个文件(原为 50K),超时 120s(原为 30s)
  • ✅ 深度扫描模式:使用 --deep-scan 进行无限制扫描
  • ✅ Windows 目录支持:使用 --include-windows 扫描系统目录
📊 可用脚本(共 13+ 个)

核心分析:

  1. analyze_disk.py - 使用智能抽样分析磁盘(v2.2 增强)
  2. analyze_progressive.py - 渐进式扫描大型磁盘
  3. find_duplicates.py - 检测重复文件(v2.2 新增)
  4. analyze_growth.py - 分析增长趋势(v2.2 新增)

清理与整理: 5. clean_disk.py - 安全清理垃圾文件(增强缓存检测) 6. interactive_wizard.py - 交互式引导清理(v2.2 新增) 7. organize_files.py - 归档和整理文件(v2.2 新增)

监控与诊断: 8. monitor_disk.py - 监控磁盘使用情况 9. check_skill.py - 诊断工具

开发者工具: 10. skill_bootstrap.py - 智能引导模块 11. package_skill.py - 软件包创建工具 12. scheduler.py - 自动化调度

macOS QQ 媒体清理

当 QQ 图片或表情占用 macOS 上过多空间,且必须保留聊天记录时,使用 scripts/qq_cleanup_macos.zsh。

  1. 审核 QQ 存储,不更改文件:

    scripts/qq_cleanup_macos.zsh audit
    
  2. 预览 90 天前的图片和表情:

    scripts/qq_cleanup_macos.zsh clean --older-than-days 90 --categories Pic,Emoji
    
  3. 报告预览结果并获得明确批准。退出 QQ,然后使用 --execute 重复执行 已批准的命令。

切勿选择 nt_db、账户根目录、偏好设置、语音消息、视频或接收的文件。该脚本只接受 Pic 和 Emoji,默认仅预览,并且在 QQ 运行时会拒绝执行。请警告用户,已删除的本地媒体可能 无法在较早的对话中再次查看。

🚀 多 Agent 加速(对性能至关重要)

🎯 关键要点:使用子 Agent 并行处理

这是 AI Agent 使用 disk-cleaner 时最强大的功能之一!

为什么要使用多个 Agent?

单线程扫描:

Agent scans → [Dir1] → [Dir2] → [Dir3] → ... (sequential, slow)

多 Agent 并行扫描:

Main Agent
  ├─ Sub-Agent-1 scans → [Dir1, Dir2, Dir3] (parallel)
  ├─ Sub-Agent-2 scans → [Dir4, Dir5, Dir6] (parallel)
  └─ Sub-Agent-3 scans → [Dir7, Dir8, Dir9] (parallel)
Result: 3-10x faster! ⚡
何时使用多 Agent 模式?

✅ 始终在以下情况使用:

  • 扫描多个顶层目录(例如 C:\、D:\、E:\)
  • 清理多个用户配置文件
  • 处理大型文件集(>100K 个文件)
  • 时间紧迫的操作

❌ 以下情况不要使用:

  • 单个小型目录(<10K 个文件)
  • 快速分析(<30 秒)
  • 简单清理任务
如何实现多 Agent 扫描

选项 1:使用 Agent 工具(推荐用于 Claude Code)

# Agent code that spawns sub-agents
from anthropic import Anthropic

def parallel_scan_directories(directories_list):
    """
    Scan multiple directories in parallel using sub-agents
    """
    # Split directories among sub-agents (3-5 agents optimal)
    chunks = split_list(directories_list, n_chunks=3)
    
    # Launch sub-agents in parallel
    agents = []
    for i, chunk in enumerate(chunks):
        agent = Anthropic().agent.create(
            name=f"scanner-{i}",
            instructions=f"""
            Scan these directories: {chunk}
            Use disk-cleaner with: --file-limit 50000 --time-limit 60
            Return results in JSON format
            """,
            model="claude-sonnet-4-20250514"  # Fast model
        )
        agents.append(agent)
    
    # Wait for all agents and collect results
    results = [agent.wait() for agent in agents]
    return merge_results(results)

选项 2:并行子进程(跨平台)

import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed

def parallel_scan_subprocess(directories_list):
    """
    Scan multiple directories using parallel subprocess calls
    Works with ALL AI IDEs that support subprocess
    """
    def scan_directory(directory):
        """Scan a single directory"""
        cmd = [
            'python',
            'skills/disk-cleaner/scripts/analyze_disk.py',
            '--path', str(directory),
            '--file-limit', '50000',
            '--json'
        ]
        result = subprocess.run(cmd, capture_output=True, text=True)
        return json.loads(result.stdout)
    
    # Use 3-5 parallel workers
    with ThreadPoolExecutor(max_workers=4) as executor:
        futures = {
            executor.submit(scan_directory, d): d
            for d in directories_list
        }
        
        results = {}
        for future in as_completed(futures):
            directory = futures[future]
            try:
                results[directory] = future.result()
            except Exception as e:
                results[directory] = {"error": str(e)}
    
    return results

# Usage: Scan C:\, D:\, E:\ in parallel
directories = ['C:\\', 'D:\\', 'E:\\']
results = parallel_scan_subprocess(directories)

选项 3:多平台 Agent 团队(高级)

适用于支持 Agent 的系统(Claude Code、支持 Agent 的 Cursor):

# Create agent team for massive parallelism
def create_agent_team_scan(top_level_paths):
    """
    Create a team of sub-agents, each handling a portion of the work
    """
    team_config = {
        "name": "disk-cleaner-team",
        "members": [
            {
                "name": "scanner-1",
                "task": f"Scan {top_level_paths[0]} using progressive mode",
                "tool_use": "subprocess"
            },
            {
                "name": "scanner-2",
                "task": f"Scan {top_level_paths[1]} using progressive mode",
                "tool_use": "subprocess"
            },
            {
                "name": "scanner-3",
                "task": f"Scan {top_level_paths[2]} using progressive mode",
                "tool_use": "subprocess"
            }
        ],
        "coordination": "parallel",  # All run at once
        "aggregation": "merge_results"  # Combine results at end
    }
    
    return launch_agent_team(team_config)
性能对比
场景单个 Agent3 个子 Agent加速比
3 个磁盘(每个 1TB)约 15 分钟约 5 分钟3 倍
10 个用户配置文件约 20 分钟约 4 分钟5 倍
1M 个文件约 30 分钟约 6 分钟5 倍
缓存清理(26 个位置)约 8 分钟约 2 分钟4 倍
推荐的 Agent 数量
  • 小型任务(<50K 个文件):1 个 Agent(不值得承担额外开销)
  • 中型任务(50K-500K 个文件):2-3 个 Agent
  • 大型任务(500K-2M 个文件):3-5 个 Agent
  • 超大型任务(>2M 个文件):5-8 个 Agent

最佳数量:3-4 个 Agent(速度与额外开销之间的最佳平衡)

最佳实践
  1. 按逻辑划分工作:按磁盘、用户配置文件、目录类型划分
  2. 使用一致的参数:所有 Agent 使用相同的扫描限制
  3. 谨慎合并结果:去重、排序、格式化
  4. 妥善处理故障:如果某个 Agent 失败,继续运行其他 Agent
  5. 监控进度:跟踪哪些 Agent 已完成

⚠️ IMPORTANT:并非所有 AI IDE 都支持子 Agent。如果无法使用,请改用并行子进程。

📚 文档(仅必要文件)
  • SKILL.md - 本完整指南(请先阅读)
  • README.md - 项目概览和快速入门
  • README_zh.md - 中文文档
  • CHANGELOG.md - 版本历史和变更
  • AGENT_QUICK_REF.txt - Agent 单页参考
  • INSTALL.md - 详细安装指南
  • NO_PYTHON_GUIDE.md - 为没有 Python 的用户提供的帮助
  • references/temp_locations.md - 特定平台的缓存位置

🎯 Agent 检查清单(必须遵循)

对于任何磁盘分析请求:
[ ] STEP 1: Check Python availability
[ ] STEP 2: Find skill package (auto-detects 20+ locations)
[ ] STEP 3: Run diagnostics: python scripts/check_skill.py
[ ] STEP 4: Run quick sample: --sample (MANDATORY - do this FIRST)
[ ] STEP 5: Choose scan mode based on estimate
[ ] STEP 6: Inform user of expected time
[ ] STEP 7: Execute scan with appropriate limits
[ ] STEP 8: Show results and offer next steps
对于任何清理请求:
[ ] STEP 1-3: Same as above
[ ] STEP 4: ALWAYS use --dry-run first (MANDATORY)
[ ] STEP 5: Show preview results
[ ] STEP 6: Ask user confirmation before --force
[ ] STEP 7: Execute actual cleaning if confirmed

⚡ 渐进式扫描(大容量磁盘的关键)

🚨 关键信息(请先阅读)

通用兼容性
  • ✅ 适用于所有 AI IDE:Cursor、Windsurf、Continue、Aider、Claude Code 等
  • ✅ 跨平台:Windows、macOS、Linux
  • ✅ 安装方式不限:支持全局、项目或用户级安装
  • ✅ 自包含:无外部依赖,只需 Python 3.7+
唯一要求
import subprocess
result = subprocess.run(['python', '--version'], capture_output=True, text=True)
# If this succeeds, you can use this skill

⚡ 渐进式扫描(大容量磁盘的关键)

🚨 Agent 必须在大容量磁盘(>100GB)上使用

问题:在大容量磁盘(500GB+)上进行完整磁盘扫描可能需要数小时。用户会失去耐心。

解决方案:使用渐进式扫描——几秒内获取结果,而不是数小时!

📋 三种扫描模式
模式 1:快速抽样(⚡ 最快 - 1 秒)

使用场景:立即估算目录大小和扫描时间

python scripts/analyze_disk.py --sample
# OR
python scripts/analyze_progressive.py --sample

输出:

{
  "sample_file_count": 7591,
  "sample_size_gb": 17.62,
  "files_per_second": 7501.0,
  "estimated_time_seconds": 2.0
}

Agent 决策逻辑:

# ALWAYS run quick sample first for unknown disk sizes
result = subprocess.run(
    ['python', 'scripts/analyze_disk.py', '--sample', '--json'],
    capture_output=True,
    text=True,
    timeout=10,
    cwd=skill_path
)

import json
sample = json.loads(result.stdout)
estimated_time = sample.get('estimated_time_seconds', 0)

# Choose next action based on estimate
if estimated_time < 30:
    mode = 'full'  # Full scan is fine
elif estimated_time < 120:
    mode = 'time_limited'  # Use time limit
else:
    mode = 'progressive'  # MUST use progressive mode
模式 2:渐进式扫描(🎯 大容量磁盘推荐)

使用场景:在大容量磁盘上于 30 秒内获取部分结果

python scripts/analyze_progressive.py --max-seconds 30

功能:

  • ✅ 每 2 秒实时更新进度
  • ✅ 随发现结果随时显示部分结果
  • ✅ 可按 Ctrl+C 中断并保留结果
  • ✅ 智能文件数量限制(默认 50,000)

Agent 用法:

def analyze_large_disk_safely(path, max_seconds=30):
    """Safely analyze large disk with time limit"""
    result = subprocess.run(
        ['python', 'scripts/analyze_progressive.py',
         '--max-seconds', str(max_seconds),
         '--path', str(path)],
        capture_output=True,
        text=True,
        timeout=max_seconds + 10,
        cwd=skill_path
    )
    return result.stdout
模式 3:有限扫描(📊 快速获取结果)

使用场景:通过设置文件数或时间限制快速获取结果

# Limit by file count (fast)
python scripts/analyze_disk.py --file-limit 10000

# Limit by time (safe)
python scripts/analyze_disk.py --time-limit 30

# Both limits (very fast)
python scripts/analyze_disk.py --file-limit 10000 --time-limit 30
🎯 Agent 决策树(关键 - 请遵循)
USER REQUEST: "Analyze my disk"
    ↓
┌─────────────────────────────────────────┐
│ STEP 1: Quick Sample (MANDATORY)          │
│ python scripts/analyze_disk.py --sample │
└─────────────────────────────────────────┘
    ↓
    Get estimated_time from sample
    ↓
    ├─ estimated_time < 30 seconds
    │   ↓
    │   ✅ Use FULL SCAN
    │   python scripts/analyze_disk.py
    │
    ├─ estimated_time 30-120 seconds
    │   ↓
    │   ⚠️ Use TIME LIMIT
    │   python scripts/analyze_disk.py --time-limit 60
    │   Tell user: "This will take ~X minutes"
    │
    └─ estimated_time > 120 seconds
        ↓
        🚨 MUST USE PROGRESSIVE MODE
        python scripts/analyze_progressive.py --max-seconds 30
        Tell user: "Large disk detected - using progressive scan (30 seconds)"
📝 必需的回复模板
快速抽样显示 < 30 秒时
✅ Disk analysis will take approximately 2 seconds
Starting full scan...
快速抽样显示 30-120 秒时
⚠️ Disk analysis will take approximately 3 minutes
Using time-limited scan for faster results...
快速抽样显示 > 120 秒时
🚨 Large disk detected! Full scan would take approximately 5 minutes
Using progressive scan mode to get results in 30 seconds...
(This gives you partial results quickly - you can always do a full scan later)
💡 可复制粘贴的代码(请使用)
import subprocess
import json
from pathlib import Path

def smart_disk_analysis(disk_path, python_cmd='python'):
    """
    SMART disk analysis - automatically chooses best method

    THIS IS THE RECOMMENDED WAY for all agents
    """
    # Find skill package
    skill_path = find_skill_package()  # Use your find function
    if not skill_path:
        return False, "Skill package not found"

    # STEP 1: Quick sample (MANDATORY - do this first!)
    print("🔍 Quick sampling disk...")
    sample_result = subprocess.run(
        [python_cmd, 'scripts/analyze_disk.py', '--sample',
         '--path', str(disk_path), '--json'],
        capture_output=True,
        text=True,
        timeout=10,
        cwd=str(skill_path)
    )

    if sample_result.returncode != 0:
        return False, "Sample failed"

    try:
        sample = json.loads(sample_result.stdout)
        estimated_time = sample.get('estimated_time_seconds', 0)
    except:
        estimated_time = 0

    print(f"   Estimated scan time: {estimated_time:.0f} seconds")

    # STEP 2: Choose scanning method based on estimate
    if estimated_time < 30:
        # Small disk - full scan
        print("✅ Using full scan (small disk)")
        result = subprocess.run(
            [python_cmd, 'scripts/analyze_disk.py',
             '--path', str(disk_path)],
            capture_output=True,
            text=True,
            timeout=60,
            cwd=str(skill_path)
        )

    elif estimated_time < 120:
        # Medium disk - time limited
        minutes = estimated_time / 60
        print(f"⚠️  Using time-limited scan (~{minutes:.1f} minutes)")
        result = subprocess.run(
            [python_cmd, 'scripts/analyze_disk.py',
             '--path', str(disk_path),
             '--time-limit', '60'],  # 1 minute max
            capture_output=True,
            text=True,
            timeout=70,
            cwd=str(skill_path)
        )

    else:
        # Large disk - PROGRESSIVE MODE (MANDATORY)
        print(f"🚨 Large disk detected! Using progressive scan (30 seconds)")
        result = subprocess.run(
            [python_cmd, 'scripts/analyze_progressive.py',
             '--path', str(disk_path),
             '--max-seconds', '30',
             '--json'],
            capture_output=True,
            text=True,
            timeout=40,
            cwd=str(skill_path)
        )

    if result.returncode != 0:
        return False, result.stderr

    print(result.stdout)
    return True, result.stdout

# USAGE - Just call this function:
success, output = smart_disk_analysis("C:\\")
success, output = smart_disk_analysis("/home/user")
success, output = smart_disk_analysis("D:\\Projects")
⚠️ 应避免的常见错误

❌ 不要:不先检查磁盘大小就始终运行完整扫描 ✅ 应该:始终先运行 --sample 进行估算

❌ 不要:让用户为大容量磁盘扫描等待数小时 ✅ 应该:在大容量磁盘上使用 --max-seconds 30

❌ 不要:忽略抽样得出的预计时间 ✅ 应该:根据估算选择合适的扫描模式

❌ 不要:在 1TB 磁盘上不加限制地运行 analyze_disk.py ✅ 应该:使用 analyze_progressive.py 和 --max-seconds

📊 命令参考卡
情况命令时间结果
大小未知--sample1s估算 + 建议
< 30 秒analyze_disk.py<30s完整结果
30-120 秒--time-limit 6060s大部分结果
> 120 秒analyze_progressive.py --max-seconds 3030s部分结果
超大容量磁盘analyze_progressive.py --max-seconds 6060s更多结果
🔍 渐进式扫描的工作原理
  1. 快速抽样(1 秒)

    • 在 1 秒内尽可能多地扫描文件
    • 计算扫描速率(文件数/秒)
    • 估算扫描总时长
    • 立即提供反馈
  2. 渐进式扫描(N 秒)

    • 连续扫描 N 秒
    • 每 2 秒显示一次进度
    • 边扫描边收集结果
    • 时间到后返回已找到的结果
    • 用户可以中断扫描并保留部分结果
  3. 智能停止

    • 达到时间或文件数量限制时自动停止
    • 妥善处理中断
    • 部分结果仍然有用
🎯 Agent 最佳实践
  1. 务必先运行 --sample
  2. 务必先检查 estimated_time,再选择模式
  3. 务必告知用户预计扫描时长
  4. 务必对大型磁盘(超过 2 分钟)使用渐进模式
  5. 切勿让用户等待超过 2 分钟而没有反馈


🎯 通用 Agent 工作流

此工作流适用于任何平台、任何 AI IDE 和任何位置。

步骤 1:验证 Python
import subprocess
import sys

def verify_python():
    """Check if Python 3.7+ is available - PLATFORM AGNOSTIC"""
    try:
        # Try 'python' first (Windows, some Unix)
        result = subprocess.run(
            ['python', '--version'],
            capture_output=True,
            text=True,
            timeout=5
        )
        if result.returncode == 0:
            return True, result.stderr.strip() or result.stdout.strip()
    except FileNotFoundError:
        pass

    try:
        # Try 'python3' (macOS, Linux)
        result = subprocess.run(
            ['python3', '--version'],
            capture_output=True,
            text=True,
            timeout=5
        )
        if result.returncode == 0:
            return True, result.stderr.strip() or result.stdout.strip()
    except FileNotFoundError:
        pass

    return False, "Python not found"

# EXECUTE
python_available, version_info = verify_python()
if not python_available:
    print("❌ Python 3.7+ required but not found")
    print("Install from: https://www.python.org/downloads/")
    print("See: NO_PYTHON_GUIDE.md for platform-specific instructions")
    sys.exit(1)

print(f"✅ Python available: {version_info}")
步骤 2:定位技能包
from pathlib import Path
import os

def find_skill_package():
    """
    Find disk-cleaner skill package - LOCATION INDEPENDENT

    Searches in order of priority:
    1. Current working directory
    2. Project-level: ./skills/, ./.skills/, ./agent-skills/
    3. User-level: ~/.skills/, ~/.agent-skills/, ~/skill-packages/
    4. Common AI IDE locations
    5. Parent directories
    """

    # Get python command (python or python3)
    python_cmd = 'python' if os.name == 'nt' else 'python3'

    # Search locations - PLATFORM & IDE AGNOSTIC
    search_locations = []

    # 1. Current directory
    cwd = Path.cwd()
    search_locations.extend([
        cwd / 'disk-cleaner',
        cwd / 'skills' / 'disk-cleaner',
        cwd / '.skills' / 'disk-cleaner',
        cwd / 'agent-skills' / 'disk-cleaner',
        cwd / '.agent-skills' / 'disk-cleaner',
    ])

    # 2. Parent directories (project root)
    for parent in [cwd, *cwd.parents]:
        search_locations.extend([
            parent / 'skills' / 'disk-cleaner',
            parent / '.skills' / 'disk-cleaner',
            parent / 'agent-skills' / 'disk-cleaner',
        ])
        # Limit search depth
        if len(parent.parts) <= 3:
            break

    # 3. User home directory
    home = Path.home()
    search_locations.extend([
        home / 'skills' / 'disk-cleaner',
        home / '.skills' / 'disk-cleaner',
        home / 'agent-skills' / 'disk-cleaner',
        home / '.agent-skills' / 'disk-cleaner',
        home / 'skill-packages' / 'disk-cleaner',
    ])

    # 4. Platform-specific user directories
    if os.name == 'nt':  # Windows
        appdata = os.environ.get('APPDATA', '')
        if appdata:
            search_locations.append(Path(appdata) / 'skills' / 'disk-cleaner')
        localappdata = os.environ.get('LOCALAPPDATA', '')
        if localappdata:
            search_locations.append(Path(localappdata) / 'skills' / 'disk-cleaner')
    else:  # Unix-like (macOS, Linux)
        search_locations.extend([
            home / '.local' / 'share' / 'skills' / 'disk-cleaner',
            home / '.config' / 'skills' / 'disk-cleaner',
            Path('/usr/local/share/skills/disk-cleaner'),
        ])

    # 5. AI IDE specific directories (IDE-AGNOSTIC)
    # Note: These are examples - actual locations vary
    ide_specific = [
        # Cursor
        home / '.cursor' / 'skills' / 'disk-cleaner',
        home / '.cursor' / 'user' / 'skills' / 'disk-cleaner',
        # Windsurf
        home / '.windsurf' / 'skills' / 'disk-cleaner',
        # Continue
        home / '.continue' / 'skills' / 'disk-cleaner',
        # Generic
        home / '.ai-ide' / 'skills' / 'disk-cleaner',
    ]
    search_locations.extend(ide_specific)

    # 6. sys.path entries (Python module style)
    for path_entry in sys.path:
        if path_entry and path_entry not in ['', '.']:
            test_path = Path(path_entry) / 'disk-cleaner'
            search_locations.append(test_path)

    # Remove duplicates and non-existent
    search_locations = list(set(search_locations))

    # Search for valid skill package
    for location in search_locations:
        if not location:
            continue
        try:
            # Check for key indicator files
            if (location / 'scripts' / 'analyze_disk.py').exists():
                return location, f"Found at: {location}"
            if (location / 'SKILL.md').exists():
                return location, f"Found at: {location}"
        except PermissionError:
            continue
        except Exception:
            continue

    # Not found - provide helpful message
    print("❌ Skill package not found")
    print("\nSearched locations:")
    for loc in search_locations[:10]:  # Show first 10
        print(f"  - {loc}")
    print("\nSolutions:")
    print("1. Extract skill package to one of the locations above")
    print("2. Or set environment variable: DISK_CLEANER_SKILL_PATH")
    print("3. Or provide explicit path when calling functions")
    return None, "Not found"

# EXECUTE
skill_path, message = find_skill_package()
if not skill_path:
    print(message)
    sys.exit(1)

print(f"✅ {message}")
步骤 3:验证技能包
def verify_skill_package(skill_path, python_cmd='python'):
    """Verify skill package integrity - LOCATION INDEPENDENT"""
    check_script = skill_path / 'scripts' / 'check_skill.py'

    if not check_script.exists():
        print(f"❌ Check script not found: {check_script}")
        return False

    try:
        result = subprocess.run(
            [python_cmd, str(check_script)],
            capture_output=True,
            text=True,
            timeout=30,
            cwd=str(skill_path)
        )

        # Show verification output
        if result.stdout:
            print(result.stdout)

        if result.returncode == 0:
            print("✅ Skill package verified successfully")
            return True
        else:
            print("❌ Skill package verification failed")
            if result.stderr:
                print(result.stderr)
            return False

    except subprocess.TimeoutExpired:
        print("❌ Verification timed out")
        return False
    except Exception as e:
        print(f"❌ Verification error: {e}")
        return False

# Determine python command
python_cmd = 'python' if os.name == 'nt' else 'python3'

# EXECUTE
if not verify_skill_package(skill_path, python_cmd):
    sys.exit(1)
步骤 4:执行操作
def execute_operation(skill_path, operation, python_cmd='python', **kwargs):
    """
    Execute disk cleaner operation - PLATFORM & IDE AGNOSTIC

    Args:
        skill_path: Path to skill package
        operation: 'analyze', 'clean', 'monitor'
        python_cmd: 'python' or 'python3'
        **kwargs: Operation-specific arguments
    """

    operation_map = {
        'analyze': 'analyze_disk.py',
        'clean': 'clean_disk.py',
        'monitor': 'monitor_disk.py',
    }

    if operation not in operation_map:
        print(f"❌ Unknown operation: {operation}")
        print(f"Valid operations: {list(operation_map.keys())}")
        return False, None

    script = skill_path / 'scripts' / operation_map[operation]
    cmd = [python_cmd, str(script)]

    # Add operation-specific arguments
    if operation == 'analyze':
        if kwargs.get('path'):
            cmd.extend(['--path', str(kwargs['path'])])
        if kwargs.get('top'):
            cmd.extend(['--top', str(kwargs['top'])])
        if kwargs.get('json'):
            cmd.append('--json')

    elif operation == 'clean':
        # ALWAYS use dry-run for safety
        if not kwargs.get('force'):
            cmd.append('--dry-run')
        else:
            cmd.append('--force')

        if kwargs.get('temp'):
            cmd.append('--temp')
        if kwargs.get('cache'):
            cmd.append('--cache')
        if kwargs.get('logs'):
            cmd.append('--logs')

    elif operation == 'monitor':
        if kwargs.get('watch'):
            cmd.append('--watch')
        if kwargs.get('json'):
            cmd.append('--json')

    try:
        print(f"🔧 Executing: {' '.join(cmd)}")

        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=kwargs.get('timeout', 300),
            cwd=str(skill_path)
        )

        # Show output
        if result.stdout:
            print(result.stdout)

        if result.returncode != 0:
            if result.stderr:
                print(f"❌ Error: {result.stderr}")
            return False, None

        return True, result.stdout

    except subprocess.TimeoutExpired:
        print("⚠️ Operation timed out")
        return False, None
    except Exception as e:
        print(f"❌ Execution error: {e}")
        return False, None

# EXECUTE
success, output = execute_operation(
    skill_path,
    operation='analyze',
    python_cmd=python_cmd,
    path='C:\\Users' if os.name == 'nt' else '/home',
    json=True
)

if success:
    print("✅ Operation completed successfully")

📋 快速参考(所有 IDE)

⚠️ 关键提示:大型磁盘请使用渐进式扫描!

进行任何磁盘分析之前:

  1. 先运行 --sample 以估算扫描时长
  2. 如果估算时长超过 2 分钟,请使用渐进模式
  3. 切勿让用户等待超过 2 分钟而没有反馈

快速参考:

# STEP 1: ALWAYS DO THIS FIRST (1 second)
python scripts/analyze_disk.py --sample

# STEP 2: Choose based on estimate
# < 30s: python scripts/analyze_disk.py
# 30-120s: python scripts/analyze_disk.py --time-limit 60
# > 120s: python scripts/analyze_progressive.py --max-seconds 30
用户意图 → 操作映射
用户意图 → 操作映射
用户说法操作命令模板
“分析磁盘”分析python scripts/analyze_disk.py
“检查磁盘空间”分析python scripts/analyze_disk.py --top 50
“快速扫描”分析python scripts/analyze_disk.py --sample
“分析大型磁盘”分析python scripts/analyze_progressive.py --max-seconds 30
“清理临时文件”清理python scripts/clean_disk.py --temp --dry-run
“预览清理”清理python scripts/clean_disk.py --dry-run
“监控磁盘”监控python scripts/monitor_disk.py
“磁盘使用情况”监控python scripts/monitor_disk.py --json
渐进式扫描(适用于大型磁盘)

问题:在大型磁盘(1TB 及以上)上,完整磁盘扫描可能需要数小时

解决方案:使用带有时间或文件数量限制的渐进式扫描

# Quick sample (1 second) - Get instant estimate
subprocess.run(['python', 'scripts/analyze_disk.py', '--sample'])

# Progressive scan (30 seconds) - Get partial results quickly
subprocess.run(['python', 'scripts/analyze_progressive.py',
                 '--max-seconds', '30'])

# Limited file count (fast)
subprocess.run(['python', 'scripts/analyze_disk.py',
                 '--file-limit', '10000'])

# Full scan with time limit
subprocess.run(['python', 'scripts/analyze_disk.py',
                 '--time-limit', '120'])

大型磁盘的建议工作流:

  1. 首先运行 --sample 获取估算值(1 秒)
  2. 如果估算时长过长,请使用 --max-seconds 或 --file-limit
  3. 或使用 analyze_progressive.py 获取实时反馈
跨平台 Python 命令
平台Python 命令检查命令
Windowspythonpython --version
macOSpython3python3 --version
Linuxpython3python3 --version
通用命令模板
# Works on ALL platforms
import os
import subprocess

python_cmd = 'python' if os.name == 'nt' else 'python3'
result = subprocess.run([python_cmd, '--version'], capture_output=True, text=True)

🌐 多 IDE 兼容性

此技能包适用于所有支持以下功能的 AI IDE:

支持的 AI IDE
  • ✅ Cursor - 可作为项目级或用户级技能使用
  • ✅ Windsurf - 可在任何位置使用
  • ✅ Continue - 可作为全局或项目级技能使用
  • ✅ Aider - 可作为 Agent 工具使用
  • ✅ Claude Code - 可作为技能使用
  • ✅ 任何 AI IDE - 可通过子进程使用
按 IDE 类型安装
项目级安装
your-project/
├── skills/
│   └── disk-cleaner/    ← Extract here
├── src/
└── README.md
用户级安装
~/.skills/disk-cleaner/      ← Unix-like
~/agent-skills/disk-cleaner/ ← Alternative
C:\Users\You\skills\disk-cleaner\ ← Windows
全局安装
/usr/local/share/skills/disk-cleaner/  ← Linux (system-wide)
C:\ProgramData\skills\disk-cleaner\   ← Windows (system-wide)

🔧 IDE 特定说明

Cursor
# Cursor automatically searches for skills in:
# - .cursor/skills/
# - project/skills/
# - ~/.skills/

# No special configuration needed
Windsurf
# Windsurf supports skills at:
# - .windsurf/skills/
# - project/skills/

# Skill works via subprocess, no special setup
Continue
# Continue configuration (if needed):
# {
#   "skills": ["./skills/disk-cleaner"]
# }
# But auto-detection works in most cases
Aider
# Use as a tool via subprocess:
# !python skills/disk-cleaner/scripts/analyze_disk.py
通用/其他 IDE
# The skill includes intelligent auto-detection
# Just extract and use - no configuration needed

🎯 完整的复制粘贴模板

"""
Universal Disk Cleaner Skill Usage
Works with ALL AI IDEs, on ALL platforms, at ANY location
"""

import subprocess
import sys
import os
from pathlib import Path


def use_disk_cleaner(operation='analyze', **kwargs):
    """
    Use disk cleaner skill - UNIVERSAL FUNCTION

    Works on:
    - All platforms (Windows, macOS, Linux)
    - All AI IDEs (Cursor, Windsurf, Continue, etc.)
    - All installation levels (global, project, user)

    Args:
        operation: 'analyze', 'clean', 'monitor'
        **kwargs: Operation-specific arguments

    Returns:
        (success: bool, output: str)
    """

    # 1. Determine Python command
    python_cmd = 'python' if os.name == 'nt' else 'python3'

    # 2. Verify Python
    try:
        result = subprocess.run(
            [python_cmd, '--version'],
            capture_output=True,
            text=True,
            timeout=5
        )
        if result.returncode != 0:
            print("❌ Python not found")
            return False, "Python 3.7+ required"
    except Exception as e:
        print(f"❌ Python check failed: {e}")
        return False, str(e)

    # 3. Find skill package (intelligent search)
    def find_skill():
        search_paths = [
            # Current directory
            Path.cwd() / 'disk-cleaner',
            Path.cwd() / 'skills' / 'disk-cleaner',
            Path.cwd() / '.skills' / 'disk-cleaner',
            # Project root
            *[(p / 'skills' / 'disk-cleaner') for p in [Path.cwd(), *Path.cwd().parents][:3]],
            # User home
            Path.home() / 'skills' / 'disk-cleaner',
            Path.home() / '.skills' / 'disk-cleaner',
        ]

        for path in search_paths:
            if (path / 'scripts' / 'analyze_disk.py').exists():
                return path
        return None

    skill_path = find_skill()
    if not skill_path:
        print("❌ Skill package not found")
        print("Extract to: skills/disk-cleaner/ or ~/.skills/disk-cleaner/")
        return False, "Skill package not found"

    # 4. Execute operation
    scripts = {
        'analyze': 'analyze_disk.py',
        'clean': 'clean_disk.py',
        'monitor': 'monitor_disk.py',
    }

    if operation not in scripts:
        return False, f"Unknown operation: {operation}"

    script = skill_path / 'scripts' / scripts[operation]
    cmd = [python_cmd, str(script)]

    # Add arguments
    if operation == 'analyze':
        if kwargs.get('path'):
            cmd.extend(['--path', str(kwargs['path'])])
    elif operation == 'clean':
        cmd.append('--dry-run')  # Always safe
    elif operation == 'monitor':
        if kwargs.get('json'):
            cmd.append('--json')

    # Run
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=300,
            cwd=str(skill_path)
        )

        return result.returncode == 0, result.stdout

    except Exception as e:
        return False, str(e)


# USAGE EXAMPLES:
# success, output = use_disk_cleaner('analyze', path='.')
# success, output = use_disk_cleaner('clean')
# success, output = use_disk_cleaner('monitor', json=True)

if __name__ == "__main__":
    # Quick test
    success, output = use_disk_cleaner('analyze')
    print(output)

⚡ 渐进式扫描检查清单(关键)

Agent 必须遵循以下要求,处理所有磁盘分析请求:
[ ] Did you run --sample FIRST to estimate scan time?
[ ] Did you inform user about expected scan time?
[ ] Did you choose appropriate mode based on estimate?
[ ] Did you use progressive mode for >2 minute estimates?
[ ] Did you provide feedback during long scans?
按磁盘大小执行的必需行为:

小型磁盘(预计少于 30 秒):

  • ✅ 运行完整扫描
  • ✅ 无需特殊处理

中型磁盘(预计 30–120 秒):

  • ✅ 使用 --time-limit
  • ✅ 告知用户预计耗时
  • ⚠️ 如果用户似乎不耐烦,可考虑渐进模式

大型磁盘(预计超过 120 秒):

  • 🚨 必须使用渐进模式
  • 🚨 必须告知用户时间限制
  • ✅ 说明部分结果
  • ✅ 提供完整扫描选项
必需的代码模式:
# THIS IS THE REQUIRED PATTERN for all disk analysis:

def safe_disk_analysis(disk_path):
    # Step 1: ALWAYS sample first
    sample = subprocess.run(
        ['python', 'scripts/analyze_disk.py', '--sample', '--json'],
        capture_output=True,
        text=True,
        cwd=skill_path
    )
    import json
    data = json.loads(sample.stdout)
    estimate = data.get('estimated_time_seconds', 0)

    # Step 2: Inform user
    if estimate > 120:
        print(f"Large disk detected! Estimated: {estimate/60:.1f} minutes")
        print("Using progressive scan (30 seconds) for quick results...")

    # Step 3: Choose mode
    if estimate < 30:
        # Full scan
        return subprocess.run(['python', 'scripts/analyze_disk.py'])
    elif estimate < 120:
        # Time limited
        return subprocess.run(['python', 'scripts/analyze_disk.py', '--time-limit', '60'])
    else:
        # Progressive (MANDATORY for large disks)
        return subprocess.run(['python', 'scripts/analyze_progressive.py', '--max-seconds', '30'])

🚨 错误处理(通用)

错误:未找到 Python
# SOLUTION - Platform-independent guidance
import platform

system = platform.system()
if system == "Windows":
    print("Install from: https://www.python.org/downloads/")
    print("Check 'Add Python to PATH' during installation")
elif system == "Darwin":  # macOS
    print("Install: brew install [email protected]")
    print("Or: https://www.python.org/downloads/macos/")
else:  # Linux
    print("Install: sudo apt install python3  # Debian/Ubuntu")
    print("Or: sudo dnf install python3      # Fedora")
错误:未找到技能
# SOLUTION - Show all searched locations
print("Skill package not found.")
print("Extract to ONE of these locations:")
print("  - ./skills/disk-cleaner/")
print("  - ./disk-cleaner/")
print("  - ~/.skills/disk-cleaner/")
print("  - project/skills/disk-cleaner/")
print("\nOr set: DISK_CLEANER_SKILL_PATH=/path/to/skill")
错误:权限被拒绝
# SOLUTION - Platform-specific advice
if os.name == 'nt':
    print("Run as Administrator if needed")
else:
    print("Some directories may require: sudo")
    print("Or adjust: chmod +x scripts/*.py")

📝 环境变量(可选)

你可以选择设置以下变量,以帮助自动检测:

# Set skill package location (overrides auto-detection)
export DISK_CLEANER_SKILL_PATH=/path/to/skills/disk-cleaner

# Set Python command (overrides auto-detection)
export DISK_CLEANER_PYTHON_CMD=python3

# Enable debug output
export DISK_CLEANER_DEBUG=true

🎓 所有 Agent 的最佳实践

  1. 始终先检查 Python——不要假设它已安装
  2. 在 Unix 上使用 python3——在 Windows 上使用 python
  3. 搜索多个位置——不要假设只有一个安装路径
  4. 使用带超时的 subprocess——防止进程挂起
  5. 同时捕获 stdout 和 stderr——获取完整的错误信息
  6. 清理时优先使用 --dry-run——安全第一
  7. 处理所有异常——优雅降级
  8. 显示有帮助的错误消息——引导用户找到解决方案

🔍 故障排除(通用)

问题:技能在一个 IDE 中可用,在另一个 IDE 中却不可用

解决方案:该技能与 IDE 无关。请检查:

  1. Python 是否可从该 IDE 访问
  2. 技能包是否位于可搜索的位置
  3. 文件权限是否允许执行
问题:不同平台上的行为不同

解决方案:该技能会处理平台差异。请检查:

  1. Python 命令(python 与 python3)
  2. 路径分隔符(由 pathlib 自动处理)
  3. 文件权限(Unix 上可能需要 chmod +x)
问题:找不到技能包

解决方案:运行诊断:

python skills/disk-cleaner/scripts/check_skill.py
# Or
python3 skills/disk-cleaner/scripts/check_skill.py

📦 包含的内容(通用)

disk-cleaner/
├── SKILL.md              # This file
├── AGENT_QUICK_REF.txt   # Quick reference
├── NO_PYTHON_GUIDE.md    # Help for users without Python
├── INSTALL.md            # Installation guide
├── FIXES.md              # What's fixed in v2.0
├── scripts/              # All scripts (universal)
├── diskcleaner/          # Core modules (self-contained)
└── references/           # Platform information

✅ 通用检查清单

在任何 AI IDE 中使用此技能之前:

  • 已安装 Python 3.7+
  • 技能包已解压到可访问的位置
  • 可以运行:python --version(或 python3 --version)
  • 知道技能包的位置(或让它自动检测)

此技能包可在任何地方使用——只需要 Python 3.7+!

无需针对 IDE 进行配置。无需针对平台进行设置。没有安装级别限制。

只需解压并使用!

评论

支持 Markdown