Activate Claude Code optimization for a specific project (10-15 minutes)
This guide walks you through activating the global Claude Code optimization system for a specific project. After completing the global setup (see ../01-global-optimization/), each project requires a brief activation process to create project-specific memories and configuration.
- Prerequisites
- Overview
- Quick Start
- Step-by-Step Activation
- Memory Creation
- Constitution Setup
- Verification
- Troubleshooting
- Next Steps
Before activating a project, ensure:
- ✅ Global optimization setup complete (
~/.claude/configured) - ✅ Serena MCP server available (check with Claude Code)
- ✅ You're in your project's root directory
- ✅ Project has recognizable structure (code files, config files)
Check global setup:
ls ~/.claude/agents/pm-orchestrator.md
ls ~/.claude/skills/*/SKILL.md
# Should see optimize, context, cache-inspector, update-docs, init-projectCheck Serena availability: In Claude Code conversation, try reading a file symbolically. If Serena is not activated, you'll see "No active project" errors.
Creates project-specific memories (.serena/memories/):
architecture.md- Project structure, patterns, key modulescodebase-conventions.md- Coding standards, naming patternsmodule-structure.md- Directory map, module relationships (if applicable)testing-strategy.md- Test patterns, commands, conventionsdocker-workflow.md- Docker commands, container names (if applicable)
Optional configuration (.claude/settings/):
constitution.json- Architectural decision framework (if needed)
Token savings:
- Per session: 60-70% reduction (load 5-8K token memories vs reading 15-20K tokens from files)
- Long-term: 70-90% with prompt caching on repeated memory reads
- Automated (using
/init-project --full): 10-15 minutes - Manual (following this guide): 20-30 minutes
- Per project: One-time activation
- ROI: Immediate - first session benefits from optimizations
# Navigate to project root
cd ~/projects/your-project
# Run automated initialization
# In Claude Code conversation:
/init-project --fullThis will:
- Auto-detect your language/framework
- Activate Serena for the project
- Fetch best practices from fastmcp.me
- Create constitution.json
- Initialize all 5 memories with templates
- Configure optimization settings
Time: 10-15 minutes (mostly automated)
# Navigate to project root
cd ~/projects/your-project
# Copy activation-agent.md content
# Paste into Claude Code conversation
# Agent guides you through activationTime: 15-20 minutes (guided)
Follow the step-by-step instructions below.
Time: 20-30 minutes (full control)
Serena needs to know about your project before it can create memories.
Method 1: Using mcp__serena__activate_project
In Claude Code conversation:
Please activate Serena for this project.
Use the tool: mcp__serena__activate_project
Project path: /full/path/to/your/project
Claude will call the tool and confirm activation.
Method 2: Using /init-project command
/init-project detect
This auto-detects your project and activates Serena.
Verification:
Please check if Serena is activated.
Try: mcp__serena__get_current_config
You should see your project listed as the active project.
If you haven't run Serena onboarding yet for this project:
In Claude Code conversation:
Please run Serena onboarding for this project.
Use: mcp__serena__onboarding
Serena will:
- Analyze your project structure
- Identify language and frameworks
- Recommend memory files to create
- Suggest constitution rules
Important: This is a one-time setup per project.
Claude Code's auto-memory uses a closed four-type taxonomy. Each memory must be one of these types:
| Type | Purpose | Body Structure |
|---|---|---|
| user | Role, goals, preferences, knowledge | Free-form profile |
| feedback | Corrections AND confirmations from user | Rule → Why: → How to apply: |
| project | Ongoing work, goals, deadlines, decisions | Fact → Why: → How to apply: |
| reference | Pointers to external systems (Linear, Grafana, Slack) | Location + purpose |
Key principles:
- Feedback captures BOTH failures AND successes — "if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated"
- Convert relative dates to absolute when saving project memories (e.g., "Thursday" → "2026-03-05")
- feedback/project types use structured body: lead with the rule/fact, then
**Why:**line, then**How to apply:**line
What NOT to save as memories (derivable from current state):
- Code patterns, conventions, architecture, file paths, project structure → read the code
- Git history, recent changes, who-changed-what →
git log/git blame - Debugging solutions or fix recipes → the fix is in the code, commit message has context
- Anything already documented in CLAUDE.md files
- Ephemeral task details, in-progress work, current conversation context
Before recommending from memory (trusting recall):
- A memory that names a specific function, file, or flag is a claim that it existed when the memory was written. It may have been renamed, removed, or never merged.
- If the memory names a file path: check the file exists before recommending
- If the memory names a function or flag: grep for it first
- "The memory says X exists" is not the same as "X exists now"
Serena stores project knowledge in .serena/memories/ as Markdown files. These are loaded at session start, providing instant context without reading files.
Create 5 core memories:
File: .serena/memories/architecture.md
Purpose: High-level project structure, key patterns, module organization
Template:
# Project Architecture
## Project Type
[e.g., Multi-tenant Laravel SaaS, React SPA, Python/Django API, Rust microservice]
## Tech Stack
- **Language**: [PHP 8.3, JavaScript ES6, Python 3.11, Rust 1.75, etc.]
- **Framework**: [Laravel 11, React 18, Django 5, Actix-web, etc.]
- **Database**: [PostgreSQL, MySQL, MongoDB, etc.]
- **Cache**: [Redis, Memcached, etc.]
- **Queue**: [Redis, RabbitMQ, etc.]
## Directory Structureproject-root/ ├── app/ # [Application code, models, controllers] ├── resources/ # [Views, assets] ├── database/ # [Migrations, factories, seeders] ├── tests/ # [Test files] ├── config/ # [Configuration files] └── docker/ # [Docker configuration]
## Key Architectural Patterns
### [Pattern 1: e.g., Multi-Tenancy]
- **Implementation**: [Organization-scoped queries, UUID primary keys]
- **Critical Files**: [Models, Middleware, Service classes]
- **Rules**: [ALWAYS scope by organization_id, never expose sequential IDs]
### [Pattern 2: e.g., Service Layer]
- **Implementation**: [Business logic in Services, controllers stay thin]
- **Location**: [app/Services/]
- **Usage**: [Called from controllers, contains all business rules]
## Module Structure
[List main modules/features and their relationships]
## External Integrations
[APIs, webhooks, third-party services]
How to fill it:
- Start with basic info (language, framework)
- Add directory structure (use
ls -laor file tree) - Identify 2-3 key patterns (multi-tenancy, auth, caching, etc.)
- List main modules/features
- Note any unique architectural decisions
Token size: 5-8K tokens (comprehensive but concise)
File: .serena/memories/codebase-conventions.md
Purpose: Coding standards, naming patterns, file organization rules
Template:
# Codebase Conventions
## Code Quality Standards
### Validation
- **Rule**: [e.g., ALL validation uses FormRequest classes (never inline)]
- **Location**: [app/Http/Requests/]
- **Pattern**: [One FormRequest per form, named {Action}{Model}Request]
### Business Logic
- **Rule**: [e.g., Business logic in Service Layer]
- **Location**: [app/Services/]
- **Pattern**: [One service per domain, injected via constructor]
### Authorization
- **Rule**: [e.g., Use Policy classes for all authorization]
- **Location**: [app/Policies/]
- **Pattern**: [One policy per model, registered in AuthServiceProvider]
## Naming Conventions
### Files
- **Models**: [PascalCase, singular (User.php)]
- **Controllers**: [PascalCase, plural + Controller (UsersController.php)]
- **Services**: [PascalCase + Service (UserService.php)]
- **Policies**: [PascalCase + Policy (UserPolicy.php)]
### Database
- **Tables**: [snake_case, plural (users, organization_users)]
- **Columns**: [snake_case (first_name, created_at)]
- **Foreign Keys**: [{model}_id (user_id, organization_id)]
- **Pivot Tables**: [alphabetical order (organization_user, not user_organization)]
### Routes
- **Naming**: [snake_case (api/users/profile, not api/users/userProfile)]
- **Grouping**: [By module/feature]
## File Organization
### Where to Put New Code
- **New Model**: [app/Models/]
- **New Controller**: [app/Http/Controllers/{Module}/]
- **New Service**: [app/Services/{Module}/]
- **New Request**: [app/Http/Requests/{Module}/]
- **New Policy**: [app/Policies/]
- **New Migration**: [database/migrations/]
- **New Test**: [tests/Feature/{Module}/ or tests/Unit/]
## Common Patterns
### Eloquent Relationships
```php
// Always define inverse relationships
// Use proper return types
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class);
}// Controllers call services, services contain business logic
public function store(CreateUserRequest $request)
{
$user = $this->userService->create($request->validated());
return response()->json($user, 201);
}// ALWAYS scope by organization
User::where('organization_id', auth()->user()->organization_id)->get();- ❌ Inline validation in controllers
- ❌ Business logic in controllers or models
- ❌ Direct authorization checks (use policies)
- ❌ Queries without organization scoping
- ❌ Sequential IDs in URLs (use UUIDs)
**How to fill it**:
1. Document validation approach
2. Note where business logic lives
3. List naming conventions for all file types
4. Show common code patterns with examples
5. List anti-patterns to avoid
**Token size**: 3-5K tokens
---
#### 3.3 Module Structure Memory (If Applicable)
**File**: `.serena/memories/module-structure.md`
**Purpose**: Map of modules/features, their relationships, navigation guide
**When to create**: If your project has multiple distinct modules/features
**Template**:
```markdown
# Module Structure
## Module Overview
Total modules: [21]
### Core Modules
1. **Authentication** - User login, registration, password reset
2. **Organizations** - Multi-tenant organization management
3. **Users** - User profiles, permissions, roles
### Feature Modules
4. **Dashboard** - Analytics, charts, summaries
5. **Settings** - Application configuration
[... list all modules ...]
## Module Dependencies
```mermaid
graph TD
Auth[Authentication] --> Org[Organizations]
Org --> Users
Users --> Dashboard
Users --> Settings
Each module follows this structure:
app/
├── Http/Controllers/{Module}/
│ ├── {Module}Controller.php
│ └── {Action}Controller.php
├── Models/{Module}/
│ └── {Model}.php
├── Services/{Module}/
│ └── {Module}Service.php
resources/views/{module}/
│ ├── index.blade.php
│ ├── show.blade.php
│ ├── create.blade.php
│ └── edit.blade.php
tests/Feature/{Module}/
│ └── {Module}Test.php
- Routes:
/organizations/* - Key Models: Organization, OrganizationUser
- Key Services: OrganizationService
- Special Logic: Multi-tenancy scoping, plan tier gating
- Routes:
/users/* - Key Models: User, Role, Permission
- Key Services: UserService, RoleService
- Special Logic: RBAC, organization scoping [... document each module ...]
- User authentication: app/Http/Controllers/Auth/
- Organization switching: app/Services/OrganizationService.php
- Dashboard widgets: app/View/Components/Dashboard/ [... map features to locations ...]
**How to fill it**:
1. List all modules/features
2. Show dependency relationships
3. Document standard module structure
4. Note special logic per module
5. Create feature → code location map
**Token size**: 2-3K tokens
**Skip if**: Single-module or very small project
---
#### 3.4 Testing Strategy Memory
**File**: `.serena/memories/testing-strategy.md`
**Purpose**: How to run tests, write tests, test patterns and conventions
**Template**:
```markdown
# Testing Strategy
## Running Tests
### Full Test Suite
```bash
# [Your test command, e.g.:]
docker-compose exec app php artisan test
# or
npm test
# or
cargo test
# [e.g.:]
docker-compose exec app php artisan test --filter=UserTest
npm test UserService.test.js
cargo test user_service# [e.g.:]
docker-compose exec app php artisan test --coverage
npm test -- --coverage
cargo tarpaulintests/
├── Feature/ # [Integration tests, HTTP tests]
│ ├── Auth/
│ ├── Organizations/
│ └── Users/
├── Unit/ # [Unit tests, isolated logic]
│ ├── Services/
│ └── Models/
└── Fixtures/ # [Test data, mocks]
- File: [{Thing}Test.php or {thing}.test.js]
- Class: [{Thing}Test extends TestCase]
- Method: [test_{action}_{expected_outcome}()]
// [Example: Testing HTTP endpoint]
public function test_user_can_create_organization()
{
$user = User::factory()->create();
$response = $this->actingAs($user)->postJson('/api/organizations', [
'name' => 'Acme Corp',
'plan' => 'premium',
]);
$response->assertStatus(201);
$this->assertDatabaseHas('organizations', ['name' => 'Acme Corp']);
}// [Example: Testing service method]
public function test_user_service_creates_user_with_organization()
{
$organization = Organization::factory()->create();
$user = $this->userService->create([
'name' => 'John Doe',
'email' => 'john@example.com',
'organization_id' => $organization->id,
]);
$this->assertInstanceOf(User::class, $user);
$this->assertEquals($organization->id, $user->organization_id);
}// [e.g., UserFactory.php]
public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'organization_id' => Organization::factory(),
];
}// [e.g., different user types]
public function admin()
{
return $this->state(['role' => 'admin']);
}
public function suspended()
{
return $this->state(['status' => 'suspended']);
}- Driver: [SQLite in-memory for tests]
- Config File: [phpunit.xml, jest.config.js, etc.]
- Migrations: [Run automatically before each test]
// [When to seed vs factory]
// Use factories for specific test data
// Use seeders for baseline data needed by all tests- Run test - See the error
- Add debugging - dd(), console.log(), dbg!
- Check state - Database, session, cache
- Fix code - Make the change
- Verify - Test passes
If not fixed after 5 iterations, ask for help or review approach.
- Overall: [80%+ code coverage]
- Critical paths: [100% (auth, payments, security)]
- Services: [90%+]
- Controllers: [80%+]
- Models: [70%+ (basic relationships)]
protected function actAsUser($role = 'user')
{
$user = User::factory()->$role()->create();
return $this->actingAs($user);
}[Document custom assertions, if any]
**How to fill it**:
1. Document test commands (local, Docker, CI)
2. Show test file organization
3. Provide pattern examples for feature/unit tests
4. Document factory patterns
5. Note test database configuration
6. List debugging strategies
**Token size**: 2-3K tokens
---
#### 3.5 Docker Workflow Memory (If Applicable)
**File**: `.serena/memories/docker-workflow.md`
**Purpose**: Docker commands, container names, common workflows
**When to create**: If project uses Docker
**Template**:
```markdown
# Docker Workflow
## Container Names
- **App**: [app] - Main application container
- **Database**: [db] - PostgreSQL/MySQL container
- **Redis**: [redis] - Cache/queue container
- **Web Server**: [nginx] - Nginx container (if separate)
- **Worker**: [worker] - Queue worker container (if applicable)
## Common Commands
### Start/Stop
```bash
# Start all containers
docker-compose up -d
# Stop all containers
docker-compose down
# Restart specific container
docker-compose restart app
# ALL artisan commands must use docker-compose exec
docker-compose exec app php artisan migrate
docker-compose exec app php artisan make:model Product
docker-compose exec app php artisan test
# Composer commands
docker-compose exec app composer install
docker-compose exec app composer require package/name
# NPM commands
docker-compose exec app npm install
docker-compose exec app npm run build# Run migrations
docker-compose exec app php artisan migrate
# Fresh migrations with seeding
docker-compose exec app php artisan migrate:fresh --seed
# Access database CLI
docker-compose exec db psql -U [username] -d [database]# View all logs
docker-compose logs -f
# View specific container logs
docker-compose logs -f app
docker-compose logs -f db# Enter app container
docker-compose exec app bash
# Enter database container
docker-compose exec db bashdocker-compose exec app composer install
docker-compose exec app php artisan migrate
docker-compose exec app npm install
docker-compose exec app npm run build# Create migration
docker-compose exec app php artisan make:migration create_products_table
# Edit migration file
# Run migration
docker-compose exec app php artisan migrate# Full test suite
docker-compose exec app php artisan test
# Specific test
docker-compose exec app php artisan test --filter=UserTest
# With coverage
docker-compose exec app php artisan test --coverage.env- Main environment configuration.env.testing- Test environment (if separate)docker-compose.yml- Docker configuration
# Check container status
docker-compose ps
# View container logs
docker-compose logs app
# Restart problematic container
docker-compose restart app# Check database is running
docker-compose ps db
# Verify .env DB_HOST matches container name
# (Usually DB_HOST=db, not localhost)# Fix storage permissions
docker-compose exec app chmod -R 775 storage bootstrap/cache
docker-compose exec app chown -R www-data:www-data storage bootstrap/cache- ✅ ALWAYS use
docker-compose exec appfor artisan, composer, npm commands - ✅ NEVER run commands directly on host (they won't affect Docker environment)
- ✅ Use container names in .env (DB_HOST=db, not localhost)
- ✅ Check docker-compose.yml for accurate container names
**How to fill it**:
1. List all container names from docker-compose.yml
2. Document standard command patterns
3. Show development workflow steps
4. Note common debugging scenarios
5. Highlight critical rules (exec vs direct commands)
**Token size**: 1-2K tokens
**Skip if**: No Docker usage
---
### Step 5: Save Memories to Serena
After creating the memory files, save them using Serena:
**In Claude Code conversation**:
Please save these memories to Serena:
- .serena/memories/architecture.md
- .serena/memories/codebase-conventions.md
- .serena/memories/module-structure.md (if created)
- .serena/memories/testing-strategy.md
- .serena/memories/docker-workflow.md (if created)
Use: mcp__serena__write_memory for each file
**Verify memories saved**:
List all memories: mcp__serena__list_memories
You should see all your memory files listed.
---
## Constitution Setup
**Optional**: Create a constitution if your project has critical architectural rules that must be enforced.
### When to Create a Constitution
Create `.claude/settings/constitution.json` if:
- Multi-tenant architecture (critical scoping rules)
- Strict security requirements
- Complex architectural patterns
- Team needs consistent decision-making framework
### Constitution Template
**File**: `.claude/settings/constitution.json`
```json
{
"version": "1.0.0",
"project": "Your Project Name",
"description": "Architectural decision framework for this project",
"principles": {
"multi_tenancy": {
"priority": "critical",
"description": "All data must be scoped to organizations",
"rules": [
"ALWAYS scope queries by organization_id",
"Use UUID primary keys for all models",
"Never expose sequential IDs in URLs or APIs",
"Validate organization access in all policies"
],
"enforcement": "automatic",
"violations": "reject_change"
},
"code_quality": {
"priority": "high",
"description": "Maintain consistent code quality standards",
"rules": [
"FormRequest for ALL validation (never inline)",
"Service Layer for business logic",
"Policy classes for authorization",
"Factory classes for all models"
],
"enforcement": "automatic",
"violations": "warn_and_suggest_fix"
},
"testing": {
"priority": "high",
"description": "All changes must include tests",
"rules": [
"Feature tests for all HTTP endpoints",
"Unit tests for all service methods",
"Factory coverage for all models",
"Run tests before committing"
],
"enforcement": "automatic",
"violations": "warn_and_suggest_fix"
},
"docker_workflow": {
"priority": "critical",
"description": "All commands must use Docker",
"rules": [
"ALL artisan commands via 'docker-compose exec app'",
"ALL composer commands via 'docker-compose exec app'",
"NEVER run commands directly on host"
],
"enforcement": "automatic",
"violations": "reject_change"
}
},
"decision_framework": {
"new_feature": [
"Check if similar feature exists",
"Verify multi-tenancy scoping",
"Plan tests before implementation",
"Create FormRequest for validation",
"Create Service for business logic",
"Create Policy if authorization needed"
],
"bug_fix": [
"Identify root cause",
"Write failing test first",
"Fix the bug",
"Verify test passes",
"Check for similar bugs elsewhere"
],
"refactoring": [
"Ensure tests exist and pass",
"Make incremental changes",
"Run tests after each change",
"Verify no behavior changes"
]
}
}
How to customize:
- Replace "Your Project Name" with actual project name
- Adjust priorities (critical, high, medium, low)
- Add/remove principles based on your architecture
- Define decision frameworks for common scenarios
- Set enforcement levels (automatic, manual, advisory)
Token impact: Constitution adds ~2K tokens to session start but prevents costly mistakes
After activation, verify everything works:
In Claude Code:
Please check Serena status:
mcp__serena__get_current_config
Should show your project as active.
List all memories:
mcp__serena__list_memories
Should see all 5 (or 3-4) memory files.
Read architecture memory:
mcp__serena__read_memory
memory_file_name: architecture.md
Should return your architecture content.
Find a class in your project using symbols:
mcp__serena__find_symbol
name_path_pattern: YourClassName
Should find the class without reading the full file.
/optimize "Fix typo in README.md"
Watch for:
- PM Orchestrator loads memories
- Uses symbol-first exploration
- References constitution (if applicable)
- Completes task efficiently
Symptom: Serena tools fail with "No active project"
Fix:
Activate the project:
mcp__serena__activate_project
project: /full/path/to/your/project
Symptom: Session doesn't include project context
Fix:
-
Verify memories exist:
ls .serena/memories/
-
List memories in Serena:
mcp__serena__list_memories -
If missing, recreate them following Step 3 above
Symptom: Claude reads full files instead of using symbols
Fix:
- Check Serena is activated (see above)
- Verify language server is running for your language
- Check
.serena/project.ymlhas correct language configuration - Remind Claude to use symbol-first exploration:
Please use symbol-first exploration. Use mcp__serena__find_symbol before reading files.
Symptom: Architectural rules not followed
Fix:
-
Verify constitution.json exists:
ls .claude/settings/constitution.json
-
Validate JSON syntax:
cat .claude/settings/constitution.json | python -m json.tool -
Check PM Orchestrator is loading it:
Please check if constitution is loaded. Read: .claude/settings/constitution.json
Symptom: Not seeing 60-70% token reduction
Possible causes:
- Memories not loaded - Verify memories are being loaded at session start
- Reading full files - Ensure symbol-first exploration is used
- No prompt caching - Check if prompt caching is enabled in global settings
- Small project - Savings more noticeable in larger projects
Debug:
/cache-inspector status
Check cache hit rate and memory usage.
After successful activation:
# For any task
/optimize "Your task here"
# For implementing a feature
/sc-implement "New feature description"
# For working on specific module
/sc-module module-name# Check cache performance
/cache-inspector status
# Analyze token usage
/cache-inspector analyzeWhen architecture changes:
# Refresh memories
/context refresh
# Or manually update specific memory
# Edit .serena/memories/architecture.md
# Re-save with mcp__serena__write_memoryShare this guide and memory templates with teammates:
# Zip memory files as examples
tar -czf memories-template.tar.gz .serena/memories/
# Share with team
# They can use as starting point for their activationFor your next project:
cd ~/projects/another-project
/init-project --fullWith global setup complete, each new project takes only 10-15 minutes!
What we accomplished:
- ✅ Activated Serena for your project
- ✅ Created 3-5 core memories (12-20K tokens of context)
- ✅ Optionally created constitution for architectural decisions
- ✅ Verified activation successful
- ✅ Ready for 60-90% token savings on all future sessions
Time invested: 10-30 minutes (depending on automation level)
Expected savings:
- Per session: 60-70% token reduction (load memories vs read files)
- With caching: 70-90% total reduction
- Cost savings: $1-2 per session for medium/large projects
- Speed improvement: 40-50% faster (less file reading)
ROI: Immediate - first session benefits from optimizations
Next: Start working with optimized workflows! See ../03-custom-skills/ for creating project-specific skills, or jump straight to coding with /optimize "your task".