Files
claude-plugins/claude-code/skills/claude-memory/patterns.md
2025-10-28 12:28:48 -05:00

11 KiB
Raw Blame History

Memory Optimization Patterns

Advanced techniques for token-efficient memory management.

Pattern 1: Core + Imports Architecture

Strategy: Keep main CLAUDE.md minimal, import details on demand.

Structure

project/
├── CLAUDE.md (100 lines - core)
├── docs/
│   ├── tech-stack.md
│   ├── architecture.md
│   ├── style-guide.md
│   └── api-reference.md

CLAUDE.md (Core - Always Loaded)

# MyProject

Quick reference for AI coding assistant.

## Tech Stack
- Backend: Node.js + Express + PostgreSQL
- Frontend: React + TypeScript + Tailwind
- Details: @docs/tech-stack.md

## Common Commands
```bash
npm run dev      # Start dev server
npm test         # Run tests
npm run build    # Production build

Coding Standards

  • 2-space indentation
  • ESLint + Prettier
  • Full details: @docs/style-guide.md

Architecture

  • Microservices pattern
  • See @docs/architecture.md

IMPORTANT Rules

  • YOU MUST run tests before commits
  • Never commit secrets
  • Update API docs with endpoint changes

**Token Cost**: ~400 tokens (loaded every conversation)

### docs/tech-stack.md (Detailed - Loaded on Demand)

```markdown
# Technology Stack

## Backend
- Node.js 20 LTS
- Express 4.18
- PostgreSQL 15
- Sequelize ORM
- Redis for caching
- JWT authentication
- bcrypt for passwords

[Extensive details, dependencies, versions, configuration...]

Token Cost: ~1500 tokens (loaded only when discussing tech stack)

Benefits

  • Main memory stays lean: 100 lines vs 500+
  • Details loaded contextually: Only when needed
  • Easy to update: Each doc has single focus
  • Team ownership: Different people can own different docs

Pattern 2: Subfolder Specialization

Strategy: Use subfolder memory for context-specific guidance.

Directory Structure

myproject/
├── CLAUDE.md                # Root - shared context
├── frontend/
│   ├── CLAUDE.md           # Frontend-specific
│   └── src/
├── backend/
│   ├── CLAUDE.md           # Backend-specific
│   └── src/
└── docs/
    ├── architecture.md
    └── conventions.md

Root CLAUDE.md

# MyProject

Microservices e-commerce platform.

## Common Across All Areas
- Git workflow: feature branches + PRs
- Testing required before merge
- See @docs/architecture.md

## Subprojects
- `frontend/` - React app (see frontend/CLAUDE.md)
- `backend/` - API server (see backend/CLAUDE.md)

frontend/CLAUDE.md (Loaded When Working in frontend/)

# Frontend Context

- React 18 + TypeScript strict mode
- Component structure: Atomic Design
- Styling: Tailwind utility-first
- State: Redux Toolkit

## Component Patterns
@../docs/ui-patterns.md

## Testing
- Jest + React Testing Library
- Coverage > 80%
- Test user interactions, not implementation

backend/CLAUDE.md (Loaded When Working in backend/)

# Backend Context

- Express + TypeScript
- Database: PostgreSQL + Sequelize
- Auth: JWT + refresh tokens
- Caching: Redis

## API Patterns
@../docs/api-patterns.md

## Security
- All endpoints have rate limiting
- Input validation with Zod
- SQL injection protection via ORM

When to Use

  • Large monorepos
  • Different tech stacks per area
  • Team specialization (frontend/backend teams)
  • Different conventions per module

Pattern 3: User + Project Separation

Strategy: Personal preferences globally, project specifics locally.

~/.claude/CLAUDE.md (Personal - All Projects)

# Personal Defaults

## Communication Style
- Explain decisions before acting
- Ask before destructive operations
- Show diffs for large changes

## Code Preferences
- Prefer functional programming
- Avoid premature optimization
- Comprehensive error handling

