Best Practices Guide
Overview
This guide summarizes the key best practices demonstrated in the claude-code-leaked codebase.
Architectural Best Practices
1. Modular Tool Design
Practice: Every capability is exposed as a self-contained tool.
Why: Makes the system highly extensible and maintainable.
Example:
// Each tool has its own directory with logic, UI, and prompt
src/tools/BashTool/
├── BashTool.ts - Tool implementation
├── UI.tsx - UI rendering
├── prompt.ts - System prompt contribution
2. Feature-Flagged Architecture
Practice: Use bun:bundle feature flags for dead code elimination.
Why: Reduces memory footprint and improves performance.
Example:
const module = feature('FLAG_NAME')
? require('./module.js')
: null;
3. Parallel Initialization
Practice: Fire MDM, Keychain, and API preconnect simultaneously.
Why: Minimizes startup time by running independent operations in parallel.
Example:
await Promise.all([
ensureMdmSettingsLoaded(),
ensureKeychainPrefetchCompleted(),
fetchBootstrapData()
]);
4. Service Layer Abstraction
Practice: Separate external integrations into a dedicated services layer.
Why: Clean separation of concerns, easier testing and maintenance.
Example:
src/services/
├── api/ - Anthropic SDK
├── mcp/ - MCP client
├── oauth/ - Authentication
├── lsp/ - Language server
├── analytics/ - Feature flags
5. Permission System
Practice: Gate tool operations based on configurable permission modes.
Why: Provides fine-grained control over tool access.
Example:
async checkPermissions(input, context) {
// Check working directory restrictions
// Check tool-specific rules
return { result: true };
}
Code Quality Best Practices
1. Strict TypeScript
Practice: Use strict TypeScript throughout the codebase.
Why: Ensures type safety and reduces runtime errors.
Example:
interface ToolInputJSONSchema {
[x: string]: unknown;
type: 'object';
properties?: { [x: string]: unknown };
}
2. Zod Schemas
Practice: Use Zod for runtime schema validation.
Why: Provides clear input validation and error messages.
Example:
inputSchema: z.object({
command: z.string(),
timeout: z.number().optional(),
workdir: z.string().optional(),
})
3. Lazy Loading
Practice: Load heavy modules only when needed.
Why: Reduces initial memory usage and improves startup time.
Example:
const messageSelector = (): typeof import('src/components/MessageSelector.js') =>
require('src/components/MessageSelector.js')
4. Error Handling
Practice: Implement graceful degradation on failures.
Why: Prevents crashes and maintains system stability.
Example:
try {
await serviceOperation();
} catch (error) {
if (isRetryableError(error)) {
await retryOperation(error);
}
logEvent('service_error', { service: 'api', error: error.message });
}
5. Caching Strategy
Practice: Cache expensive operations to improve performance.
Why: Avoids redundant computations and I/O operations.
Example:
export function clearPluginCache(reason: string): void {
// Clear cache when settings or files change
}
Performance Best Practices
1. Parallel Executions
Practice: Run independent operations simultaneously.
Why: Maximizes CPU and I/O utilization.
Example:
void Promise.all([
initUser(),
getUserContext(),
prefetchSystemContextIfSafe(),
getRelevantTips(),
prefetchOfficialMcpUrls()
]);
2. Event Loop Monitoring
Practice: Detect event loop stalls for performance issues.
Why: Identifies when the main thread is blocked.
Example:
void import('./utils/eventLoopStallDetector.js')
.then(m => m.startEventLoopStallDetector());
3. Dead Code Elimination
Practice: Use feature flags to exclude unused code from builds.
Why: Reduces binary size and memory usage.
Example:
const module = feature('FLAG') ? require('./module.js') : null;
4. Prefetching Strategy
Practice: Prefetch data before it’s needed.
Why: Reduces latency when data is actually required.
Example:
void prefetchOfficialMcpUrls();
void prefetchAwsCredentialsAndBedRockInfoIfSafe();
Security Best Practices
1. Permission Modes
Practice: Implement configurable permission modes (default, plan, auto, bypass).
Why: Provides fine-grained control over tool access.
2. Working Directory Restrictions
Practice: Restrict operations to allowed working directories.
Why: Prevents unauthorized file access.
3. Feature-Gated Security
Practice: Gate security features with feature flags.
Why: Allows selective enabling of security features.
4. Error Boundaries
Practice: Isolate failures to prevent system-wide crashes.
Why: Maintains system stability on errors.
Development Best Practices
1. Consistent Naming Conventions
Practice: Use predictable naming patterns.
Why: Makes the codebase more intuitive to navigate.
Examples:
- Tool files:
<ToolName>Tool.ts - UI files:
UI.tsx - Prompt files:
prompt.ts
2. Clear Directory Structure
Practice: Organize code by functionality.
Why: Makes it easy to find related code.
Example:
src/
├── tools/ - All tool implementations
├── commands/ - All slash commands
├── services/ - External integrations
├── components/ - UI components
├── utils/ - Utility functions
3. Inline Documentation
Practice: Add JSDoc comments for clarity.
Why: Makes code self-documenting.
Example:
/**
* findGitRoot - Find git repository root
*
* @param cwd - Current working directory
* @returns Git root path or null if not found
*/
export function findGitRoot(cwd: string): string | null {
// Implementation
}
4. Migration System
Practice: Implement versioned migrations for settings.
Why: Ensures backward compatibility.
Example:
const CURRENT_MIGRATION_VERSION = 11;
if (getGlobalConfig().migrationVersion !== CURRENT_MIGRATION_VERSION) {
migrateSonnet1mToSonnet45();
migrateLegacyOpusToCurrent();
saveGlobalConfig(prev => ({
...prev,
migrationVersion: CURRENT_MIGRATION_VERSION
}));
}
Testing Best Practices
1. Unit Tests
Practice: Test individual functions and utilities.
Why: Verifies core logic in isolation.
2. Integration Tests
Practice: Test interactions between modules.
Why: Validates system integration points.
3. E2E Tests
Practice: Test full user workflows.
Why: Ensures end-to-end functionality.
4. Performance Tests
Practice: Benchmark critical paths.
Why: Identifies performance bottlenecks.
Common Pitfalls to Avoid
- Circular Dependencies: Can cause import cycles and slow initialization
- Over-Engineering Feature Flags: Excessive flags can complicate build configuration
- Large Monolithic Files: Files with 29K-46K lines can be overwhelming
- Permission System Complexity: Multiple handlers can be confusing for newcomers
- Documentation Burden: New contributors need to understand multiple docs
Recommendations for New Codebase
When duplicating this codebase, focus on:
- Tool System: Implement the tool factory pattern consistently
- Service Layer: Keep external integrations separate from core logic
- Feature Flags: Use them for dead code elimination
- Parallel Startup: Initialize independent systems simultaneously
- Permission Gates: Implement configurable permission modes
- Lazy Loading: Load heavy modules on demand
- Caching Strategy: Cache expensive operations
- Error Handling: Implement graceful degradation