Skip to content

Orchestre Memory System: A Practical Guide

Introduction to Orchestre's Memory System

Orchestre uses a distributed memory system that fundamentally changes how AI-assisted development projects maintain context. Unlike traditional documentation that quickly becomes outdated, Orchestre's memory lives alongside your code, evolves with it, and provides Claude Code with rich, contextual understanding of your project.

Why Distributed Memory Matters

Traditional documentation fails AI assistants because:

  • It's centralized in README files that become stale
  • It lacks connection to actual code implementation
  • It requires manual updates that developers forget
  • It doesn't capture the "why" behind decisions

Orchestre's distributed memory solves these problems by:

  • Colocating memory with code - Documentation lives where it's relevant
  • Capturing context naturally - Commands automatically document their actions
  • Version controlling knowledge - Git tracks all memory changes
  • Enabling intelligent assistance - Claude Code understands your entire project

Benefits for AI-Assisted Development

  1. Contextual Understanding: Claude Code knows your project's history, patterns, and decisions
  2. Faster Development: No need to explain context repeatedly
  3. Team Knowledge Sharing: New developers (and AI) onboard instantly
  4. Living Documentation: Memory updates automatically as code changes
  5. Intelligent Suggestions: Claude can reference past solutions and patterns

CLAUDE.md File Structure

Orchestre uses a hierarchy of CLAUDE.md files to capture different levels of project knowledge:

1. Root CLAUDE.md - Project Overview

Located at: project/CLAUDE.md

This is your project's executive summary. It answers:

  • What is this project?
  • What problem does it solve?
  • What are the key architectural decisions?
  • What patterns should be followed?

Real Example from a SaaS Project:

markdown
# TechFlow - Technical Documentation Platform

## Overview
TechFlow is a modern documentation platform that helps engineering teams create, maintain, and share technical documentation with AI assistance. Built with Next.js, Supabase, and integrated AI capabilities.

## Core Architecture Decisions
- **Multi-tenant SaaS**: Each organization has isolated data with RLS
- **AI-First Editing**: GPT-4 integration for documentation assistance
- **Real-time Collaboration**: Supabase real-time for live editing
- **Markdown-Based**: All docs stored as enhanced Markdown with frontmatter

## Key Patterns
- Server Components by default, Client Components only for interactivity
- All data access through Server Actions with authentication
- Feature-based folder structure with colocated CLAUDE.md files
- Comprehensive error boundaries and loading states

## Development Philosophy
- User experience over technical elegance
- Progressive enhancement with graceful degradation
- Accessibility as a first-class concern
- Performance budgets for all features

2. Orchestration Memory - Workflow State

Located at: .orchestre/CLAUDE.md

This captures the development workflow and current state:

  • Active development tasks
  • Recent architectural decisions
  • Workflow patterns that work
  • Integration challenges solved

Real Example:

markdown
# TechFlow - Orchestration Memory

## Current Development State
- **Phase**: MVP Feature Complete, Starting Beta
- **Active Feature**: Real-time collaborative editing
- **Next Priority**: Performance optimization for large documents

## Recent Decisions
### 2024-01-15: Switched to Server Actions
- Replaced API routes with Server Actions for better DX
- Automatic type safety and validation
- Simplified auth flow with built-in session handling
- Pattern established in `app/(app)/documents/actions.ts`

### 2024-01-12: Implemented Custom MDX Pipeline
- Built custom pipeline for security and performance
- Sanitization happens server-side before storage
- Client receives pre-processed safe HTML
- See `lib/mdx/` for implementation

## Discovered Patterns
### Optimistic UI Updates
```typescript
// Pattern for real-time features
const [optimisticState, setOptimisticState] = useState(initialState);

const handleUpdate = async (newValue) => {
  setOptimisticState(newValue); // Update immediately
  try {
    await serverAction(newValue);
  } catch (error) {
    setOptimisticState(initialState); // Rollback on error
    toast.error('Update failed');
  }
};

Integration Challenges Solved

Supabase Real-time + React Server Components

  • Challenge: Real-time subscriptions need client components
  • Solution: Hybrid approach with streaming SSR
  • Server component fetches initial data
  • Client component subscribes to updates
  • See components/realtime-wrapper.tsx pattern

### 3. Feature-Specific Memory

Located at: `feature-folder/CLAUDE.md`

Each major feature has its own memory capturing:
- Implementation details
- Business logic rationale
- Integration points
- Known edge cases

**Real Example from `app/(app)/editor/CLAUDE.md`:**
```markdown
# Document Editor Feature

## Overview
Real-time collaborative document editor with AI assistance. Supports Markdown with live preview, @mentions, and AI-powered writing suggestions.

## Implementation Details
- **Created**: 2024-01-10
- **Type**: Core user-facing feature
- **Key Decision**: Used TipTap instead of Slate.js for better stability

