Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Intelligent code cleanup with mainline detection, stale artifact discovery, and safe execution. Supports targeted cleanup and confirmation.
.claude/skills/catlog22-clean/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-07 | ✗→✓ | ▲ Improved | 105% | 0% |
| case-08 | ✗→✓ | ▲ Improved | 53% | 0% |
| case-09 | ✗→✓ | ▲ Improved | 375% | 0% |
| case-10 | ✗→✓ | ▲ Improved | 115% | 0% |
| case-11 | ✗→✓ | ▲ Improved | 237% | 0% |
Evidence-based intelligent cleanup command. Systematically identifies stale artifacts through mainline analysis, discovers drift, and safely removes unused sessions, documents, and dead code.
Core workflow: Detect Mainline → Discover Drift → Confirm → Stage → Execute
Focus area: $FOCUS (or entire project if not specified) Mode: $ARGUMENTS
--dry-run: Preview cleanup without executing--focus: Focus area (module or path)Phase 0: Initialization
├─ Parse arguments (--dry-run, FOCUS)
├─ Setup session folder
└─ Initialize utility functions
Phase 1: Mainline Detection
├─ Analyze git history (30 days)
├─ Identify core modules (high commit frequency)
├─ Map active vs stale branches
└─ Build mainline profile
Phase 2: Drift Discovery (Subagent)
├─ spawn_agent with cli-explore-agent role
├─ Scan workflow sessions for orphaned artifacts
├─ Identify documents drifted from mainline
├─ Detect dead code and unused exports
└─ Generate cleanup manifest
Phase 3: Confirmation
├─ Validate manifest schema
├─ Display cleanup summary by category
├─ request_user_input: Select categories and risk level
└─ Dry-run exit if --dry-run
Phase 4: Execution
├─ Validate paths (security check)
├─ Stage deletion (move to .trash)
├─ Update manifests
├─ Permanent deletion
└─ Report results##### Step 0: Determine Project Root
检测项目根目录,确保 .workflow/ 产物位置正确:
bashPROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
优先通过 git 获取仓库根目录;非 git 项目回退到 pwd 取当前绝对路径。 存储为 {projectRoot},后续所有 .workflow/ 路径必须以此为前缀。
javascriptconst getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString() // Parse arguments const args = "$ARGUMENTS" const isDryRun = args.includes('--dry-run') const focusMatch = args.match(/FOCUS="([^"]+)"/) const focusArea = focusMatch ? focusMatch[1] : "$FOCUS" !== "$" + "FOCUS" ? "$FOCUS" : null // Session setup const dateStr = getUtc8ISOString().substring(0, 10) const sessionId = `clean-${dateStr}` const sessionFolder = `${projectRoot}/.workflow/.clean/${sessionId}` const trashFolder = `${sessionFolder}/.trash` const projectRoot = bash('git rev-parse --show-toplevel 2>/dev/null || pwd').trim() bash(`mkdir -p ${sessionFolder}`) bash(`mkdir -p ${trashFolder}`) // Utility functions function fileExists(p) { try { return bash(`test -f "${p}" && echo "yes"`).includes('yes') } catch { return false } } function dirExists(p) { try { return bash(`test -d "${p}" && echo "yes"`).includes('yes') } catch { return false } } function validatePath(targetPath) { if (targetPath.includes('..')) return { valid: false, reason: 'Path traversal' } const allowed = ['.workflow/', '.claude/rules/tech/', 'src/'] const dangerous = [/^\//, /^C:\\Windows/i, /node_modules/, /\.git$/] if (!allowed.some(p => targetPath.startsWith(p))) { return { valid: false, reason: 'Outside allowed directories' } } if (dangerous.some(p => p.test(targetPath))) { return { valid: false, reason: 'Dangerous pattern' } } return { valid: true } }
javascript// Check git repository const isGitRepo = bash('git rev-parse --git-dir 2>/dev/null && echo "yes"').includes('yes') let mainlineProfile = { coreModules: [], activeFiles: [], activeBranches: [], staleThreshold: { sessions: 7, branches: 30, documents: 14 }, isGitRepo, timestamp: getUtc8ISOString() } if (isGitRepo) { // Commit frequency by directory (last 30 days) const freq = bash('git log --since="30 days ago" --name-only --pretty=format: | grep -v "^$" | cut -d/ -f1-2 | sort | uniq -c | sort -rn | head -20') // Parse core modules (>5 commits) mainlineProfile.coreModules = freq.trim().split('\n') .map(l => l.trim().match(/^(\d+)\s+(.+)$/)) .filter(m => m && parseInt(m[1]) >= 5) .map(m => m[2]) // Recent branches const branches = bash('git for-each-ref --sort=-committerdate refs/heads/ --format="%(refname:short)" | head -10') mainlineProfile.activeBranches = branches.trim().split('\n').filter(Boolean) } Write(`${sessionFolder}/mainline-profile.json`, JSON.stringify(mainlineProfile, null, 2))
javascriptlet exploreAgent = null try { // Launch cli-explore-agent exploreAgent = spawn_agent({ agent_type: "cli_explore_agent", message: ` ## TASK ASSIGNMENT ### MANDATORY FIRST STEPS 1. Read: ${projectRoot}/.workflow/project-tech.json (if exists) ## Task Objective Discover stale artifacts for cleanup. ## Context - Session: ${sessionFolder} - Focus: ${focusArea || 'entire project'} ## Discovery Categories ### 1. Stale Workflow Sessions Scan: ${projectRoot}/.workflow/active/WFS-*, ${projectRoot}/.workflow/archives/WFS-*, ${projectRoot}/.workflow/.lite-plan/*, ${projectRoot}/.workflow/.debug/DBG-* Criteria: No modification >7 days + no related git commits ### 2. Drifted Documents Scan: .claude/rules/tech/*, ${projectRoot}/.workflow/.scratchpad/* Criteria: >30% broken references to non-existent files ### 3. Dead Code Scan: Unused exports, orphan files (not imported anywhere) Criteria: No importers in import graph ## Output Write to: ${sessionFolder}/cleanup-manifest.json Format: { "generated_at": "ISO", "discoveries": { "stale_sessions": [{ "path": "...", "age_days": N, "reason": "...", "risk": "low|medium|high" }], "drifted_documents": [{ "path": "...", "drift_percentage": N, "reason": "...", "risk": "..." }], "dead_code": [{ "path": "...", "type": "orphan_file", "reason": "...", "risk": "..." }] }, "summary": { "total_items": N, "by_category": {...}, "by_risk": {...} } } ` }) // Wait with timeout handling (4-step cascade) let result = wait_agent({ timeout_ms: 1800000 }) if (result.timed_out) { // Status probe followup_task({ target: exploreAgent, message: "STATUS_CHECK: Report current progress, findings so far, and estimated remaining work." }) const status = wait_agent({ timeout_ms: 180000 }) // 3 min if (status.timed_out) { // Force finalize followup_task({ target: exploreAgent, message: "FINALIZE: Output all current findings immediately. Time limit reached.", interrupt: true }) const forced = wait_agent({ timeout_ms: 180000 }) // 3 min if (forced.timed_out) { close_agent({ target: exploreAgent }) throw new Error('Agent timeout') } } } if (!fileExists(`${sessionFolder}/cleanup-manifest.json`)) { throw new Error('Manifest not generated') } } finally { if (exploreAgent) close_agent({ target: exploreAgent }) }
javascript// Load and validate manifest const manifest = JSON.parse(Read(`${sessionFolder}/cleanup-manifest.json`)) // Display summary console.log(` ## Cleanup Discovery Report | Category | Count | Risk | |----------|-------|------| | Sessions | ${manifest.summary.by_category.stale_sessions} | ${getRiskSummary('sessions')} | | Documents | ${manifest.summary.by_category.drifted_documents} | ${getRiskSummary('documents')} | | Dead Code | ${manifest.summary.by_category.dead_code} | ${getRiskSummary('code')} | **Total**: ${manifest.summary.total_items} items `) // Dry-run exit if (isDryRun) { console.log(` **Dry-run mode**: No changes made. Manifest: ${sessionFolder}/cleanup-manifest.json `) return } // User confirmation const selection = functions.request_user_input({ questions: [ { header: "清理类别", id: "categories", question: "Which categories to clean?", options: [ { label: "Sessions", description: `${manifest.summary.by_category.stale_sessions} stale sessions` }, { label: "Documents", description: `${manifest.summary.by_category.drifted_documents} drifted docs` }, { label: "Dead Code", description: `${manifest.summary.by_category.dead_code} unused files` } ] }, { header: "风险级别", id: "risk", question: "Risk level?", options: [ { label: "Low only(Recommended)", description: "Safest — only clearly stale items" }, { label: "Low + Medium", description: "Includes likely unused" }, { label: "All", description: "Aggressive" } ] } ] }) // BLOCKS (wait for user response)
javascriptconst selectedCategory = selection.answers.categories.answers[0] const selectedRisk = selection.answers.risk.answers[0] const riskFilter = { 'Low only(Recommended)': ['low'], 'Low + Medium': ['low', 'medium'], 'All': ['low', 'medium', 'high'] }[selectedRisk] // Collect items to clean const items = [] if (selectedCategory === 'Sessions') { items.push(...manifest.discoveries.stale_sessions.filter(s => riskFilter.includes(s.risk))) } if (selectedCategory === 'Documents') { items.push(...manifest.discoveries.drifted_documents.filter(d => riskFilter.includes(d.risk))) } if (selectedCategory === 'Dead Code') { items.push(...manifest.discoveries.dead_code.filter(c => riskFilter.includes(c.risk))) } const results = { staged: [], deleted: [], failed: [], skipped: [] } // Validate and stage for (const item of items) { const validation = validatePath(item.path) if (!validation.valid) { results.skipped.push({ path: item.path, reason: validation.reason }) continue } if (!fileExists(item.path) && !dirExists(item.path)) { results.skipped.push({ path: item.path, reason: 'Not found' }) continue } try { const trashTarget = `${trashFolder}/${item.path.replace(/\//g, '_')}` bash(`mv "${item.path}" "${trashTarget}"`) results.staged.push({ path: item.path, trashPath: trashTarget }) } catch (e) { results.failed.push({ path: item.path, error: e.message }) } } // Permanent deletion for (const staged of results.staged) { try { bash(`rm -rf "${staged.trashPath}"`) results.deleted.push(staged.path) } catch (e) { console.error(`Failed: ${staged.path}`) } } // Cleanup empty trash bash(`rmdir "${trashFolder}" 2>/dev/null || true`) // Report console.log(` ## Cleanup Complete **Deleted**: ${results.deleted.length} **Failed**: ${results.failed.length} **Skipped**: ${results.skipped.length} ### Deleted ${results.deleted.map(p => `- ${p}`).join('\n') || '(none)'} ${results.failed.length > 0 ? `### Failed\n${results.failed.map(f => `- ${f.path}: ${f.error}`).join('\n')}` : ''} Report: ${sessionFolder}/cleanup-report.json `) Write(`${sessionFolder}/cleanup-report.json`, JSON.stringify({ timestamp: getUtc8ISOString(), results, summary: { deleted: results.deleted.length, failed: results.failed.length, skipped: results.skipped.length } }, null, 2))
{projectRoot}/.workflow/.clean/clean-{YYYY-MM-DD}/
├── mainline-profile.json # Git history analysis
├── cleanup-manifest.json # Discovery results
├── cleanup-report.json # Execution results
└── .trash/ # Staging area (temporary)| Risk | Description | Examples | |------|-------------|----------| | Low | Safe to delete | Empty sessions, scratchpad files | | Medium | Likely unused | Orphan files, old archives | | High | May have dependencies | Files with some imports |
| Feature | Protection | |---------|------------| | Path Validation | Whitelist directories, reject traversal | | Staged Deletion | Move to .trash before permanent delete | | Dangerous Patterns | Block system dirs, node_modules, .git |
First Call (/prompts:clean):
├─ Detect mainline from git history
├─ Discover stale artifacts via subagent
├─ Display summary, await user selection
└─ Execute cleanup with staging
Dry-Run (/prompts:clean --dry-run):
├─ All phases except execution
└─ Manifest saved for review
Focused (/prompts:clean FOCUS="auth"):
└─ Discovery limited to specified area| Situation | Action | |-----------|--------| | No git repo | Use file timestamps only | | Agent timeout | Retry once with prompt, then abort | | Path validation fail | Skip item, report reason | | Manifest parse error | Abort with error | | Empty discovery | Report "codebase is clean" |
Now execute cleanup workflow with focus: $FOCUS
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→fail | 14,616 | 29,233 | +100% | 1 | 1 | 0% | 2,613 | 4,462 | +71% | 0 | 0 | — |
case-02 | fail→fail | 10,768 | 5,245 | -51% | 1 | 1 | 0% | 1,941 | 3,905 | +101% | 0 | 0 | — |
case-22 | fail→fail | 5,834 | 5,749 | -1% | 1 | 1 | 0% | 1,046 | 3,870 | +270% | 0 | 0 | — |
case-03 | fail→fail | 9,050 | 10,052 | +11% | 1 | 1 | 0% | 1,425 | 4,352 | +205% | 0 | 0 | — |
case-04 | fail→fail | 12,773 | 6,492 | -49% | 1 | 1 | 0% | 2,238 | 4,003 | +79% | 0 | 0 | — |
case-05 | fail→fail | 9,637 | 5,940 | -38% | 1 | 1 | 0% | 1,680 | 4,670 | +178% | 0 | 0 | — |
case-06 | fail→fail | 16,072 | 9,840 | -39% | 1 | 1 | 0% | 2,643 | 5,354 | +103% | 0 | 0 | — |
case-16 | fail→fail | 20,350 | 2,251 | -89% | 1 | 1 | 0% | 1,323 | 3,858 | +192% | 0 | 0 | — |
case-07 | fail→pass | 12,534 | 3,195 | -75% | 1 | 1 | 0% | 1,981 | 4,064 | +105% | 0 | 0 | — |
case-08 | fail→pass | 16,525 | 3,779 | -77% | 1 | 1 | 0% | 2,811 | 4,305 | +53% | 0 | 0 | — |
case-09 | fail→pass | 5,427 | 2,861 | -47% | 1 | 1 | 0% | 855 | 4,058 | +375% | 0 | 0 | — |
case-10 | fail→pass | 10,927 | 1,735 | -84% | 1 | 1 | 0% | 1,777 | 3,827 | +115% | 0 | 0 | — |
case-11 | fail→pass | 7,982 | 3,501 | -56% | 1 | 1 | 0% | 1,300 | 4,387 | +237% | 0 | 0 | — |
case-12 | fail→pass | 11,389 | 3,101 | -73% | 1 | 1 | 0% | 2,029 | 4,077 | +101% | 0 | 0 | — |
case-13 | pass→pass | 11,615 | 1,935 | -83% | 1 | 1 | 0% | 1,881 | 3,919 | +108% | 0 | 0 | — |
case-14 | fail→pass | 10,321 | 5,539 | -46% | 1 | 1 | 0% | 1,606 | 4,150 | +158% | 0 | 0 | — |
case-15 | pass→pass | 5,052 | 2,528 | -50% | 1 | 1 | 0% | 633 | 4,003 | +532% | 0 | 0 | — |
case-17 | fail→pass | 16,279 | 6,427 | -61% | 1 | 1 | 0% | 2,568 | 4,879 | +90% | 0 | 0 | — |
case-18 | pass→pass | 11,453 | 4,010 | -65% | 1 | 1 | 0% | 1,944 | 4,280 | +120% | 0 | 0 | — |
case-19 | pass→pass | 9,398 | 3,398 | -64% | 1 | 1 | 0% | 1,604 | 4,383 | +173% | 0 | 0 | — |
case-20 | pass→fail | 6,722 | 6,463 | -4% | 1 | 1 | 0% | 1,198 | 3,897 | +225% | 0 | 0 | — |
case-21 | fail→fail | 6,087 | 5,788 | -5% | 1 | 1 | 0% | 1,045 | 3,862 | +270% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted, and 15 counted toward the lift figure. The other 7 produced results that are not comparable between the two arms, so they are excluded from the headline rather than averaged into it. The headline lift of +32 percentage points is the difference between those two pass rates over the 15 comparable cases. 6 cases got worse with the skill loaded, and they are included in that figure.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.