---
description:
globs:
alwaysApply: false
---
# Debugging and Troubleshooting Guide

## General Debugging Strategies

### Logging and Console Output
- **Development Mode**: Output debugging information using `console.log`
- **Structured Logging**: Structured log messages in JSON format
- **Error Stack Tracing**: Include detailed error information and stack traces

### TypeScript Type Errors
- **Type Checking**: Check entire project types with `npm run type-check`
- **Gradual Type Application**: Minimize `any` type usage and define specific types
- **Type Guards**: Ensure type safety at runtime

## MCP Server Debugging

### MCP Server Inspection Tools
```bash
# Inspect MCP server under development
npm run inspect

# Inspect built MCP server
npm run inspect:built
```

### Common MCP Issues

#### 1. Tool Registration Failure
```typescript
// Incorrect example
server.tool('invalid-tool', {
  // Missing parameter schema
}, handler);

// Correct example
server.tool('valid-tool', {
  description: 'Clear description',
  parameters: z.object({
    param: z.string().describe('Parameter description')
  })
}, handler);
```

#### 2. Type Mismatch Issues
- **Zod Schema Validation**: Type validation of input parameters
- **TypeScript Type Definitions**: Compile-time type safety

#### 3. Asynchronous Processing Errors
```typescript
// Properly handle Promise chains
server.tool('async-tool', schema, async (params) => {
  try {
    const result = await someAsyncOperation(params);
    return { result };
  } catch (error) {
    throw new Error(`Operation failed: ${error.message}`);
  }
});
```

## CLI Debugging

### CLI Command Testing
```bash
# Run CLI in local development mode
npm run context-compose -- --help

# Debug specific commands
npm run context-compose -- get-context default --verbose
```

### Common CLI Issues

#### 1. Command Parsing Errors
- **Commander.js Configuration Check**: Review command definitions in [src/cli/index.ts](mdc:src/cli/index.ts)
- **Argument Validation**: Distinguish between required and optional arguments

#### 2. File Path Issues
```typescript
// Handle relative paths
import path from 'path';
const configPath = path.resolve(process.cwd(), '.contextcompose');

// Check file existence
import fs from 'fs-extra';
if (!await fs.pathExists(configPath)) {
  throw new Error('Configuration directory does not exist');
}
```

## Build and Deployment Issues

### TypeScript Compilation Errors
```bash
# Full type checking
npm run type-check

# Incremental build
npm run build
```

### Dependency Issues
```bash
# Reinstall dependencies
rm -rf node_modules pnpm-lock.yaml
pnpm install

# Check dependency version conflicts
pnpm list --depth=0
```

### Package Deployment Issues
```bash
# Test local package
npm pack
npm install -g context-compose-1.0.5.tgz

# Pre-deployment validation
npm run lint && npm run test && npm run build
```

## Test Debugging

### Vitest Test Execution
```bash
# Run all tests
npm test

# Run specific test file
npx vitest run tests/specific-test.test.ts

# Run tests in watch mode
npx vitest --watch
```

### Playwright E2E Tests
```bash
# Run E2E tests
npx playwright test

# Disable headless mode (for debugging)
npx playwright test --headed

# Test only in specific browser
npx playwright test --project=chromium
```

## Performance Debugging

### Profiling
- **Node.js Profiler**: Use `--inspect` flag
- **Memory Usage Monitoring**: Detect memory leaks
- **Async Operation Bottlenecks**: Identify slow I/O operations

### Optimization Strategies
- **Minimize Bundle Size**: Remove unnecessary dependencies
- **Parallelize Async Operations**: Utilize Promise.all
- **Caching Strategy**: Optimize repetitive file read operations

## Error Handling Patterns

### Structured Error Handling
```typescript
class ContextComposeError extends Error {
  constructor(
    message: string,
    public code: string,
    public details?: any
  ) {
    super(message);
    this.name = 'ContextComposeError';
  }
}

// Usage example
throw new ContextComposeError(
  'Context file not found',
  'CONTEXT_NOT_FOUND',
  { path: contextPath }
);
```

### Graceful Failure Handling
- **Provide Defaults**: Use default configuration when config file is missing
- **User-Friendly Messages**: Convert technical errors to understandable messages
- **Recoverable Errors**: Distinguish errors that can be automatically recovered
