Continuous Context Cleanup
The core insight from all team feedback is that context pollution accumulates over time as codebases evolve. A one-time cleanup is insufficient; teams need a continuous process to maintain context quality.
Key Principle: Context quality degrades naturally. Without active maintenance, every codebase will eventually become "AI-hostile" as patterns accumulate, frameworks coexist, and documentation becomes stale.
Why Continuous Cleanup Matters
The Continuous Cleanup Cycle
Phase 1: Identify Pollution
Goal: Detect context pollution before it impacts AI effectiveness.
| Signal | How to Detect | Example |
|---|---|---|
| AI uses wrong pattern | Review AI-generated PRs | AI creates DAO instead of Repository |
| AI misses existing components | Track duplicate code generation | AI implements new button instead of using shared component |
| AI chooses deprecated framework | Monitor framework usage in new code | AI uses XML binding instead of Jetpack Compose |
| Inconsistent naming | Code review for naming violations | AI generates deviceId when standard is DeviceKey |
Detection Methods:
Weekly AI Output Review
- Sample 5-10 AI-generated code changes
- Check against project standards
- Document violations for pattern analysis
Search Pollution Audit
bash# Count results for common searches grep -r "api handler" --include="*.go" | wc -l # Should be < modern results grep -r "clean architecture controller" --include="*.go" | wc -lDeveloper Feedback Loop
- Add "AI made wrong choice" option in PR comments
- Track which patterns cause most AI confusion
Phase 2: Document Standards
Goal: Make current standards explicit and discoverable by AI.
CLAUDE.md Template:
# Project Name - AI Guidelines
## Current Standards (Use These)
- **API Layer**: `/internal/restful/` - Clean Architecture controllers
- **Data Access**: `/internal/.../repository/` - Repository pattern
- **State Management**: Pinia composition stores
- **UI Framework**: Jetpack Compose (Android), SwiftUI (iOS)
## Deprecated (DO NOT Use)
- `/internal/openapi/` - Legacy API handlers
- `/pkg/dao/` - Legacy DAO pattern
- Vuex stores with Map objects
- XML binding layouts
## Search Recommendations
| When looking for... | Search for... | NOT... |
|---------------------|---------------|--------|
| API handlers | "controller" + "restful" | "handler" |
| Database access | "repository" | "dao" |
| Device info | "DeviceIdentity" | "deviceId", "mac" |
## Key Conventions
- All new APIs follow RFC 9457 Problem Details
- Use Google Wire for dependency injection
- Repository interfaces in domain layer, implementations in adapter layerDirectory README Template:
# /internal/openapi/ - DEPRECATED
> **Status:** DEPRECATED - Do not add new code here
## Why Deprecated
- Does not follow Clean Architecture principles
- Uses legacy `params.Params` dependency injection
- Mixed concerns (HTTP + business logic + data access)
## What to Use Instead
New API endpoints should go in:
- Controller: `/internal/cleanarchitecture/core/adapter/controller/`
- Router: `/internal/restful/router/vortex/core_router.go`
## Migration Example
See PR #1234 for example migration from OpenAPI to Clean Architecture.
## Timeline
- Bug fixes only: Now
- Read-only mode: Q3 2025
- Removal: Q1 2026Phase 3: Mark Deprecated
Goal: Make deprecated code visible to both AI and humans.
Go Package-Level Deprecation:
// Package openapi contains DEPRECATED legacy API handlers.
//
// Deprecated: Do not add new endpoints here.
// New APIs should be added to /internal/restful/ using Clean Architecture.
// This package is maintained only for backward compatibility with V1 mobile apps.
//
// See /internal/cleanarchitecture/ for the modern pattern.
package openapiJavaScript/TypeScript Deprecation:
/**
* @deprecated Since v2.0 - Use useDeviceStore() from Pinia instead
*
* This Vuex module uses non-serializable Map objects which break
* AI context understanding and DevTools inspection.
*
* Migration guide: docs/migration/vuex-to-pinia.md
* Removal planned: v3.0
*/
export default {
state: {
deviceMap: new Map() // Anti-pattern: non-serializable
}
}Swift Deprecation:
/// Legacy device info fetcher
/// - Warning: Deprecated - Use `DeviceRepository` instead
/// - Note: This class uses direct API calls without proper error handling
@available(*, deprecated, message: "Use DeviceRepository from CleanArchitecture module")
class DeviceInfoFetcher {
// ...
}Kotlin Deprecation:
/**
* Legacy XML-based device list adapter
*
* @deprecated Use [DeviceListComposable] with Jetpack Compose instead.
* XML binding is being phased out - see migration guide at docs/compose-migration.md
*/
@Deprecated(
message = "Use DeviceListComposable instead",
replaceWith = ReplaceWith("DeviceListComposable(devices)")
)
class DeviceListAdapter : RecyclerView.Adapter<DeviceViewHolder>() {
// ...
}Phase 4: Migrate Incrementally
Goal: Move code to modern patterns without big-bang rewrites.
Migration Strategy:
Sprint-Based Migration:
| Sprint | Migration Target | Effort | Validator |
|---|---|---|---|
| Sprint 1 | Document all deprecated areas | 2 days | README files exist |
| Sprint 2 | Add deprecation markers | 1 day | grep shows markers |
| Sprint 3 | Migrate 1 low-risk endpoint | 3 days | Tests pass, AI uses new pattern |
| Sprint 4 | Migrate related endpoints | 5 days | Feature group complete |
| Sprint N | Remove deprecated code | 2 days | No references remain |
Pre-commit Hook for Deprecated Directories:
#!/bin/bash
# .git/hooks/pre-commit
DEPRECATED_DIRS=(
"internal/openapi"
"pkg/dao"
"internal/nonca"
)
for dir in "${DEPRECATED_DIRS[@]}"; do
if git diff --cached --name-only | grep -q "$dir"; then
echo "WARNING: You are modifying deprecated code in $dir"
echo "Consider migrating to modern patterns instead."
echo "See CLAUDE.md for current standards."
read -p "Continue anyway? [y/N] " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
exit 1
fi
fi
donePhase 5: Verify & Monitor
Goal: Ensure cleanup efforts are effective and sustained.
Verification Commands:
# Check deprecated code ratio
echo "Deprecated packages:"
grep -r "Deprecated:" --include="*.go" -l | wc -l
echo "Total packages:"
find . -name "*.go" -type f | xargs dirname | sort -u | wc -l
# Check CLAUDE.md coverage
echo "Projects with CLAUDE.md:"
find . -name "CLAUDE.md" -type f | wc -l
echo "Total project roots:"
find . -name "go.mod" -o -name "package.json" | wc -l
# Search pollution check
echo "Legacy 'handler' results:"
grep -r "func.*Handler" internal/openapi --include="*.go" | wc -l
echo "Modern 'controller' results:"
grep -r "func.*Controller" internal/cleanarchitecture --include="*.go" | wc -lMonthly Audit Checklist:
- [ ] Review AI output accuracy metrics
- [ ] Update deprecated code ratio
- [ ] Check for new undocumented patterns
- [ ] Verify CLAUDE.md reflects current state
- [ ] Sample search pollution rates
- [ ] Review developer feedback on AI confusion
Dashboard Metrics:
| Metric | Target | Current | Trend |
|---|---|---|---|
| AI first-time accuracy | >80% | - | - |
| Deprecated code ratio | <20% | - | - |
| CLAUDE.md coverage | 100% | - | - |
| Search pollution rate | <30% legacy | - | - |
| Avg re-prompts per task | <2 | - | - |
Integration with Development Workflow
During Code Review
## AI Context Cleanup Checklist
- [ ] New patterns documented in CLAUDE.md?
- [ ] Deprecated code marked with appropriate annotations?
- [ ] README updated for modified directories?
- [ ] No new code in deprecated directories without justification?
- [ ] Search terms for new features considered?During Sprint Planning
- Allocate 10-15% of sprint capacity to context cleanup
- Prioritize cleanup of areas causing most AI confusion
- Include "AI usability" as acceptance criteria for new features
During Retrospectives
Add standing question: "What patterns confused AI this sprint?"
- Document specific examples
- Create action items for CLAUDE.md updates
- Track recurring issues
Anti-Patterns to Avoid
1. Big Bang Cleanup
Problem: Attempting to clean up entire codebase at once.
Why It Fails:
- High risk of breaking changes
- Resource-intensive
- Cleanup becomes stale before completion
Instead: Incremental migration with strangler fig pattern.
2. Documentation Without Enforcement
Problem: Writing CLAUDE.md but not verifying compliance.
Why It Fails:
- Documentation drifts from reality
- AI learns wrong patterns from code, ignores docs
- Developers forget to update docs
Instead: Automated verification + pre-commit hooks.
3. Marking Without Migration Path
Problem: Marking code as deprecated without showing alternative.
Why It Fails:
- Developers don't know what to use instead
- AI may still choose deprecated pattern as "best available"
- Creates frustration without progress
Instead: Every deprecation notice includes migration path and example.
4. One-Time Effort
Problem: Treating cleanup as a project with an end date.
Why It Fails:
- New pollution accumulates immediately after "completion"
- Team loses cleanup habits
- Context degrades to original state within months
Instead: Continuous process integrated into regular development workflow.
Quick Start Guide
Week 1: Foundation
- Create CLAUDE.md in project root
- List current vs deprecated patterns
- Add deprecation markers to 3 most confusing packages
Week 2: Awareness
- Add pre-commit hook for deprecated directories
- Share CLAUDE.md location with team
- Start tracking AI confusion incidents
Week 3: Process
- Add AI context checklist to PR template
- Schedule monthly audit
- Pick first migration target
Ongoing
- Update CLAUDE.md as patterns evolve
- Review monthly metrics
- Iterate on process based on results
Related Principles
- C1: Context Engineering Competency - Core principle for context cleanup
Back: Proposals Overview
References
- Claude Code Documentation - Official documentation for CLAUDE.md AI guidance files
- Strangler Fig Pattern - Martin Fowler's description of the incremental migration pattern