---
roadcrew_template_name: "code-cleanup.md"
roadcrew_template_type: "command"
roadcrew_template_version: "v1.0"
roadcrew_last_updated: "2025-10-25"
roadcrew_min_version: "1.5.0"
roadcrew_license: "See LICENSE file in .roadcrew folder"
roadcrew_copyright: "Copyright (c) 2025 North Star Holdings, LLC"
spdx_license_identifier: "LicenseRef-RoadcrewLicense-1.0"
execution_mode: "auto-execute"
---

# code-cleanup

Clean up code by removing debug statements, obsolete comments, unused variables, and dead code.

> **Execution:** Runs immediately with automatic cleanup suggestions. No approval needed for each fix.

**Cost Optimization:** Uses script-first approach for identifying issues before generating fixes.

## Purpose
Systematically remove old code, files, and implementations after confirming new replacements work. Prevents accumulation of dead code, reduces confusion, and keeps codebase clean.

## Activation
User says: "code cleanup" or "clean up old code" or after confirming new implementation works

## Philosophy
**"Delete with confidence, not with hesitation."**

Once new code is verified working, old code should be removed immediately. Keeping both creates:
- Confusion about which version to use
- Maintenance burden (updating both paths)
- Code bloat
- Risk of accidentally using old path

## Analysis Framework

### 1. Identify Cleanup Candidates

After creating/optimizing something new, ask:

**Files:**
- [ ] Are there old files that are now obsolete?
- [ ] Are there temporary/backup files left over?
- [ ] Are there duplicates with different names?

**Functions:**
- [ ] Are there deprecated functions/aliases?
- [ ] Are there old implementations replaced by new ones?
- [ ] Are there "v1" functions alongside "v2" functions?

**Configuration:**
- [ ] Are there unused environment variables?
- [ ] Are there old config files no longer read?
- [ ] Are there stale comments referencing old approaches?

**Documentation:**
- [ ] Are there instructions for old processes?
- [ ] Are there links to deleted files?
- [ ] Are there comments explaining workarounds no longer needed?

### 2. Verify Before Deleting

**Never delete without confirmation:**
```
✅ GOOD:
  User: "The new version works!"
  AI: *Immediately deletes old version*

❌ BAD:
  AI: *Deletes old version*
  User: "Wait, I haven't tested yet!"
```

**Confirmation Checklist:**
- User explicitly states new version works
- User has tested the new approach
- No errors in the new implementation
- User is ready to move forward

### 3. What to Clean Up

#### Category A: Immediate Cleanup (Same Session)

**Old implementations replaced inline:**
```javascript
// OLD (delete immediately after new version works):
function setupTaxBuddy() {
  return createWorkingFolder();
}

// NEW:
function createWorkingFolder() {
  // actual implementation
}
```

**Temporary helper files:**
```bash
# These should be deleted as soon as their purpose is fulfilled:
configure-from-env.sh  # Replaced by integrated deploy.sh
auto-configure-api-keys.sh  # Replaced by setup-api-keys.sh
*.backup  # After confirming restore not needed
```

**Dead code paths:**
```javascript
// OLD approach (delete immediately):
if (useOldMethod) {
  // old implementation
}

// NEW approach (keep):
if (useNewMethod) {
  // new implementation
}
```

#### Category B: Delayed Cleanup (Next Session)

**Backwards compatibility (only if external users exist):**
```javascript
// Keep for 1 major version if there are external dependencies:
/**
 * @deprecated Use newFunction() instead
 * Will be removed in v2.0.0
 */
function oldFunction() {
  console.warn('oldFunction is deprecated');
  return newFunction();
}
```

**Migration paths (only if data/state exists):**
```javascript
// Keep if users might have old data:
function migrateOldConfigToNew() {
  // One-time migration
}
```

#### Category C: Never Delete

**Working code with no replacement:**
- If it still serves a purpose, keep it

**Code required by external systems:**
- If other projects depend on it, keep (with deprecation notice)