## Tools
- Git commit format: Conventional Commits
- Prefer `npm` over `yarn`

Applies To: Every project you work on

./CLAUDE.md (Project - Overrides Personal)

# ProjectX

IMPORTANT: This legacy project uses OOP extensively (override FP preference).

Tech stack:
- Java Spring Boot
- MySQL
- jQuery (legacy frontend)

Common commands:
```bash
mvn clean install
mvn test

Conventions:

  • CamelCase for classes
  • snake_case for database

**Applies To**: Only this project, overrides personal preferences

### Benefits

- Consistent personal style across all projects
- Project-specific overrides when needed
- Easy onboarding to new projects
- Maintain personal workflow preferences

---

## Pattern 4: Team Collaboration

**Strategy**: Shared standards in git, personal overrides local.

### Setup

```bash
# Version control
.claude/CLAUDE.md              # Team standards (in git)
.claude/settings.json          # Team settings (in git)

# Local overrides
.claude/CLAUDE.local.md        # Personal (gitignored)
.claude/settings.local.json    # Personal (gitignored)

.gitignore

# Personal overrides only
.claude/CLAUDE.local.md
.claude/settings.local.json

# Team files are tracked
# .claude/CLAUDE.md
# .claude/settings.json

.claude/CLAUDE.md (Team - In Git)

# Team Standards

IMPORTANT: All team members should follow these conventions.

## Git Workflow
1. Create feature branch: `feature/description`
2. PR to `develop` (not `main`)
3. 2 approvals required
4. Squash merge

## Code Review Checklist
- Tests pass locally
- Coverage > 80%
- No linter warnings
- Documentation updated

## Architecture Decisions
@docs/adr/  # Architecture Decision Records

## NEVER
- Commit directly to `main`
- Merge without tests passing
- Hardcode credentials

.claude/CLAUDE.local.md (Personal - Gitignored)

# My Personal Overrides

## Development Preferences
- Use Neovim for editing
- Prefer verbose logging during dev
- Run tests in watch mode

