Skip to content

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.

SignalHow to DetectExample
AI uses wrong patternReview AI-generated PRsAI creates DAO instead of Repository
AI misses existing componentsTrack duplicate code generationAI implements new button instead of using shared component
AI chooses deprecated frameworkMonitor framework usage in new codeAI uses XML binding instead of Jetpack Compose
Inconsistent namingCode review for naming violationsAI generates deviceId when standard is DeviceKey

Detection Methods:

  1. Weekly AI Output Review

    • Sample 5-10 AI-generated code changes
    • Check against project standards
    • Document violations for pattern analysis
  2. 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 -l
  3. Developer 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:

markdown
# 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 layer

Directory README Template:

markdown
# /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 2026

Phase 3: Mark Deprecated

Goal: Make deprecated code visible to both AI and humans.

Go Package-Level Deprecation:

go
// 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 openapi

JavaScript/TypeScript Deprecation:

javascript
/**
 * @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:

swift
/// 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:

kotlin
/**
 * 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:

SprintMigration TargetEffortValidator
Sprint 1Document all deprecated areas2 daysREADME files exist
Sprint 2Add deprecation markers1 daygrep shows markers
Sprint 3Migrate 1 low-risk endpoint3 daysTests pass, AI uses new pattern
Sprint 4Migrate related endpoints5 daysFeature group complete
Sprint NRemove deprecated code2 daysNo references remain

Pre-commit Hook for Deprecated Directories:

bash
#!/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
done

Phase 5: Verify & Monitor

Goal: Ensure cleanup efforts are effective and sustained.

Verification Commands:

bash
# 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 -l

Monthly 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:

MetricTargetCurrentTrend
AI first-time accuracy>80%--
Deprecated code ratio<20%--
CLAUDE.md coverage100%--
Search pollution rate<30% legacy--
Avg re-prompts per task<2--

Integration with Development Workflow

During Code Review

markdown
## 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

  1. Create CLAUDE.md in project root
  2. List current vs deprecated patterns
  3. Add deprecation markers to 3 most confusing packages

Week 2: Awareness

  1. Add pre-commit hook for deprecated directories
  2. Share CLAUDE.md location with team
  3. Start tracking AI confusion incidents

Week 3: Process

  1. Add AI context checklist to PR template
  2. Schedule monthly audit
  3. Pick first migration target

Ongoing

  1. Update CLAUDE.md as patterns evolve
  2. Review monthly metrics
  3. Iterate on process based on results

Back: Proposals Overview

References