## Architecture
### Key Files
- `editor-provider.tsx` - Context for editor state and collaboration
- `editor-toolbar.tsx` - Formatting controls with keyboard shortcuts
- `ai-assistant.tsx` - AI suggestion interface and streaming
- `collaboration-cursor.tsx` - Real-time cursor positions

### Database Schema
```sql
-- document_versions table for history
CREATE TABLE document_versions (
  id UUID PRIMARY KEY,
  document_id UUID REFERENCES documents(id),
  content TEXT,
  created_by UUID REFERENCES profiles(id),
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Real-time presence tracked in Supabase Realtime channels

Real-time Architecture

  1. Document changes broadcast to channel: document:${docId}
  2. Presence updates every 3 seconds for cursor positions
  3. Conflict resolution: Last write wins with operational transform
  4. Auto-save every 10 seconds or on blur

Business Logic

Permissions

  • Only organization members can view documents
  • Edit permission checked per document
  • Public sharing generates read-only links with tokens

AI Integration

  • Writing suggestions triggered by "+++" marker
  • Context includes document outline and recent paragraphs
  • Streaming responses with abort capability
  • Rate limited to 10 requests per minute per user

Performance Optimizations

  • Virtualized rendering for long documents
  • Debounced saves (500ms)
  • Diff-based updates to minimize bandwidth
  • WebSocket connection pooling

Known Edge Cases

  1. Large Pastes: Chunks content to prevent blocking
  2. Offline Editing: Queues changes in localStorage
  3. Concurrent Edits: Shows conflict notification
  4. Session Timeout: Auto-saves before auth redirect

Debugging Helpers

typescript
// Enable debug mode in console
window.EDITOR_DEBUG = true;

// Logs all real-time messages and performance metrics

## Memory Hierarchy

Orchestre's memory system works as a hierarchy, with each level serving a specific purpose:

### 1. Project Level (Broad Context)
**File**: `CLAUDE.md`
- Project goals and vision
- Architecture decisions
- Technology choices
- Team conventions

**When to Update**: Major architectural changes, new team patterns, significant pivots

### 2. Orchestration Level (Workflow State)
**File**: `.orchestre/CLAUDE.md`
- Current sprint/phase
- Recent decisions and their outcomes
- Discovered patterns
- Integration solutions

**When to Update**: After each significant task, when patterns emerge, when solving tricky problems

### 3. Feature Level (Detailed Knowledge)
**File**: `feature/CLAUDE.md`
- Implementation specifics
- Business logic explanation
- API contracts
- UI/UX decisions

**When to Update**: When completing features, fixing bugs, discovering edge cases

### How They Interconnect

The memory files reference each other to build a complete picture:

```markdown
# In root CLAUDE.md
## Architecture Patterns
For specific implementation examples, see:
- Authentication: `app/(auth)/CLAUDE.md`
- Payment Processing: `app/(app)/billing/CLAUDE.md`
- API Design: `app/api/CLAUDE.md`

# In feature CLAUDE.md
## Related Context
- Follows project patterns from root `/CLAUDE.md`
- Uses authentication flow from `app/(auth)/CLAUDE.md`
- Integrates with billing as per `app/(app)/billing/CLAUDE.md`

Best Practices

What to Document

Always Document:

  1. The "Why": Reasoning behind decisions
  2. Patterns: Reusable solutions and approaches
  3. Gotchas: Non-obvious issues and their solutions
  4. Integration Points: How features connect
  5. Business Logic: Rules and constraints

Example of Good Memory:

markdown
## Decision: Custom Session Management
**Why**: Supabase sessions expire after 1 hour by default, causing poor UX
**Solution**: Implemented refresh token rotation with 7-day sliding window
**Trade-off**: More complex but much better user experience
**Implementation**: See `lib/auth/session-manager.ts`

How to Write Effective Memory

1. Be Specific and Actionable

❌ Bad: "Authentication is complex" ✅ Good: "Authentication uses Supabase with custom session refresh every 55 minutes to prevent expiry"

2. Include Code Examples

markdown
## Discovered Pattern: Optimistic Updates
When updating user data, we use optimistic updates for better UX:

\```typescript
// Always follow this pattern for user-facing updates
const updateProfile = async (data: ProfileData) => {
  // 1. Update UI immediately
  setProfile(data);
  
  // 2. Make server request
  const result = await updateProfileAction(data);
  
  // 3. Handle errors by reverting
  if (result.error) {
    setProfile(previousData);
    toast.error(result.error);
  }
};
\```

Always reference where the pattern is implemented:

markdown
## API Error Handling Pattern
Standardized error responses across all API routes.
**Pattern Location**: `lib/api/error-handler.ts`
**Usage Example**: `app/api/documents/[id]/route.ts`

When to Update Memory

Immediately After:

  1. Solving a tricky problem - Document the solution while it's fresh
  2. Making architectural decisions - Capture the reasoning
  3. Discovering patterns - Record reusable solutions
  4. Completing features - Document how it works

During Development:

bash
# Use Orchestre commands that auto-update memory
/document-feature editor "Added real-time collaboration"
/execute-task "Implement auth refresh" --update-memory

In Code Reviews:

  • Review memory updates alongside code
  • Ensure new patterns are documented
  • Verify feature CLAUDE.md files exist

Common Patterns

Pattern 1: Feature Development Flow

markdown
# Feature: User Notifications

## Development Chronicle
### Day 1: Research and Planning
- Evaluated email vs in-app vs push
- Decided on in-app + email for MVP
- Push notifications planned for Phase 2

### Day 2: Implementation
- Created notification preferences schema
- Built preference UI with real-time updates
- Discovered: Supabase triggers perfect for email queue

### Day 3: Edge Cases
- Handled notification grouping (max 1 email per hour)
- Added unsubscribe tokens to emails
- Implemented notification read status syncing

Pattern 2: Problem-Solution Memory

markdown
## Challenge: File Upload Progress

### Problem
Large file uploads (>50MB) showed no progress, users thought it was broken.

### Research
- Tried XMLHttpRequest upload events - too low level
- Supabase Storage SDK doesn't expose progress
- Users uploading 500MB+ video files

### Solution
Custom upload with progress:
\```typescript
const uploadWithProgress = async (file: File, onProgress: (pct: number) => void) => {
  // Implementation in lib/storage/upload-progress.ts
  // Uses chunks and measures completion
};
\```

### Result
- 87% reduction in upload abandonment
- Users now see progress bar with time remaining

Pattern 3: Architecture Decision Record

markdown
## ADR: State Management Approach

### Status: Accepted (2024-01-20)

### Context
Need state management for complex forms with:
- Multi-step flows
- Auto-save functionality
- Validation at each step
- Progress persistence

### Decision
Use Zustand instead of Redux Toolkit:
- Simpler API (50% less boilerplate)
- Built-in persistence middleware
- Better TypeScript inference
- Smaller bundle (8kb vs 40kb)

### Consequences
- ✅ Faster development
- ✅ Easier onboarding
- ❌ Less ecosystem support
- ❌ No time-travel debugging

### Implementation
See `lib/store/` for patterns and `docs/state-management.md` for guide.

Real-World Example: E-commerce Platform

Let's see how memory files work in a complete example:

Root CLAUDE.md

markdown
# ShopFlow - Modern E-commerce Platform

## Overview
Multi-vendor marketplace built with Next.js, focusing on SMB sellers. Handles 100K+ products with real-time inventory.

## Architecture Philosophy
- **Domain-Driven Design**: Bounded contexts for vendors, customers, orders
- **Event Sourcing**: All state changes through events for audit trail
- **CQRS**: Separate read/write models for performance
- **Micro-frontends**: Vendor dashboard separate from customer app

## Key Technical Decisions
- PostgreSQL with read replicas for scaling
- Redis for session and cache management
- Stripe Connect for vendor payouts
- Algolia for product search
- CloudFlare R2 for product images

.orchestre/CLAUDE.md

markdown
# ShopFlow - Orchestration State

## Current Sprint: Search Enhancement
- Implementing Algolia integration
- Migrating from PostgreSQL full-text search
- Expected 10x performance improvement

## Recent Wins
### Checkout Performance (2024-01-18)
- Reduced checkout time from 4s to 800ms
- Solution: Parallel payment processing with inventory check
- Pattern now used across all async operations

## Blockers Resolved
### Vendor Dashboard Performance
- Problem: Dashboard loading 15+ seconds with large catalogs
- Root Cause: N+1 queries in product variants
- Solution: DataLoader pattern with batching
- Result: 200ms average load time

Feature Memory: app/(vendor)/inventory/CLAUDE.md

markdown
# Vendor Inventory Management

## Overview
Real-time inventory tracking with multi-location support. Syncs with external systems via webhooks.

## Critical Business Rules
1. **Overselling Prevention**: Pessimistic locking on checkout
2. **Reserved Inventory**: 15-minute hold during checkout
3. **Low Stock Alerts**: Triggered at 20% threshold
4. **Bundle Handling**: All items must be available

## Implementation Details
### Real-time Updates
- WebSocket connection per vendor session
- Inventory changes broadcast immediately
- Optimistic UI with rollback on conflicts

### Sync Architecture
\```
External System → Webhook → Queue → Processor → Database → Broadcast
\```

### Performance Tricks
- Inventory counts cached in Redis (1min TTL)
- Bulk operations use database COPY command
- Virtual scrolling for large product lists

## Known Issues
- CSV imports timeout over 50K rows (chunking planned)
- Timezone confusion in low-stock reports (fixing in v2)

This distributed memory system ensures Claude Code always has the context needed to help effectively, whether you're debugging, adding features, or onboarding new team members.

Built with ❤️ for the AI Coding community, by Praney Behl