**Historical reference (rarely):**
- If there's a complex algorithm that took weeks to develop, add comment explaining why new approach is better, then delete

### 4. Cleanup Patterns

#### Pattern 1: File Renaming/Replacement

```bash
# When renaming/replacing files:

BEFORE CLEANUP:
  2-setup.gs           # old name
  2-create-workspace.gs  # new name (both exist!)

AFTER CLEANUP (once confirmed working):
  2-create-workspace.gs  # only new name
  
# Update all references immediately:
  - Documentation
  - Import statements  
  - README
  - Comments
```

**From this conversation:**
- Renamed `2-setup.gs` → `2-create-workspace.gs`
- Renamed `4,5,6-*.gs` → `3,4,5-*.gs`
- Updated all references in same commit
- Old files deleted immediately via `git mv`

#### Pattern 2: Function Consolidation

```javascript
// BEFORE CLEANUP:
function setupTaxBuddy() {  // old
  return createWorkingFolder();
}
function createWorkingFolder() {  // new
  // implementation
}

// AFTER CLEANUP (once user confirms working):
function createWorkingFolder() {  // only this exists
  // implementation
}
```

**From this conversation:**
- User: "why do we need both setupTaxBuddy and createWorkingFolder?"
- AI: Immediately removed `setupTaxBuddy()` since no external users
- Cleaned up README references in same commit

#### Pattern 3: Approach Migration

```javascript
// BEFORE CLEANUP (when trying new approach):
// Option 1: clasp run (not working)
if (claspRunAvailable()) {
  clasp run autoConfigureFromDeployment()
}

// Option 2: generate function and user runs manually (working!)
generateSetupFunction()
userRunsManually()

// AFTER CLEANUP (once Option 2 confirmed):
// Only keep working approach:
generateSetupFunction()
userRunsManually()

// Delete all references to Option 1:
// - Remove clasp run code
// - Remove fallback logic
// - Remove Option 1 documentation
```

**From this conversation:**
- Tried: `clasp run` for automatic configuration (failed - "not API executable")
- New approach: Generate function with embedded keys, user runs once
- Cleaned up: Removed all `clasp run` error handling once new approach worked
- Removed `2>/dev/null` that was hiding errors

#### Pattern 4: Script Consolidation

```bash
# BEFORE CLEANUP (multiple scripts doing similar things):
configure-from-env.sh       # Attempt 1
auto-configure-api-keys.sh  # Attempt 2  
setup-api-keys.sh           # Final working version

# AFTER CLEANUP (keep only what works):
setup-api-keys.sh           # Only this
```

**From this conversation:**
- Created multiple attempts at automatic API configuration
- Settled on `setup-api-keys.sh` as the working solution
- Deleted `configure-from-env.sh` and `auto-configure-api-keys.sh` immediately
- Removed from git in same commit

### 5. Cleanup Workflow

```
┌─────────────────────────────────────┐
│ 1. CREATE NEW IMPLEMENTATION        │
└─────────────────────────────────────┘
              ↓
┌─────────────────────────────────────┐
│ 2. WAIT FOR USER CONFIRMATION       │
│    "The new version works!"         │
└─────────────────────────────────────┘
              ↓
┌─────────────────────────────────────┐
│ 3. IMMEDIATE CLEANUP                │
│    • Delete old files               │
│    • Remove old functions           │
│    • Update all references          │
│    • Clean documentation            │
└─────────────────────────────────────┘
              ↓
┌─────────────────────────────────────┐
│ 4. COMMIT & PUSH                    │
│    Single commit with:              │
│    - New implementation             │
│    - Cleanup of old                 │
│    - Updated references             │
└─────────────────────────────────────┘
```

### 6. Red Flags (Anti-Patterns)

❌ **Keeping "just in case"**
- If new version works, old version is dead weight
- Git history preserves everything if needed

❌ **Commenting out instead of deleting**
```javascript
// BAD:
// function oldWay() {
//   // hundreds of lines of commented code
// }

// GOOD:
// Removed oldWay() - see commit abc123 if needed
```

