Initial commit
This commit is contained in:
355
skills/claude-context-manager/references/context_manager_mode.md
Normal file
355
skills/claude-context-manager/references/context_manager_mode.md
Normal file
@@ -0,0 +1,355 @@
|
||||
# Context Manager Mode
|
||||
|
||||
This guide helps you operate in **Context Manager Mode** - a specialized mode where your primary role is maintaining accurate, actionable context intelligence about a codebase.
|
||||
|
||||
## Your Role as Context Manager
|
||||
|
||||
When working in context manager mode, you are:
|
||||
- **Proactive**: Anticipate context needs before being asked
|
||||
- **Vigilant**: Monitor for staleness and inaccuracies
|
||||
- **Surgical**: Update only what's needed, preserve what's accurate
|
||||
- **Communicative**: Explain actions and recommendations clearly
|
||||
- **Autonomous**: Make decisions within defined boundaries
|
||||
|
||||
## Operating Mindset
|
||||
|
||||
### Think Like an Intelligence Officer
|
||||
|
||||
Your job is to maintain **operational intelligence** that helps the primary development work succeed. You're not writing documentation - you're maintaining cognitive maps.
|
||||
|
||||
**Key questions to ask:**
|
||||
- Will this information help me (Claude) work faster here?
|
||||
- Is this actionable or just descriptive?
|
||||
- Is this current or will it mislead?
|
||||
- Is this dense enough to justify the tokens?
|
||||
|
||||
### Proactive Behaviors
|
||||
|
||||
1. **When you first enter a codebase**: Run monitor.py to assess health
|
||||
2. **When code changes**: Check if affected context needs updating
|
||||
3. **When patterns emerge**: Document them immediately
|
||||
4. **When you struggle**: Note it as a signal context is inadequate
|
||||
5. **Before finishing**: Verify context is current
|
||||
|
||||
## Autonomous Workflows
|
||||
|
||||
### Workflow 1: Monitoring Loop
|
||||
|
||||
When asked to "monitor" or "maintain" context:
|
||||
|
||||
```bash
|
||||
# 1. Initial health check
|
||||
python scripts/monitor.py /path/to/repo
|
||||
|
||||
# 2. Based on results, prioritize actions:
|
||||
# - Critical/High: Update immediately
|
||||
# - Medium: Schedule for review
|
||||
# - Low: Continue monitoring
|
||||
|
||||
# 3. For items needing update:
|
||||
python scripts/auto_update.py /path/to/directory --analyze-only
|
||||
|
||||
# 4. Review suggestions, then update:
|
||||
python scripts/auto_update.py /path/to/directory
|
||||
|
||||
# 5. Verify update:
|
||||
python scripts/validate_claude_md.py /path/to/directory/claude.md
|
||||
```
|
||||
|
||||
### Workflow 2: Change-Responsive Update
|
||||
|
||||
When code changes in a directory with context:
|
||||
|
||||
```python
|
||||
# Decision tree:
|
||||
if significant_changes_detected():
|
||||
if context_exists():
|
||||
run_auto_update()
|
||||
else:
|
||||
run_generate_context()
|
||||
|
||||
verify_accuracy()
|
||||
report_actions()
|
||||
```
|
||||
|
||||
### Workflow 3: Proactive Discovery
|
||||
|
||||
When exploring new areas:
|
||||
|
||||
```python
|
||||
# As you navigate:
|
||||
if directory_seems_important() and not has_context():
|
||||
note_for_context_creation()
|
||||
|
||||
# Periodically:
|
||||
run_scan_repo()
|
||||
identify_missing_context()
|
||||
prioritize_by_importance()
|
||||
```
|
||||
|
||||
## Decision Authority
|
||||
|
||||
### You CAN decide autonomously:
|
||||
|
||||
✅ **Update context when:**
|
||||
- Staleness score is critical (score > 4)
|
||||
- You just made code changes affecting patterns
|
||||
- You discover inaccuracies while working
|
||||
- TODO markers remain and you have info to fill them
|
||||
|
||||
✅ **Generate new context when:**
|
||||
- Directory has 3+ significant files and no context
|
||||
- You struggled to understand the directory
|
||||
- Patterns are clear and worth documenting
|
||||
|
||||
✅ **Mark for review when:**
|
||||
- Staleness is high but you're unsure what changed
|
||||
- Context exists but seems incorrect
|
||||
- Significant refactor occurred
|
||||
|
||||
### You SHOULD ask first:
|
||||
|
||||
⚠️ **Before:**
|
||||
- Deleting existing context
|
||||
- Major restructuring of context
|
||||
- Updating context that's < 7 days old
|
||||
- Making bulk updates to many files
|
||||
|
||||
## Communication Patterns
|
||||
|
||||
### When Monitoring
|
||||
|
||||
**Good:**
|
||||
> I checked context health across the repo. Found 3 files needing attention:
|
||||
> - src/api/ (critical - 45 days old, 23 commits)
|
||||
> - src/services/ (high - 30 days old, 15 commits)
|
||||
> - tests/integration/ (medium - 20 days old, 8 commits)
|
||||
>
|
||||
> I'll start with src/api/. Should I proceed with all three?
|
||||
|
||||
**Bad:**
|
||||
> I ran a script and there are some issues.
|
||||
|
||||
### When Updating
|
||||
|
||||
**Good:**
|
||||
> Updated src/api/claude.md:
|
||||
> - Added new rate limiting pattern (introduced in last sprint)
|
||||
> - Updated middleware chain (auth-jwt.ts now handles tokens)
|
||||
> - Removed reference to deprecated cors-handler.ts
|
||||
>
|
||||
> Context is now current with HEAD.
|
||||
|
||||
**Bad:**
|
||||
> Updated the file.
|
||||
|
||||
### When Suggesting
|
||||
|
||||
**Good:**
|
||||
> I noticed src/utils/ has grown to 12 files but has no context. Based on my analysis:
|
||||
> - Mix of string helpers, date formatters, validation utils
|
||||
> - No clear pattern - might benefit from reorganization
|
||||
> - Should I create context as-is, or would you like to refactor first?
|
||||
|
||||
**Bad:**
|
||||
> You should add context to src/utils/.
|
||||
|
||||
## Context Quality Standards
|
||||
|
||||
### Actionable Content
|
||||
|
||||
Every section should answer: "What does this tell Claude to DO differently?"
|
||||
|
||||
❌ **Not actionable:**
|
||||
```markdown
|
||||
## Overview
|
||||
This directory contains services.
|
||||
```
|
||||
|
||||
✅ **Actionable:**
|
||||
```markdown
|
||||
## Service Pattern
|
||||
|
||||
**Structure**: Class-based with constructor DI
|
||||
**Rules**:
|
||||
- All async methods (no sync operations)
|
||||
- Throw domain-specific errors (never return error objects)
|
||||
- Transaction-aware (accept optional `trx` parameter)
|
||||
|
||||
**Example**:
|
||||
```typescript
|
||||
class UserService {
|
||||
constructor(private db: DB, private logger: Logger) {}
|
||||
async getUser(id: string, trx?: Transaction): Promise<User> { ... }
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
### Dense Information
|
||||
|
||||
Use token budget efficiently - every sentence should add value.
|
||||
|
||||
❌ **Not dense:**
|
||||
```markdown
|
||||
## Overview
|
||||
This is the API directory. It contains all the API-related code. The API
|
||||
is an important part of our application. It handles requests from the
|
||||
frontend and communicates with the backend services.
|
||||
```
|
||||
|
||||
✅ **Dense:**
|
||||
```markdown
|
||||
## API Layer
|
||||
|
||||
**Framework**: Express 4.x
|
||||
**Pattern**: Route → Validator → Service → Serializer
|
||||
**Rules**: No direct DB access, asyncHandler wrapper required
|
||||
**Entry**: index.ts registers all routes
|
||||
```
|
||||
|
||||
### Current Information
|
||||
|
||||
Context must reflect current reality, not history.
|
||||
|
||||
❌ **Historical:**
|
||||
```markdown
|
||||
We used to use MySQL but migrated to PostgreSQL in 2023.
|
||||
```
|
||||
|
||||
✅ **Current:**
|
||||
```markdown
|
||||
**Database**: PostgreSQL 15
|
||||
**ORM**: Prisma
|
||||
**Migrations**: prisma/migrations/
|
||||
```
|
||||
|
||||
## Handling Uncertainty
|
||||
|
||||
### When Unsure About Changes
|
||||
|
||||
```python
|
||||
if unsure_about_impact():
|
||||
run_analyze_only()
|
||||
present_findings()
|
||||
request_confirmation()
|
||||
else:
|
||||
update_autonomously()
|
||||
report_action()
|
||||
```
|
||||
|
||||
### When Context Conflicts with Code
|
||||
|
||||
```python
|
||||
if code_contradicts_context():
|
||||
verify_code_is_source_of_truth()
|
||||
update_context_to_match()
|
||||
note_the_discrepancy()
|
||||
```
|
||||
|
||||
### When Patterns are Unclear
|
||||
|
||||
```python
|
||||
if pattern_unclear():
|
||||
note_uncertainty_in_context()
|
||||
provide_examples_observed()
|
||||
mark_for_human_review()
|
||||
```
|
||||
|
||||
## Continuous Improvement
|
||||
|
||||
### Learn from Usage
|
||||
|
||||
When you find yourself repeatedly:
|
||||
- Looking for information that's not in context → Add it
|
||||
- Confused by outdated context → Trigger more frequent updates
|
||||
- Generating similar code → Document the pattern
|
||||
|
||||
### Measure Effectiveness
|
||||
|
||||
Track (mentally):
|
||||
- How often you reference context files
|
||||
- How often context helps vs. misleads
|
||||
- How much time saved by good context
|
||||
|
||||
### Iterate
|
||||
|
||||
After completing work:
|
||||
1. Quick context health check
|
||||
2. Update what you learned
|
||||
3. Note what would help next time
|
||||
|
||||
## Integration with Development Work
|
||||
|
||||
### Context Awareness During Development
|
||||
|
||||
While coding, maintain awareness:
|
||||
|
||||
```python
|
||||
# As you work:
|
||||
if entering_new_directory():
|
||||
check_for_context()
|
||||
note_if_missing()
|
||||
|
||||
if discovering_pattern():
|
||||
check_context_documents_it()
|
||||
update_if_missing()
|
||||
|
||||
if finding_gotcha():
|
||||
immediately_add_to_context()
|
||||
```
|
||||
|
||||
### Context Handoff
|
||||
|
||||
Before finishing a session:
|
||||
|
||||
1. Quick scan: `python scripts/monitor.py .`
|
||||
2. Update critical items
|
||||
3. Note remaining medium/low items
|
||||
4. Leave breadcrumbs for next session
|
||||
|
||||
## Example Session
|
||||
|
||||
```
|
||||
[User asks to add feature to API]
|
||||
|
||||
1. Check context: Read src/api/claude.md
|
||||
2. Work on feature: Follow patterns in context
|
||||
3. Notice new pattern: Middleware chaining changed
|
||||
4. Update context: Add new middleware pattern
|
||||
5. Verify: Run validation
|
||||
6. Report: "Feature added, context updated with new middleware pattern"
|
||||
|
||||
[Result: Feature works correctly AND context stays current]
|
||||
```
|
||||
|
||||
## Anti-Patterns to Avoid
|
||||
|
||||
❌ **Passive monitoring**: Waiting to be asked
|
||||
✅ **Active monitoring**: Regularly checking health
|
||||
|
||||
❌ **Bulk updates**: Updating everything at once
|
||||
✅ **Targeted updates**: Update what matters most
|
||||
|
||||
❌ **Over-documentation**: Writing essays
|
||||
✅ **Dense intelligence**: Every word counts
|
||||
|
||||
❌ **Ignoring staleness**: "It's probably fine"
|
||||
✅ **Vigilant maintenance**: Trust the metrics
|
||||
|
||||
❌ **Silent operation**: Just doing things
|
||||
✅ **Communicative operation**: Explaining actions
|
||||
|
||||
## Success Metrics
|
||||
|
||||
You're doing well when:
|
||||
- Context helps you work faster
|
||||
- Updates are small and frequent (not big and rare)
|
||||
- You rarely encounter outdated information
|
||||
- New contributors can onboard quickly
|
||||
- Code generation follows patterns correctly
|
||||
|
||||
## Remember
|
||||
|
||||
Context management is not about perfect documentation - it's about **maintaining cognitive maps that multiply your effectiveness**. Every context file should make you faster, more accurate, and more pattern-aware.
|
||||
|
||||
Your goal: Make future-Claude work better in this codebase.
|
||||
694
skills/claude-context-manager/references/examples.md
Normal file
694
skills/claude-context-manager/references/examples.md
Normal file
@@ -0,0 +1,694 @@
|
||||
# Claude.md Examples
|
||||
|
||||
This file provides concrete examples of well-structured `claude.md` files for different types of directories.
|
||||
|
||||
## Example 1: Source Code Directory
|
||||
|
||||
### src/services/
|
||||
|
||||
```markdown
|
||||
# src/services/
|
||||
|
||||
This directory contains the business logic layer that sits between API routes
|
||||
and the database. Services handle complex operations, business rules, and
|
||||
orchestrate multiple database operations.
|
||||
|
||||
## Purpose
|
||||
|
||||
Services provide:
|
||||
- Business logic implementation
|
||||
- Transaction management
|
||||
- Data validation and transformation
|
||||
- Integration with external APIs
|
||||
- Caching logic
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
services/
|
||||
├── user-service.ts # User management and authentication
|
||||
├── order-service.ts # Order processing and fulfillment
|
||||
├── payment-service.ts # Payment processing with Stripe
|
||||
├── email-service.ts # Email sending via SendGrid
|
||||
└── cache-service.ts # Redis caching utilities
|
||||
```
|
||||
```
|
||||
|
||||
## Key Patterns
|
||||
|
||||
### Service Class Structure
|
||||
|
||||
All services follow this pattern:
|
||||
|
||||
```typescript
|
||||
export class UserService {
|
||||
constructor(
|
||||
private db: Database,
|
||||
private cache: CacheService,
|
||||
private logger: Logger
|
||||
) {}
|
||||
|
||||
async getUser(id: string): Promise<User> {
|
||||
// 1. Check cache
|
||||
// 2. Query database if cache miss
|
||||
// 3. Transform data
|
||||
// 4. Update cache
|
||||
// 5. Return result
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
Services throw domain-specific errors:
|
||||
- `NotFoundError` - Resource doesn't exist
|
||||
- `ValidationError` - Business rule violation
|
||||
- `ConflictError` - Duplicate or conflicting resource
|
||||
- `ExternalServiceError` - Third-party API failure
|
||||
|
||||
### Transaction Management
|
||||
|
||||
Multi-step operations use database transactions:
|
||||
|
||||
```typescript
|
||||
async transferFunds(from: string, to: string, amount: number) {
|
||||
return this.db.transaction(async (trx) => {
|
||||
await this.debit(from, amount, trx);
|
||||
await this.credit(to, amount, trx);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
### Internal
|
||||
- `src/database/` - Database client and models
|
||||
- `src/lib/logger` - Logging utilities
|
||||
- `src/lib/config` - Configuration management
|
||||
|
||||
### External
|
||||
- Stripe SDK - Payment processing
|
||||
- SendGrid - Email delivery
|
||||
- Redis - Caching layer
|
||||
|
||||
## Testing
|
||||
|
||||
Service tests are in `tests/services/`:
|
||||
```bash
|
||||
npm run test:services
|
||||
```
|
||||
|
||||
Each service has:
|
||||
- Unit tests with mocked dependencies
|
||||
- Integration tests with test database
|
||||
|
||||
## Notes
|
||||
|
||||
- Services never directly access HTTP request/response objects
|
||||
- All external API calls should have timeout and retry logic
|
||||
- Cache invalidation happens within the service that modifies data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Example 2: Test Directory
|
||||
|
||||
### tests/integration/
|
||||
|
||||
```markdown
|
||||
# tests/integration/
|
||||
|
||||
Integration tests that verify multiple components working together, including
|
||||
database operations, API endpoints, and external service integrations.
|
||||
|
||||
## Overview
|
||||
|
||||
These tests use a real test database and mock external services. They run
|
||||
slower than unit tests but provide higher confidence in system behavior.
|
||||
|
||||
## Structure
|
||||
|
||||
```
|
||||
integration/
|
||||
├── api/ # Full API endpoint tests
|
||||
├── services/ # Service layer with real database
|
||||
├── workflows/ # End-to-end user workflows
|
||||
└── fixtures/ # Shared test data and utilities
|
||||
```
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
|
||||
```bash
|
||||
# All integration tests (takes ~5 minutes)
|
||||
npm run test:integration
|
||||
|
||||
# Specific test file
|
||||
npm run test:integration -- api/user-endpoints.test.ts
|
||||
|
||||
# Watch mode for development
|
||||
npm run test:integration:watch
|
||||
```
|
||||
|
||||
## Test Environment
|
||||
|
||||
Integration tests use:
|
||||
- **Database**: PostgreSQL test database (auto-created/destroyed)
|
||||
- **Cache**: In-memory Redis
|
||||
- **External APIs**: Mocked using `nock`
|
||||
- **Time**: Frozen at `2025-01-01T00:00:00Z` using `timekeeper`
|
||||
|
||||
## Patterns
|
||||
|
||||
### Test Structure
|
||||
|
||||
```typescript
|
||||
describe('User Registration Flow', () => {
|
||||
beforeAll(async () => {
|
||||
await setupTestDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await teardownTestDatabase();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await clearTestData();
|
||||
});
|
||||
|
||||
it('should create user and send welcome email', async () => {
|
||||
// Arrange
|
||||
const userData = fixtures.newUser();
|
||||
|
||||
// Act
|
||||
const response = await api.post('/users', userData);
|
||||
|
||||
// Assert
|
||||
expect(response.status).toBe(201);
|
||||
expect(emailMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ to: userData.email })
|
||||
);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Fixtures
|
||||
|
||||
Use shared fixtures for consistency:
|
||||
```typescript
|
||||
import { fixtures } from './fixtures';
|
||||
|
||||
const user = fixtures.user(); // Random valid user
|
||||
const admin = fixtures.user({ role: 'admin' }); // Admin user
|
||||
```
|
||||
|
||||
## Database Management
|
||||
|
||||
### Test Database Setup
|
||||
|
||||
Test database is created automatically but can be manually reset:
|
||||
|
||||
```bash
|
||||
npm run test:db:reset
|
||||
```
|
||||
|
||||
### Migrations
|
||||
|
||||
Integration tests run against the latest schema. If migrations change:
|
||||
|
||||
1. Stop running tests
|
||||
2. Run `npm run test:db:reset`
|
||||
3. Restart tests
|
||||
|
||||
## Common Issues
|
||||
|
||||
- **Timeout errors**: Increase timeout for slow operations
|
||||
```typescript
|
||||
it('slow operation', async () => {
|
||||
// ...
|
||||
}, 10000); // 10 second timeout
|
||||
```
|
||||
|
||||
- **Port conflicts**: Tests use port 3001. Ensure nothing else uses it.
|
||||
|
||||
- **Database locks**: Tests should clean up connections. If stuck:
|
||||
```bash
|
||||
npm run test:db:kill-connections
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Integration tests should NOT make real external API calls
|
||||
- Each test should be independent (no shared state)
|
||||
- Use transactions for faster test data cleanup when possible
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Example 3: Configuration Directory
|
||||
|
||||
### config/
|
||||
|
||||
```markdown
|
||||
# config/
|
||||
|
||||
Configuration management for all environments (development, staging, production).
|
||||
Uses environment variables with typed validation and sensible defaults.
|
||||
|
||||
## Overview
|
||||
|
||||
Configuration is loaded from:
|
||||
1. Environment variables (highest priority)
|
||||
2. `.env` file (development only)
|
||||
3. Default values (fallback)
|
||||
|
||||
## Files
|
||||
|
||||
- **index.ts**: Main config loader and validation
|
||||
- **schema.ts**: Zod schemas for type-safe config
|
||||
- **defaults.ts**: Default values for all settings
|
||||
- **database.ts**: Database connection configuration
|
||||
- **redis.ts**: Redis connection configuration
|
||||
- **stripe.ts**: Stripe API configuration
|
||||
|
||||
## Usage
|
||||
|
||||
```typescript
|
||||
import { config } from '@/config';
|
||||
|
||||
// Type-safe access
|
||||
const dbUrl = config.database.url;
|
||||
const stripeKey = config.stripe.apiKey;
|
||||
|
||||
// Environment check
|
||||
if (config.isProduction) {
|
||||
// Production-specific logic
|
||||
}
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
### Required (No Defaults)
|
||||
|
||||
These MUST be set in production:
|
||||
|
||||
```bash
|
||||
DATABASE_URL=postgresql://user:pass@host:5432/db
|
||||
REDIS_URL=redis://host:6379
|
||||
STRIPE_API_KEY=sk_live_xxxxx
|
||||
JWT_SECRET=your-secret-key
|
||||
```
|
||||
|
||||
### Optional (With Defaults)
|
||||
|
||||
```bash
|
||||
# Server
|
||||
PORT=3000
|
||||
HOST=0.0.0.0
|
||||
NODE_ENV=development
|
||||
|
||||
# Logging
|
||||
LOG_LEVEL=info
|
||||
LOG_FORMAT=json
|
||||
|
||||
# Features
|
||||
ENABLE_RATE_LIMITING=true
|
||||
ENABLE_ANALYTICS=false
|
||||
```
|
||||
|
||||
### Development Setup
|
||||
|
||||
Copy example file:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Then edit `.env` with your local values.
|
||||
|
||||
## Validation
|
||||
|
||||
Config is validated on startup using Zod schemas. Invalid config causes
|
||||
immediate application failure with clear error messages:
|
||||
|
||||
```
|
||||
❌ Configuration Error:
|
||||
- DATABASE_URL is required
|
||||
- STRIPE_API_KEY must start with 'sk_'
|
||||
- PORT must be a number between 1024 and 65535
|
||||
```
|
||||
|
||||
## Adding New Config
|
||||
|
||||
1. Add schema to `schema.ts`:
|
||||
```typescript
|
||||
export const newFeatureSchema = z.object({
|
||||
enabled: z.boolean().default(false),
|
||||
apiKey: z.string().min(1),
|
||||
});
|
||||
```
|
||||
|
||||
2. Add to main config schema in `index.ts`
|
||||
|
||||
3. Update `.env.example` with documentation
|
||||
|
||||
4. Add to TypeScript types (auto-generated from schema)
|
||||
|
||||
## Security
|
||||
|
||||
- **Never commit .env files** (in .gitignore)
|
||||
- **Never log sensitive config values**
|
||||
- **Use separate keys per environment**
|
||||
- **Rotate secrets regularly**
|
||||
|
||||
## Notes
|
||||
|
||||
- Config is loaded once at startup and cached
|
||||
- Changes require application restart
|
||||
- Use feature flags for runtime configuration changes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Example 4: API Routes Directory
|
||||
|
||||
### src/api/routes/
|
||||
|
||||
```markdown
|
||||
# src/api/routes/
|
||||
|
||||
HTTP route handlers that process requests, validate input, call services,
|
||||
and format responses. All routes follow RESTful conventions.
|
||||
|
||||
## Structure
|
||||
|
||||
Routes are organized by resource:
|
||||
|
||||
```
|
||||
routes/
|
||||
├── users.ts # User CRUD operations
|
||||
├── posts.ts # Post management
|
||||
├── comments.ts # Comment operations
|
||||
├── auth.ts # Authentication endpoints
|
||||
└── health.ts # Health check endpoints
|
||||
```
|
||||
```
|
||||
|
||||
## Route Pattern
|
||||
|
||||
Every route file exports a router:
|
||||
|
||||
```typescript
|
||||
import { Router } from 'express';
|
||||
import { authenticate, validate } from '../middleware';
|
||||
import { userService } from '@/services';
|
||||
import { createUserSchema, updateUserSchema } from '@/validators';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// GET /users/:id
|
||||
router.get('/:id',
|
||||
authenticate,
|
||||
asyncHandler(async (req, res) => {
|
||||
const user = await userService.getUser(req.params.id);
|
||||
res.json(serialize.user(user));
|
||||
})
|
||||
);
|
||||
|
||||
// POST /users
|
||||
router.post('/',
|
||||
validate(createUserSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const user = await userService.createUser(req.body);
|
||||
res.status(201).json(serialize.user(user));
|
||||
})
|
||||
);
|
||||
|
||||
export default router;
|
||||
```
|
||||
|
||||
## Conventions
|
||||
|
||||
### HTTP Methods
|
||||
- `GET` - Retrieve resources (idempotent)
|
||||
- `POST` - Create new resources
|
||||
- `PUT` - Replace entire resource
|
||||
- `PATCH` - Partial update
|
||||
- `DELETE` - Remove resource
|
||||
|
||||
### Status Codes
|
||||
- `200` - Success with body
|
||||
- `201` - Resource created
|
||||
- `204` - Success without body
|
||||
- `400` - Bad request (validation error)
|
||||
- `401` - Unauthorized (not logged in)
|
||||
- `403` - Forbidden (logged in but no permission)
|
||||
- `404` - Not found
|
||||
- `409` - Conflict (duplicate resource)
|
||||
- `500` - Server error
|
||||
|
||||
### URL Structure
|
||||
- Plural nouns: `/users`, `/posts`
|
||||
- Resource IDs: `/users/123`
|
||||
- Nested resources: `/posts/123/comments`
|
||||
- Actions as verbs: `/users/123/activate`
|
||||
|
||||
## Middleware Order
|
||||
|
||||
1. **Global middleware** (in app.ts)
|
||||
- Logging
|
||||
- CORS
|
||||
- Body parsing
|
||||
|
||||
2. **Route-specific middleware**
|
||||
- Authentication
|
||||
- Validation
|
||||
- Rate limiting
|
||||
|
||||
3. **Handler**
|
||||
- Business logic call
|
||||
- Response formatting
|
||||
|
||||
## Response Format
|
||||
|
||||
All JSON responses follow this structure:
|
||||
|
||||
```typescript
|
||||
// Success
|
||||
{
|
||||
"data": { /* resource or array */ },
|
||||
"meta": { /* pagination, etc */ }
|
||||
}
|
||||
|
||||
// Error
|
||||
{
|
||||
"error": {
|
||||
"code": "VALIDATION_ERROR",
|
||||
"message": "Invalid input",
|
||||
"details": [/* field errors */]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Adding New Routes
|
||||
|
||||
1. Create route file in this directory
|
||||
2. Define handlers with validation
|
||||
3. Register in `src/api/index.ts`:
|
||||
```typescript
|
||||
app.use('/api/resource', resourceRoutes);
|
||||
```
|
||||
4. Add tests in `tests/api/`
|
||||
5. Update OpenAPI spec in `docs/openapi.yaml`
|
||||
|
||||
## Testing Routes
|
||||
|
||||
```bash
|
||||
# All route tests
|
||||
npm run test:routes
|
||||
|
||||
# Specific route file
|
||||
npm run test:routes -- users.test.ts
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
- **Express Router** - Routing
|
||||
- **express-validator** - Input validation
|
||||
- **Services** - Business logic (in `src/services/`)
|
||||
- **Serializers** - Response formatting (in `src/serializers/`)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Example 5: Database/Models Directory
|
||||
|
||||
### src/models/
|
||||
|
||||
```markdown
|
||||
# src/models/
|
||||
|
||||
TypeScript interfaces and Prisma schema definitions that define the data
|
||||
models used throughout the application.
|
||||
|
||||
## Overview
|
||||
|
||||
Models are the single source of truth for data structure. They are used by:
|
||||
- Database operations (Prisma)
|
||||
- API validation
|
||||
- Service layer type checking
|
||||
- Response serialization
|
||||
|
||||
## Structure
|
||||
|
||||
```
|
||||
models/
|
||||
├── user.ts # User model and types
|
||||
├── post.ts # Post model and types
|
||||
├── comment.ts # Comment model and types
|
||||
└── index.ts # Re-exports all models
|
||||
```
|
||||
```
|
||||
|
||||
The actual database schema is in `prisma/schema.prisma`.
|
||||
|
||||
## Model Pattern
|
||||
|
||||
```typescript
|
||||
// Database model (from Prisma)
|
||||
export type User = {
|
||||
id: string;
|
||||
email: string;
|
||||
passwordHash: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
// API representation (subset, no sensitive fields)
|
||||
export type PublicUser = Omit<User, 'passwordHash'>;
|
||||
|
||||
// Creation input
|
||||
export type CreateUserInput = {
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
// Update input (all optional)
|
||||
export type UpdateUserInput = Partial<{
|
||||
email: string;
|
||||
password: string;
|
||||
}>;
|
||||
```
|
||||
|
||||
## Database Schema
|
||||
|
||||
The source of truth is `prisma/schema.prisma`:
|
||||
|
||||
```prisma
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
email String @unique
|
||||
passwordHash String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
posts Post[]
|
||||
}
|
||||
```
|
||||
|
||||
Generate TypeScript types after schema changes:
|
||||
```bash
|
||||
npm run prisma:generate
|
||||
```
|
||||
|
||||
## Relationships
|
||||
|
||||
- **User** → has many → **Post**
|
||||
- **Post** → has many → **Comment**
|
||||
- **Comment** → belongs to → **User**
|
||||
|
||||
Query with relations:
|
||||
```typescript
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
include: { posts: true }
|
||||
});
|
||||
```
|
||||
|
||||
## Migrations
|
||||
|
||||
After modifying `schema.prisma`:
|
||||
|
||||
```bash
|
||||
# Create migration
|
||||
npm run prisma:migrate:dev
|
||||
|
||||
# Apply to production
|
||||
npm run prisma:migrate:deploy
|
||||
```
|
||||
|
||||
## Type Generation
|
||||
|
||||
After database changes, regenerate Prisma types:
|
||||
```bash
|
||||
npm run prisma:generate
|
||||
```
|
||||
|
||||
This updates types in `node_modules/.prisma/client/` used throughout the app.
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Keep models focused (single responsibility)
|
||||
- Use explicit types for inputs/outputs
|
||||
- Never expose `passwordHash` or other sensitive fields
|
||||
- Use unions for status enums:
|
||||
```typescript
|
||||
export type PostStatus = 'draft' | 'published' | 'archived';
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Models are pure data structures (no methods)
|
||||
- Business logic belongs in services, not models
|
||||
- Use Prisma for all database operations (no raw SQL unless necessary)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template: Generic Directory
|
||||
|
||||
For directories that don't fit other categories:
|
||||
|
||||
```markdown
|
||||
# [directory-name]/
|
||||
|
||||
[One sentence describing what this directory contains]
|
||||
|
||||
## Overview
|
||||
|
||||
[2-3 sentences explaining the purpose and scope of this directory]
|
||||
|
||||
## Structure
|
||||
|
||||
[If complex, show directory tree with brief descriptions]
|
||||
|
||||
## Key Files
|
||||
|
||||
[Highlight 3-5 most important files and their roles]
|
||||
|
||||
## Important Patterns
|
||||
|
||||
[Document any conventions, patterns, or standards used here]
|
||||
|
||||
## Dependencies
|
||||
|
||||
[What this depends on and what depends on this]
|
||||
|
||||
## Usage
|
||||
|
||||
[How to work with code in this directory, with examples if helpful]
|
||||
|
||||
## Notes
|
||||
|
||||
[Any gotchas, known issues, or additional context]
|
||||
```
|
||||
|
||||
Use this template as a starting point and customize based on the specific directory's needs.
|
||||
316
skills/claude-context-manager/references/structure_guide.md
Normal file
316
skills/claude-context-manager/references/structure_guide.md
Normal file
@@ -0,0 +1,316 @@
|
||||
# Claude.md Structure Guide
|
||||
|
||||
This guide explains what makes an effective `claude.md` file and how to structure documentation for maximum utility when working with Claude.
|
||||
|
||||
## Purpose of claude.md Files
|
||||
|
||||
A `claude.md` file serves as context documentation that helps Claude (and humans) understand:
|
||||
|
||||
1. **What this directory contains** - Purpose and scope
|
||||
2. **How code is organized** - Structure and patterns
|
||||
3. **Key relationships** - Dependencies and connections
|
||||
4. **Important context** - Gotchas, conventions, and decisions
|
||||
|
||||
## Core Principles
|
||||
|
||||
### 1. Be Specific and Concrete
|
||||
|
||||
❌ **Avoid vague descriptions:**
|
||||
```markdown
|
||||
## Overview
|
||||
This directory contains utilities.
|
||||
```
|
||||
|
||||
✅ **Be specific:**
|
||||
```markdown
|
||||
## Overview
|
||||
This directory contains database utility functions for connection pooling,
|
||||
query building, and transaction management. These utilities are used across
|
||||
all services to ensure consistent database interactions.
|
||||
```
|
||||
|
||||
### 2. Prioritize Actionable Information
|
||||
|
||||
Focus on information that helps someone understand how to work with the code:
|
||||
|
||||
- **Entry points** - Where to start reading/editing
|
||||
- **Key patterns** - How things are typically done
|
||||
- **Dependencies** - What relies on what
|
||||
- **Gotchas** - Non-obvious behavior or limitations
|
||||
|
||||
### 3. Keep it Current
|
||||
|
||||
A stale `claude.md` is worse than none at all. Include:
|
||||
|
||||
- Maintenance notes ("Last updated: 2025-10-21")
|
||||
- Who maintains this area
|
||||
- How to update the documentation
|
||||
|
||||
## Recommended Structure
|
||||
|
||||
### Essential Sections
|
||||
|
||||
#### 1. Header and Overview (Required)
|
||||
|
||||
Start with a clear title and 1-3 sentence overview:
|
||||
|
||||
```markdown
|
||||
# src/api/
|
||||
|
||||
This directory implements the REST API layer, handling HTTP requests,
|
||||
validation, and response formatting. All endpoints follow OpenAPI 3.0
|
||||
specification defined in `openapi.yaml`.
|
||||
```
|
||||
|
||||
#### 2. Directory Structure (If Complex)
|
||||
|
||||
Show the layout with brief descriptions:
|
||||
|
||||
```markdown
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
api/
|
||||
├── routes/ # Route handlers grouped by resource
|
||||
├── middleware/ # Express middleware (auth, validation, logging)
|
||||
├── validators/ # Request/response validation schemas
|
||||
└── serializers/ # Response formatting utilities
|
||||
```
|
||||
```
|
||||
|
||||
#### 3. Key Files (If Applicable)
|
||||
|
||||
Highlight important files and their roles:
|
||||
|
||||
```markdown
|
||||
## Key Files
|
||||
|
||||
- **index.ts**: API server initialization and middleware setup
|
||||
- **routes.ts**: Central route registration
|
||||
- **error-handler.ts**: Global error handling middleware
|
||||
- **openapi.yaml**: API specification (source of truth for endpoints)
|
||||
```
|
||||
|
||||
#### 4. Important Patterns (Critical)
|
||||
|
||||
Document conventions and patterns used in this directory:
|
||||
|
||||
```markdown
|
||||
## Important Patterns
|
||||
|
||||
### Route Handler Structure
|
||||
|
||||
All route handlers follow this pattern:
|
||||
1. Validate request (using Zod schemas in `validators/`)
|
||||
2. Call service layer (never direct database access)
|
||||
3. Serialize response (using serializers)
|
||||
4. Handle errors (throw specific error types)
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Use `ApiError` class for all API errors
|
||||
- Status codes: 400 (validation), 401 (auth), 404 (not found), 500 (server)
|
||||
- Errors are caught by global error handler middleware
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
- Routes: kebab-case (`/user-profiles`)
|
||||
- Files: kebab-case (`user-profile-routes.ts`)
|
||||
- Handlers: camelCase (`getUserProfile`)
|
||||
```
|
||||
|
||||
#### 5. Dependencies (Important)
|
||||
|
||||
Explain relationships with other parts of the codebase:
|
||||
|
||||
```markdown
|
||||
## Dependencies
|
||||
|
||||
### Imports From
|
||||
- `src/services/` - Business logic layer
|
||||
- `src/models/` - Data models and types
|
||||
- `src/lib/` - Shared utilities (logger, config)
|
||||
|
||||
### Used By
|
||||
- All services make HTTP requests to these endpoints
|
||||
- Frontend application at `/frontend`
|
||||
|
||||
### External Dependencies
|
||||
- Express.js for routing
|
||||
- Zod for validation
|
||||
- OpenAPI Tools for spec validation
|
||||
```
|
||||
|
||||
#### 6. Usage/Getting Started (For Complex Areas)
|
||||
|
||||
Help someone get started quickly:
|
||||
|
||||
```markdown
|
||||
## Usage
|
||||
|
||||
### Adding a New Endpoint
|
||||
|
||||
1. Define the route in `openapi.yaml`
|
||||
2. Create handler in `routes/{resource}-routes.ts`
|
||||
3. Add validation schema in `validators/{resource}-validator.ts`
|
||||
4. Add serializer in `serializers/{resource}-serializer.ts`
|
||||
5. Register route in `routes.ts`
|
||||
|
||||
Example:
|
||||
[Include minimal working example]
|
||||
|
||||
### Testing
|
||||
|
||||
Run API tests:
|
||||
```bash
|
||||
npm run test:api
|
||||
```
|
||||
|
||||
Test single endpoint:
|
||||
```bash
|
||||
npm run test:api -- --grep "GET /users"
|
||||
```
|
||||
```
|
||||
|
||||
### Optional Sections
|
||||
|
||||
#### Architecture Decisions
|
||||
|
||||
Document important "why" decisions:
|
||||
|
||||
```markdown
|
||||
## Architecture Decisions
|
||||
|
||||
### Why Express over Fastify?
|
||||
- Team familiarity
|
||||
- Better TypeScript support at time of decision
|
||||
- Larger middleware ecosystem
|
||||
|
||||
### Why Separate Validators?
|
||||
- Reusable across routes and tests
|
||||
- Type inference for request/response objects
|
||||
- Easier to maintain OpenAPI spec sync
|
||||
```
|
||||
|
||||
#### Gotchas and Known Issues
|
||||
|
||||
Save others from pain:
|
||||
|
||||
```markdown
|
||||
## Gotchas
|
||||
|
||||
- **Async Handler Wrapping**: All async route handlers must be wrapped with
|
||||
`asyncHandler()` or errors won't be caught properly
|
||||
|
||||
- **Query Parameter Parsing**: Express doesn't parse nested query params by
|
||||
default. Use `qs` library for complex queries.
|
||||
|
||||
- **Rate Limiting**: Applied at middleware level, not per-route. See
|
||||
`middleware/rate-limiter.ts` for configuration.
|
||||
```
|
||||
|
||||
## What NOT to Include
|
||||
|
||||
Avoid these common pitfalls:
|
||||
|
||||
❌ **Don't duplicate what's obvious from code:**
|
||||
```markdown
|
||||
## Files
|
||||
- user.ts - Contains user-related code
|
||||
- product.ts - Contains product-related code
|
||||
```
|
||||
|
||||
❌ **Don't write tutorials for basics:**
|
||||
```markdown
|
||||
## What is an API?
|
||||
An API is an Application Programming Interface...
|
||||
```
|
||||
|
||||
❌ **Don't include things that change frequently:**
|
||||
```markdown
|
||||
## Team
|
||||
Current maintainers:
|
||||
- Alice (alice@company.com) - Lead
|
||||
- Bob (bob@company.com) - Backend
|
||||
[This will be stale immediately]
|
||||
```
|
||||
|
||||
✅ **Instead, link to maintained sources:**
|
||||
```markdown
|
||||
## Maintenance
|
||||
See [CODEOWNERS](../../CODEOWNERS) for current maintainers.
|
||||
```
|
||||
|
||||
## Hierarchy and Inheritance
|
||||
|
||||
### Root claude.md
|
||||
|
||||
The root `claude.md` provides high-level project context:
|
||||
|
||||
```markdown
|
||||
# Project Name
|
||||
|
||||
## Overview
|
||||
[High-level description of the entire project]
|
||||
|
||||
## Architecture
|
||||
[System architecture overview]
|
||||
|
||||
## Directory Guide
|
||||
- `/src` - Application source code ([claude.md](src/claude.md))
|
||||
- `/tests` - Test suite ([claude.md](tests/claude.md))
|
||||
- `/docs` - Documentation ([claude.md](docs/claude.md))
|
||||
|
||||
## Getting Started
|
||||
[Setup and development workflow]
|
||||
```
|
||||
|
||||
### Child claude.md Files
|
||||
|
||||
Child files inherit context from parent, so avoid repetition:
|
||||
|
||||
```markdown
|
||||
# src/api/routes/
|
||||
|
||||
Specific information about route handlers only. See parent
|
||||
[src/api/claude.md](../claude.md) for overall API structure.
|
||||
```
|
||||
|
||||
## Maintenance
|
||||
|
||||
### Keep It Fresh
|
||||
|
||||
Add maintenance metadata:
|
||||
|
||||
```markdown
|
||||
---
|
||||
Last Updated: 2025-10-21
|
||||
Maintainer: API Team (@api-team)
|
||||
---
|
||||
```
|
||||
|
||||
### Update Triggers
|
||||
|
||||
Update `claude.md` when:
|
||||
|
||||
- Major architectural changes occur
|
||||
- New patterns are introduced
|
||||
- Important files are added/removed/renamed
|
||||
- Gotchas are discovered
|
||||
- Team conventions change
|
||||
|
||||
### Review Regularly
|
||||
|
||||
- Quarterly reviews of all `claude.md` files
|
||||
- Update during major refactors
|
||||
- Validate during onboarding (new team members test docs)
|
||||
|
||||
## Templates by Directory Type
|
||||
|
||||
See [examples.md](examples.md) for complete templates for:
|
||||
- Source code directories
|
||||
- Test directories
|
||||
- API/Service layers
|
||||
- Configuration directories
|
||||
- Documentation directories
|
||||
- Library/utility directories
|
||||
Reference in New Issue
Block a user