disk-cleaner について
エージェント向けのディスク分析・クリーンアップスキルで、スキャン、重複検出、安全な削除、監視、ファイル整理のスクリプトを提供します。段階的なスキャン、サンプル調査、既定のドライランで大容量ディスクの分析や整理を支援します。
主な機能
- 01段階的スキャンとクイックサンプル
- 02ディスク使用量と増加傾向の分析
- 03重複ファイルの検出
- 04ドライラン削除と対話型ウィザード
- 05ファイル整理と使用量監視
- 06クロスプラットフォーム対応のPythonスクリプト
活用シーン
- 01大容量ディスクの分析前に所要時間を推定
- 02重複ファイルの検索と容量増加の追跡
- 03承認前に不要ファイル削除をプレビュー
- 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.txtdisk-cleaner.skilldiskcleaner/__init__.pydiskcleaner/config/__init__.pydefaults.pyloader.pydiskcleaner/core/__init__.pycache.pyclassifier.pyduplicate_finder.pygrowth_analyzer.pyinteractive.pyorganizer.pyprocess_manager.pyprogress.pysafety.pyscanner.pysmart_cleanup.pydiskcleaner/core/rules/__init__.pyarchive_rules.pydiskcleaner/optimization/__init__.pyconcurrency.pydelete.pyhash.pymemory.pyprofiler.pyscan.pydiskcleaner/platforms/__init__.pylinux.pymacos.py詳細
Disk Cleaner Skill - すべてのエージェント向け完全機能ガイド
🚨 重要:絵文字の使用ポリシー
スクリプト出力の場合(クロスプラットフォームの安全性)
- スクリプト出力では絵文字を絶対に使用しないでください - すべてのスクリプトで ASCII 互換の文字を使用します
- スクリプトでは次の文字を使用します:
[OK]、[X]、[!]、[*]、[i]、[DIR]、[FILE]、[PKG]、[x] - これにより、Windows GBK などの UTF-8 以外のコンソールとの互換性が確保されます
- 絵文字を追加するためにスクリプト出力を変更しないでください - クロスプラットフォームの互換性が損なわれます
エージェントから人間へのコミュニケーションの場合(推奨)
- 人間に結果を報告するときは絵文字を使用してください - 出力が読みやすくなります
- ユーザーへの最終報告では、次の絵文字を使用してください:
✅(成功)- 完了した操作、成功したスキャン❌(エラー)- 失敗した操作、重大なエラー⚠️(警告)- 警告、対応が必要な問題🔍(スキャン中)- 検索/スキャン操作📊(統計)- 分析結果、統計情報📁(ディレクトリ)- ディレクトリ関連の情報📦(パッケージ)- パッケージ/モジュールの情報🎉(成功)- 正常に完了したことを祝うメッセージ🚨(重大)- 重大な警告💡(ヒント)- 提案、推奨事項📋(リスト)- チェックリスト、概要🔧(ツール)- ツール、ユーティリティ🌐(グローバル)- クロスプラットフォーム、汎用機能🛡️(安全性)- 安全性に関する情報⚡(パフォーマンス)- パフォーマンスの改善📝(ドキュメント)- ドキュメント🎓(学習)- 学習コンテンツ📞(サポート)- ヘルプ、サポート情報📈(成長)- 改善、向上🎯(目標)- 目標、目的🚀(起動)- クイックスタート、高速な操作🛠️(ツール)- ツール関連の機能
例:
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:スキャン結果をキャッシュし、再スキャンを高速化
- ✅ メモリ監視:利用可能なメモリに応じて自動調整
- ✅ 早期停止:ファイル数/時間の上限を設定可能
- ✅ 強化されたキャッシュ検出:キャッシュパスが8か所から26か所以上に増加(225%改善)
🆕 v2.2+ の新機能
- ✅ 重複ファイルの検出:適応型の戦略で重複ファイルを見つけて削除します
- ✅ 増加傾向の分析:ディスク使用量の推移を追跡し、ディスクがいっぱいになる時期を予測します
- ✅ 対話型ウィザード:安全確認を含む、手順に沿ったクリーンアップガイドです
- ✅ ファイルの整理:インテリジェントなファイルのアーカイブと整理(4 つの戦略)
- ✅ スキャン上限の拡大:500K ファイル(従来は 50K)、タイムアウト 120 秒(従来は 30 秒)
- ✅ ディープスキャンモード:無制限にスキャンする
--deep-scan - ✅ Windows ディレクトリのサポート:システムディレクトリをスキャンする
--include-windows
📊 利用可能なスクリプト(全 13 個以上)
コア分析:
- analyze_disk.py - スマートサンプリングによるディスク分析(v2.2 で強化)
- analyze_progressive.py - 大容量ディスク向けの段階的スキャン
- find_duplicates.py - 重複ファイルの検出(v2.2 の新機能)
- 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 メディアのクリーンアップ
macOS で QQ の画像や絵文字が大きな容量を占めており、チャット履歴を
そのまま残す必要がある場合は、scripts/qq_cleanup_macos.zsh を使用します。
-
ファイルを変更せずに QQ のストレージを監査します。
scripts/qq_cleanup_macos.zsh audit -
90 日以上前の画像と絵文字をプレビューします。
scripts/qq_cleanup_macos.zsh clean --older-than-days 90 --categories Pic,Emoji -
プレビューを報告して、明示的な承認を得ます。QQ を終了してから、 承認済みのコマンドに
--executeを付けて再度実行します。
nt_db、アカウントのルート、設定、音声メッセージ、動画、受信ファイルは
絶対に選択しないでください。このスクリプトが受け付けるのは Pic と Emoji のみです。
デフォルトではプレビューを行い、QQ の実行中は実行を拒否します。削除したローカルメディアは、
古い会話から利用できなくなる可能性があることを警告してください。
🚀 マルチエージェントによる高速化(パフォーマンスにとって重要)
🎯 重要なポイント:サブエージェントを使って並列処理する
AI エージェントで使用する場合、これは disk-cleaner の最も強力な機能の 1 つです!
複数のエージェントを使う理由
シングルスレッドでのスキャン:
Agent scans → [Dir1] → [Dir2] → [Dir3] → ... (sequential, slow)
マルチエージェントによる並列スキャン:
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! ⚡
マルチエージェントモードを使うタイミング
✅ 次の場合は必ず使用します:
- 複数のトップレベルディレクトリをスキャンする(例:C:\、D:\、E:\)
- 複数のユーザープロファイルをクリーンアップする
- 大量のファイル(>100K ファイル)を処理する
- 時間が重要な操作を行う
❌ 次の場合は使用しないでください:
- 単一の小さなディレクトリ(<10K ファイル)
- 簡易分析(<30 秒)
- シンプルなクリーンアップタスク
マルチエージェントスキャンの実装方法
オプション 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:マルチプラットフォームのエージェントチーム(上級者向け)
エージェントに対応するシステム(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)
パフォーマンスの比較
| シナリオ | 単一エージェント | 3 個のサブエージェント | 高速化 |
|---|---|---|---|
| 3 台のディスク(各 1TB) | 約 15 分 | 約 5 分 | 3 倍 |
| 10 個のユーザープロファイル | 約 20 分 | 約 4 分 | 5 倍 |
| 100 万ファイル | 約 30 分 | 約 6 分 | 5 倍 |
| キャッシュのクリーンアップ(26 か所) | 約 8 分 | 約 2 分 | 4 倍 |
推奨するエージェント数
- 小規模ジョブ(<50K ファイル):1 個(オーバーヘッドに見合いません)
- 中規模ジョブ(50K~500K ファイル):2~3 個
- 大規模ジョブ(500K~2M ファイル):3~5 個
- 超大規模ジョブ(>2M ファイル):5~8 個
最適な数:3~4 個(速度とオーバーヘッドのバランスが最良です)
ベストプラクティス
- 作業を論理的に分割する:ディスク別、ユーザープロファイル別、ディレクトリの種類別
- パラメーターを統一する:すべてのエージェントで同じスキャン上限を使用する
- 結果を慎重に統合する:重複を除去し、並べ替え、書式を整える
- 障害に適切に対処する:1つのエージェントが失敗しても、ほかのエージェントの処理を続ける
- 進捗を監視する:どのエージェントが完了したかを追跡する
⚠️ IMPORTANT:すべての AI IDE がサブエージェントに対応しているわけではありません。利用できない場合は、並列サブプロセスに切り替えてください。
📚 ドキュメント(必須ファイルのみ)
- SKILL.md - この完全ガイド(最初にお読みください)
- README.md - プロジェクトの概要とクイックスタート
- README_zh.md - 中国語のドキュメント
- CHANGELOG.md - バージョン履歴と変更内容
- AGENT_QUICK_REF.txt - エージェント向け1ページリファレンス
- INSTALL.md - 詳細なインストールガイド
- NO_PYTHON_GUIDE.md - Python をお持ちでないユーザー向けのヘルプ
- references/temp_locations.md - プラットフォーム固有のキャッシュ場所
🎯 エージェント用チェックリスト(必ず従ってください)
あらゆるディスク分析リクエストに対して:
[ ] 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
⚡ 段階的スキャン(大容量ディスクでは重要)
🚨 エージェントは大容量ディスク(>100GB)で必ず使用してください
問題:大容量ディスク(500GB 以上)のフルスキャンには、何時間もかかることがあります。ユーザーは待ちきれなくなります。
解決策:段階的スキャンを使用すれば、何時間もかけずに数秒で結果が得られます!
📋 3 つのスキャンモード
モード 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
}
エージェントの判断ロジック:
# 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)
エージェントでの使用方法:
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
🎯 エージェントの判断フロー(重要 - 必ず従ってください)
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 を実行する ✅ してください:--max-seconds を指定して analyze_progressive.py を使用する
📊 コマンドリファレンスカード
| 状況 | コマンド | 時間 | 結果 |
|---|---|---|---|
| サイズ不明 | --sample | 1s | 推定値 + 推奨 |
| 30 秒未満 | analyze_disk.py | <30s | 完全な結果 |
| 30~120 秒 | --time-limit 60 | 60s | ほとんどの結果 |
| 120 秒超 | analyze_progressive.py --max-seconds 30 | 30s | 部分的な結果 |
| 非常に大容量のディスク | analyze_progressive.py --max-seconds 60 | 60s | より多くの結果 |
🔍 プログレッシブスキャンの仕組み
-
クイックサンプル(1秒)
- 1秒間にできるだけ多くのファイルをスキャンします
- スキャン速度(ファイル数/秒)を計算します
- スキャン全体の所要時間を推定します
- すぐに結果をフィードバックします
-
プログレッシブスキャン(N秒)
- N秒間、連続してスキャンします
- 2秒ごとに進捗を表示します
- スキャンしながら結果を収集します
- 時間切れになると、それまでに見つかった結果を返します
- ユーザーは処理を中断して、途中までの結果を保持できます
-
スマート停止
- 時間またはファイル数の上限に達すると自動的に停止します
- 中断を適切に処理します
- 途中までの結果も役立ちます
🎯 エージェントのベストプラクティス
- 必ず最初に
--sampleを実行します - 必ずモードを選ぶ前にestimated_timeを確認します
- 必ず想定されるスキャン時間をユーザーに伝えます
- 必ず大容量ディスク(2分超)にはプログレッシブモードを使用します
- 絶対にユーザーをフィードバックなしで2分以上待たせないでください
🎯 あらゆる環境で使えるエージェントのワークフロー
このワークフローは、あらゆるプラットフォーム、あらゆるAI IDE、あらゆる場所で動作します。
STEP 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}")
STEP 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}")
STEP 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)
STEP 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)
⚠️ 重要:大容量ディスクにはプログレッシブスキャンを使用してください!
ディスクを分析する前に:
- 最初に
--sampleを実行して、スキャン時間を推定します - 推定時間が2分を超える場合は、プログレッシブモードを使用します
- ユーザーをフィードバックなしで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'])
大容量ディスク向けの推奨ワークフロー:
- まず
--sampleを実行して、所要時間を推定します(1秒) - 推定時間が長すぎる場合は、
--max-secondsまたは--file-limitを使用します - または、リアルタイムでフィードバックを得るために
analyze_progressive.pyを使用します
クロスプラットフォーム対応のPythonコマンド
| プラットフォーム | Pythonコマンド | 確認コマンド |
|---|---|---|
| Windows | python | python --version |
| macOS | python3 | python3 --version |
| Linux | python3 | python3 --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 - エージェントツールとして動作します
- ✅ 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)
⚡ プログレッシブスキャンのチェックリスト(重要)
エージェントは、ディスク分析に関するすべての依頼で、必ず次の手順に従ってください。
[ ] 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
🎓 すべてのエージェントに共通するベストプラクティス
- 必ず最初に Python を確認する - インストール済みだと決めつけない
- Unix では 'python3' を使用する - Windows では 'python' を使用する
- 複数の場所を検索する - インストール先が 1 か所だけだと決めつけない
- タイムアウトを設定して subprocess を使用する - 処理が停止するのを防ぐ
- stdout と stderr の両方を取得する - エラー情報を漏れなく確認する
- clean には --dry-run を優先する - 安全を第一にする
- すべての例外を処理する - 問題が起きても可能な限り動作を続ける
- 役立つエラーメッセージを表示する - 解決方法をユーザーに案内する
🔍 トラブルシューティング(共通)
問題:ある IDE ではスキルが動作するが、別の IDE では動作しない
解決方法:このスキルは IDE に依存しません。次の点を確認してください:
- その IDE から Python にアクセスできる
- スキルパッケージが検索可能な場所にある
- ファイルのアクセス権限によって実行が許可されている
問題:プラットフォームによって動作が異なる
解決方法:このスキルはプラットフォーム間の違いに対応しています。次の点を確認してください:
- Python コマンド(
pythonとpython3のどちらを使うか) - パス区切り文字(pathlib が自動的に処理します)
- ファイルのアクセス権限(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 固有の設定は不要です。プラットフォーム固有のセットアップも不要です。インストールレベルの制限もありません。
展開して、すぐに使用できます!