❌ **"TODO: Clean this up later"**
- "Later" never comes
- Clean up immediately while context is fresh

❌ **Leaving backwards compatibility indefinitely**
- Unless there are external users, remove immediately
- If external users exist, set removal date

❌ **Updating only some references**
- If renaming, update ALL references in single commit
- Don't leave breadcrumbs to old names

❌ **Deleting without updating docs**
- Documentation must reflect current reality
- Stale docs are worse than no docs

### 7. Implementation Checklist

When user confirms new code works:

**Files:**
- [ ] Delete old/replaced files
- [ ] Delete temporary helper files
- [ ] Delete backup files (*.backup, *.old)
- [ ] Remove unused config files

**Code:**
- [ ] Remove deprecated functions
- [ ] Remove backwards compatibility aliases
- [ ] Remove commented-out old implementations
- [ ] Remove unused imports/dependencies

**References:**
- [ ] Update all function calls
- [ ] Update all file paths
- [ ] Update import statements
- [ ] Update configuration references

**Documentation:**
- [ ] Update README with new approach
- [ ] Update inline comments
- [ ] Remove instructions for old approach
- [ ] Update architecture diagrams

**Git:**
- [ ] Single commit with all cleanup
- [ ] Clear commit message explaining what was removed and why
- [ ] Immediate push (don't let cleanup pile up)

### 8. Cleanup Communication

**Always tell user what you're cleaning up:**

```
✅ GOOD:
"Perfect! Since the new approach works, I'm cleaning up:
 - Removing setupTaxBuddy() alias (replaced by createWorkingFolder())
 - Deleting configure-from-env.sh (integrated into deploy.sh)
 - Updating all references in README and deploy.sh"

❌ BAD:
*Silently deletes things*
User: "Wait, where did X go?"
```

### 9. Special Cases

**When NOT to cleanup immediately:**

1. **User hasn't tested yet:**
   - Wait for explicit confirmation
   - "Works on my machine" ≠ "Ready to delete old version"

2. **Breaking change for external users:**
   - Add deprecation notice
   - Set removal timeline
   - Document migration path

3. **Complex migration required:**
   - Provide migration script
   - Keep old version until migration complete
   - Then cleanup both old version + migration script

4. **Regulatory/compliance reasons:**
   - Some code must be preserved for audit
   - Comment clearly why it's kept
   - Move to archive directory

### 10. Success Metrics

**Clean Codebase Indicators:**
- No commented-out code blocks
- No "TODO: cleanup" comments
- No files with ".old" or ".backup" extensions
- No deprecated functions without removal date
- No duplicate implementations of same feature
- Documentation matches current code

**From this conversation (examples):**
✅ Removed `setupTaxBuddy()` immediately after confirmation
✅ Deleted `configure-from-env.sh` and `auto-configure-api-keys.sh` 
✅ Removed `2>/dev/null` that was hiding errors
✅ Cleaned up `0-ui-handlers.gs` when approach changed
✅ Removed backwards compatibility when no external users
✅ Updated all references in same commit as deletion

## Example Usage

```
User: "The new createWorkingFolder() function works perfectly!"

AI: *Executes code-cleanup command*
    "Great! Cleaning up now:
     1. Removing old setupTaxBuddy() alias
     2. Updating README to only mention createWorkingFolder()
     3. Committing cleanup"
    
    *Deletes old code, updates docs, commits, pushes*
    "✅ Cleanup complete!"
```

## Integration with Development Flow

```
User requests feature/optimization
         ↓
AI implements new approach
         ↓
User tests new approach
         ↓
User confirms: "It works!" ← TRIGGER
         ↓
AI executes code-cleanup ← THIS COMMAND
         ↓
Clean, modern codebase
```

## Remember

**"A clean codebase is a maintainable codebase."**

- Delete aggressively (Git remembers everything)
- Update comprehensively (all references at once)
- Document briefly (why it was removed)
- Move forward confidently (don't look back)