# Yemaya Debugging Guide

A comprehensive guide for debugging issues in the Yemaya platform.

## Table of Contents

- [Development Environment](#development-environment)
- [Debugging the API](#debugging-the-api)
- [Debugging the Web App](#debugging-the-web-app)
- [Debugging the Desktop App](#debugging-the-desktop-app)
- [Database Issues](#database-issues)
- [Common Issues](#common-issues)
- [Performance Debugging](#performance-debugging)
- [Logging](#logging)
- [Tools and Techniques](#tools-and-techniques)

---

## Development Environment

### Quick Health Check

Run these commands to verify your environment:

```bash
# Check Node version
node -v  # Should be v20+

# Check pnpm version
pnpm -v  # Should be v10+

# Check Docker is running
docker ps

# Verify infrastructure services
docker compose ps
```

### Infrastructure Not Starting

If `docker compose up` fails:

```bash
# Check for port conflicts
lsof -i :5432  # PostgreSQL
lsof -i :6379  # Redis
lsof -i :9000  # MinIO

# View container logs
docker compose logs postgres
docker compose logs redis

# Restart fresh
docker compose down -v
docker compose up -d
```

### Dependency Issues

```bash
# Clear node_modules and reinstall
rm -rf node_modules
rm -rf apps/*/node_modules
rm -rf packages/*/node_modules
pnpm install

# Clear pnpm cache if needed
pnpm store prune

# Rebuild native dependencies
pnpm rebuild
```

### TypeScript Errors After Pull

```bash
# Rebuild all packages in order
pnpm build

# Or rebuild specific package
pnpm --filter @yemaya/types build
pnpm --filter @yemaya/core build
```

---

## Debugging the API

### Enable Debug Logging

Set environment variables in `.env`:

```bash
# Enable verbose logging
LOG_LEVEL=debug

# Log all database queries
DATABASE_LOG_QUERIES=true

# Log HTTP requests
DEBUG=hono:*
```

### VS Code Launch Configuration

Create `.vscode/launch.json`:

```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug API",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "pnpm",
      "runtimeArgs": ["--filter", "@yemaya/api", "dev"],
      "cwd": "${workspaceFolder}",
      "console": "integratedTerminal",
      "env": {
        "NODE_ENV": "development",
        "LOG_LEVEL": "debug"
      }
    }
  ]
}
```

### Debugging with Breakpoints

1. Add `debugger` statement in code:

```typescript
async function handleRequest(c: Context) {
  debugger; // Execution pauses here
  const user = await getUser(c.get('userId'));
  return c.json({ user });
}
```

2. Or use VS Code breakpoints with source maps

### Inspect API Requests

Use the built-in request logger:

```typescript
// In development, all requests are logged
// Output: <-- GET /v1/projects
//         --> GET /v1/projects 200 45ms
```

For detailed request/response inspection:

```bash
# Use curl with verbose output
curl -v http://localhost:3000/v1/projects \
  -H "Authorization: Bearer $TOKEN"

# Use httpie for cleaner output
http GET localhost:3000/v1/projects Authorization:"Bearer $TOKEN"
```

### API Error Investigation

When you receive an error response:

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input",
    "details": { "name": ["Required"] }
  }
}
```

1. Check the error code in `packages/core/src/errors/`
2. Search codebase for where error is thrown
3. Add logging before the throw statement

```typescript
// Add temporary logging
console.log('Validation input:', JSON.stringify(input, null, 2));
throw new ValidationError('Invalid input', details);
```

---

## Debugging the Web App

### React DevTools

Install the React DevTools browser extension for:

- Component tree inspection
- Props and state examination
- Performance profiling
- Hooks debugging

### TanStack Query DevTools

Already included in development mode. Access via the floating button in
bottom-right corner.

Features:

- View all queries and their status
- Inspect cached data
- Trigger refetches
- View query timelines

### Console Debugging

```typescript
// Log component renders
function ProjectList() {
  console.log('ProjectList rendered');
  // ...
}

// Log state changes
useEffect(() => {
  console.log('Projects changed:', projects);
}, [projects]);

// Log with component name
console.log('[ProjectList]', 'Loading projects...');
```

### Network Tab

Use browser DevTools Network tab to:

1. Filter by `Fetch/XHR` to see API calls
2. Check request headers (especially Authorization)
3. Examine response bodies
4. Look for failed requests (red)

### Source Maps

Source maps are enabled in development. To debug:

1. Open browser DevTools > Sources
2. Navigate to `webpack://` or `vite://` sources
3. Set breakpoints in original TypeScript files

### State Debugging

For Zustand stores:

```typescript
// Enable devtools
import { devtools } from 'zustand/middleware';

const useStore = create(
  devtools(
    (set) => ({
      // ...
    }),
    { name: 'ProjectStore' }
  )
);
```

View in Redux DevTools browser extension.

---

## Debugging the Desktop App

### Main Process

The main process runs in Node.js. Debug with:

```bash
# Start with inspector
pnpm desktop dev --inspect

# Or with specific port
pnpm desktop dev --inspect=9229
```

Then in Chrome:

1. Navigate to `chrome://inspect`
2. Click "Open dedicated DevTools for Node"
3. Set breakpoints in main process code

### Renderer Process

The renderer is a Chromium window:

1. In the app, press `Cmd+Option+I` (Mac) or `Ctrl+Shift+I` (Windows/Linux)
2. DevTools opens with full debugging capabilities

### IPC Communication

Debug IPC messages:

```typescript
// In main process
ipcMain.handle('get-project', async (event, projectId) => {
  console.log('[IPC Main] get-project:', projectId);
  const result = await getProject(projectId);
  console.log('[IPC Main] result:', result);
  return result;
});

// In renderer process
const result = await window.api.getProject(projectId);
console.log('[IPC Renderer] result:', result);
```

### Production Builds

Debug production builds locally:

```bash
# Build the app
pnpm desktop build

# Run the built app with console output
# macOS
./dist/mac/Yemaya.app/Contents/MacOS/Yemaya --enable-logging

# Windows
.\dist\win-unpacked\Yemaya.exe --enable-logging

# Linux
./dist/linux-unpacked/yemaya --enable-logging
```

---

## Database Issues

### Connection Problems

```bash
# Test PostgreSQL connection
docker compose exec postgres psql -U postgres -d yemaya -c "SELECT 1"

# Check connection string
echo $DATABASE_URL

# Verify from Node.js
pnpm --filter @yemaya/database db:test-connection
```

### Migration Issues

```bash
# Check migration status
pnpm --filter @yemaya/database db:migrate:status

# Reset database (WARNING: destroys data)
pnpm --filter @yemaya/database db:reset

# Generate migration from schema changes
pnpm --filter @yemaya/database db:migrate:dev

# Apply pending migrations
pnpm --filter @yemaya/database db:migrate
```

### Query Debugging

Enable query logging in Prisma:

```typescript
// packages/database/src/client.ts
const prisma = new PrismaClient({
  log: [
    { emit: 'event', level: 'query' },
    { emit: 'stdout', level: 'error' },
    { emit: 'stdout', level: 'warn' },
  ],
});

prisma.$on('query', (e) => {
  console.log('Query:', e.query);
  console.log('Params:', e.params);
  console.log('Duration:', e.duration, 'ms');
});
```

### Prisma Studio

Visual database browser:

```bash
pnpm --filter @yemaya/database db:studio
```

Opens at http://localhost:5555

### Data Inspection

```bash
# Connect to database
docker compose exec postgres psql -U postgres -d yemaya

# Common queries
\dt                          # List tables
\d users                     # Describe users table
SELECT * FROM users LIMIT 5; # Sample data
SELECT count(*) FROM projects;
```

---

## Common Issues

### "Cannot find module"

```bash
# Ensure all packages are built
pnpm build

# Check package exports in package.json
cat packages/core/package.json | jq '.exports'

# Verify the file exists
ls packages/core/dist/
```

### "Port already in use"

```bash
# Find process using port
lsof -i :3000

# Kill process
kill -9 <PID>

# Or use different port
PORT=3001 pnpm --filter @yemaya/api dev
```

### TypeScript Errors

```bash
# Check specific package
pnpm --filter @yemaya/core typecheck

# Clear TypeScript cache
rm -rf node_modules/.cache/typescript
pnpm typecheck
```

### "Hydration mismatch" (React)

This occurs when server/client HTML differs:

1. Check for `typeof window !== 'undefined'` guards
2. Avoid reading `localStorage` during render
3. Use `useEffect` for client-only code

```typescript
// Bad - causes hydration mismatch
function Component() {
  const theme = localStorage.getItem('theme'); // Runs on server too
  return <div className={theme}>...</div>;
}

// Good - client-only
function Component() {
  const [theme, setTheme] = useState('light');

  useEffect(() => {
    setTheme(localStorage.getItem('theme') || 'light');
  }, []);

  return <div className={theme}>...</div>;
}
```

### "CORS error"

Check API CORS configuration:

```typescript
// apps/api/src/app.ts
app.use(
  cors({
    origin: ['http://localhost:5173'], // Add your frontend URL
    credentials: true,
  })
);
```

### Authentication Issues

Debug token flow:

```typescript
// Check token contents
const token = localStorage.getItem('accessToken');
const payload = JSON.parse(atob(token.split('.')[1]));
console.log('Token payload:', payload);
console.log('Expires:', new Date(payload.exp * 1000));
```

---

## Performance Debugging

### API Performance

```typescript
// Add timing middleware
app.use('*', async (c, next) => {
  const start = performance.now();
  await next();
  const duration = performance.now() - start;

  if (duration > 100) {
    console.warn(`Slow request: ${c.req.method} ${c.req.path} - ${duration}ms`);
  }
});
```

### Database Query Performance

```bash
# Enable slow query logging
docker compose exec postgres psql -U postgres -d yemaya -c "
  ALTER SYSTEM SET log_min_duration_statement = 100;
  SELECT pg_reload_conf();
"

# View slow queries
docker compose logs postgres | grep duration
```

### React Performance

Use React DevTools Profiler:

1. Open React DevTools
2. Go to "Profiler" tab
3. Click "Record"
4. Perform action
5. Click "Stop"
6. Analyze flame graph

Look for:

- Components re-rendering unnecessarily
- Expensive computations in render
- Missing memoization

### Memory Leaks

```typescript
// Watch for growing heap
setInterval(() => {
  const used = process.memoryUsage();
  console.log({
    heapUsed: Math.round(used.heapUsed / 1024 / 1024) + 'MB',
    heapTotal: Math.round(used.heapTotal / 1024 / 1024) + 'MB',
  });
}, 10000);
```

For React, check for:

- Uncleared intervals/timeouts
- Event listeners not removed
- Subscriptions not unsubscribed

```typescript
useEffect(() => {
  const interval = setInterval(fetchData, 5000);
  return () => clearInterval(interval); // Cleanup!
}, []);
```

---

## Logging

### Structured Logging

```typescript
import { logger } from '@yemaya/core';

// Log levels: debug, info, warn, error
logger.info('User logged in', {
  userId: user.id,
  email: user.email,
  method: 'password',
});

logger.error('Failed to process upload', {
  error: err.message,
  stack: err.stack,
  fileId,
  userId,
});
```

### Log Output Format

Development (pretty):

```
2024-01-15T10:30:00.000Z INFO  User logged in
  userId: usr_abc123
  email: user@example.com
```

Production (JSON):

```json
{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "level": "info",
  "message": "User logged in",
  "userId": "usr_abc123",
  "email": "user@example.com"
}
```

### Log Filtering

```bash
# Filter by level
LOG_LEVEL=warn pnpm --filter @yemaya/api dev

# Filter by module (using DEBUG)
DEBUG=yemaya:auth,yemaya:database pnpm --filter @yemaya/api dev
```

---

## Tools and Techniques

### Interactive REPL

```bash
# Start Node REPL with project loaded
node --experimental-repl-await

# Then import modules
> const { db } = await import('@yemaya/database')
> const users = await db.user.findMany({ take: 5 })
```

### Postman/Insomnia

Import OpenAPI spec for easy API testing:

```bash
# Export OpenAPI spec
curl http://localhost:3000/openapi.json > openapi.json
```

Then import into Postman or Insomnia.

### Database GUI

- **TablePlus**: Clean interface for PostgreSQL
- **DBeaver**: Free, cross-platform
- **pgAdmin**: Official PostgreSQL tool

### Network Debugging

```bash
# Capture network traffic
sudo tcpdump -i lo0 port 3000 -w capture.pcap

# Analyze with Wireshark
wireshark capture.pcap
```

### Git Bisect

Find the commit that introduced a bug:

```bash
# Start bisecting
git bisect start

# Mark current commit as bad
git bisect bad

# Mark known good commit
git bisect good v1.0.0

# Git checks out a commit - test it
pnpm test

# Mark result and continue
git bisect good  # or git bisect bad

# When done
git bisect reset
```

---

## Getting Help

If you're stuck:

1. **Search existing issues** on GitHub
2. **Check the FAQ** in docs
3. **Ask in Discord** #help channel
4. **Create a GitHub issue** with:
   - Steps to reproduce
   - Expected behavior
   - Actual behavior
   - Environment details
   - Relevant logs

Include debug output:

```bash
# Gather environment info
node -v
pnpm -v
docker --version
cat .env | grep -v KEY | grep -v SECRET
```