[Preferences that don't affect team]

Benefits

  • Consistent team standards
  • Personal customization allowed
  • Version-controlled team rules
  • Built-in onboarding documentation

Token Management Strategies

Strategy 1: Measure Current Usage

# Estimate tokens (rough: chars ÷ 4)
wc -c CLAUDE.md | awk '{print $1/4}'
# Goal: < 5000 tokens (<20KB file)

# Count lines
wc -l CLAUDE.md
# Goal: 100-200 lines

# Find verbose sections (lines >100 chars)
grep -n "." CLAUDE.md | awk -F: 'length($2) > 100 {print NR": "$0}'

Strategy 2: Lean Writing Techniques

Before (150 tokens)

The application uses a microservices architecture where each service is
independently deployable and scalable. The services communicate via REST
APIs and message queues. This allows for better separation of concerns
and makes it easier to maintain and scale individual components.

After (30 tokens)

Architecture: Microservices (REST + message queues)
- Independent deployment/scaling
- See @docs/architecture.md

Reduction: 80%

Compression Techniques

  1. Bullet Points > Paragraphs

    • Lists are 50% more token-efficient
    • Easier to scan
  2. Commands > Explanations

    • Show npm test instead of describing testing process
    • Code is self-documenting
  3. Imports > Embedding

    • @docs/api.md costs 5 tokens
    • Embedding API docs costs 2000 tokens
  4. Examples > Theory

    • One example worth 100 words
    • Concrete beats abstract

Strategy 3: Strategic Importing

# Decision Tree

Is this info needed in 80%+ of sessions?
  → YES: Keep in CLAUDE.md

Is this info needed occasionally?
  → YES: Put in @docs/, reference from CLAUDE.md

Is this info needed rarely?
  → NO: Don't include, use web search or direct file read

Example

# CLAUDE.md (Always Loaded - ~400 tokens)
Core commands, key conventions, critical rules

# @docs/architecture.md (On Demand - ~1500 tokens)
Loaded only when discussing architecture

# @docs/api-reference.md (On Demand - ~2000 tokens)
Loaded only when working on APIs

# @docs/testing-guide.md (On Demand - ~800 tokens)
Loaded only when writing tests

# @docs/deployment.md (On Demand - ~600 tokens)
Loaded only when deploying

Total: 400 tokens/conversation instead of 5300 tokens Savings: 92%

Strategy 4: Regular Cleanup

Monthly review checklist:

# 1. Find outdated content
grep -i "deprecated\|old\|legacy\|TODO" CLAUDE.md

# 2. Check for redundant sections
# Look for repeated information

# 3. Identify candidates for @imports
# Sections >50 lines that aren't always needed

# 4. Verify all rules are current
# Test: does Claude follow each rule?

# 5. Measure improvement
# Before: X lines
# After: Y lines
# Reduction: Z%

Advanced Patterns

Dynamic Context Loading

# CLAUDE.md

## Context Selection

When working on:
- **Frontend**: Read @frontend/CLAUDE.md
- **Backend**: Read @backend/CLAUDE.md
- **DevOps**: Read @docs/devops.md
- **Testing**: Read @docs/testing.md
- **Documentation**: Read @docs/writing-guide.md

Ask yourself: "What am I working on?" and load that context.

Versioned Standards

# CLAUDE.md

## Current Standards

API Version: v2
See @docs/api-v2.md

## Migration Guides

Upgrading from v1? See @docs/migration-v1-to-v2.md

## Deprecated

v1 API (deprecated, remove by Q1 2024)
Historical reference: @docs/api-v1-deprecated.md

Role-Based Memory

# CLAUDE.md

## Available Roles

You can act as different roles depending on the task:

- **Full-Stack Developer**: @docs/role-fullstack.md
- **Frontend Specialist**: @docs/role-frontend.md
- **Backend Specialist**: @docs/role-backend.md
- **DevOps Engineer**: @docs/role-devops.md
- **QA Engineer**: @docs/role-qa.md

Switch roles: "Act as [role name]"

Conditional Instructions

# CLAUDE.md

## Environment-Aware Behavior

### Development Environment
- Verbose logging OK
- Use local DB (localhost:5432)
- Mock external APIs

### Staging Environment
- Moderate logging
- Use staging DB
- Real external APIs (test keys)

### Production Environment
- Minimal logging
- Use RDS
- NEVER commit with console.log
- ALWAYS check deployment checklist

Performance Optimization

Before Optimization

# CLAUDE.md (1000 lines, 4000 tokens)
[Everything embedded]

Average tokens per conversation: 4000
Cost per 1000 conversations: ~$80 (input tokens)

After Optimization

# CLAUDE.md (150 lines, 600 tokens)
[Core + imports]

# Imported when needed:
@docs/architecture.md (1500 tokens)
@docs/api.md (1200 tokens)
@docs/testing.md (800 tokens)

Average tokens per conversation: 600
  + Architecture discussions: +1500 (20% of conversations)
  + API work: +1200 (30% of conversations)
  + Testing: +800 (15% of conversations)

Weighted average: 600 + (1500×0.2) + (1200×0.3) + (800×0.15) = 1380 tokens

Cost per 1000 conversations: ~$27 (input tokens)
Savings: 66%

Summary: Best Practices

  1. Target 100-200 lines for main CLAUDE.md
  2. Use imports liberally for detailed docs
  3. Write concisely: bullets > paragraphs
  4. Be specific: concrete > vague
  5. Emphasize critical rules: IMPORTANT, YOU MUST, NEVER
  6. Organize by scope: user vs project vs subfolder
  7. Measure regularly: track token usage
  8. Clean monthly: remove outdated content
  9. Test effectiveness: verify Claude follows rules
  10. Version control team files: track changes

Goal: Minimum tokens for maximum effectiveness.