# Contributing to BuzzTrail Video Extension

Thank you for contributing to the BuzzTrail Video Extension project! This document provides guidelines and standards for contributing code to this monorepo.

## Table of Contents

- [Code Quality Standards](#code-quality-standards)
- [Lint Standards](#lint-standards)
- [Development Workflow](#development-workflow)
- [Commit Guidelines](#commit-guidelines)
- [Pull Request Process](#pull-request-process)

## Code Quality Standards

### Zero Tolerance Policy

All code must pass quality checks with **0 errors and 0 warnings**:

- ✅ ESLint: 0 errors, 0 warnings
- ✅ TypeScript: 0 compilation errors
- ✅ Tests: All tests passing (no regressions)
- ✅ Python (Ruff): 0 errors for production code

### Automated Enforcement

Quality standards are automatically enforced at two levels:

1. **Pre-commit hooks** (Husky): Run checks on staged files before commit
   - TypeScript type checking
   - ESLint type-aware linting
   - Python linting (Ruff) for affected Python files

2. **CI/CD pipeline**: All pull requests must pass CI checks before merge
   - Full type checking across affected projects
   - Full linting with `--max-warnings=0`
   - Test suite execution
   - Production builds

## Lint Standards

### ESLint Configuration

Our ESLint configuration enforces strict quality and safety rules:

#### Critical Rules (Errors)

**Type Safety**:
- `@typescript-eslint/no-explicit-any`: Prevent use of `any` type (use proper types or `unknown`)
- `@typescript-eslint/no-unused-vars`: Remove dead code and unused imports
  - Exception: Variables prefixed with `_` (e.g., `_unusedParam`)

**Async Bug Prevention** (P0 - Critical):
- `@typescript-eslint/no-floating-promises`: All promises must be awaited or voided
- `@typescript-eslint/no-misused-promises`: Async functions in wrong contexts
- `@typescript-eslint/await-thenable`: Don't await non-promises

**Code Quality**:
- `no-template-curly-in-string`: Catch common template literal typos
- Standard TypeScript recommended rules

### Handling Lint Errors

If you encounter a lint error:

1. **Fix the root cause** (preferred)
   - Replace `any` with proper types
   - Add `void` operator for intentionally-unhandled promises
   - Remove unused variables or prefix with `_` if intentionally unused

2. **Understand the rule**
   - See [TYPE_SAFETY.md](docs/development/TYPE_SAFETY.md) for detailed explanations
   - Each rule exists to prevent bugs or improve code quality

3. **Need an exception?** (rare)
   - Add `eslint-disable-next-line` with **detailed justification**
   - Document in code why the exception is necessary

**Example**:
```typescript
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Third-party API returns unknown structure, documented in #123
function handleLegacyAPI(response: any) { ... }
```

### Common Patterns

#### 1. Replacing `any` Types

```typescript
// ❌ Bad
function process(data: any) { ... }

// ✅ Good - Use specific types
interface ProcessData {
  id: string;
  value: number;
}
function process(data: ProcessData) { ... }

// ✅ Good - Use unknown + type narrowing
function process(data: unknown) {
  if (isProcessData(data)) {
    // data is ProcessData here
  }
}

// ✅ Good - Generic objects
function process(data: Record<string, unknown>) { ... }
```

#### 2. Fixing Floating Promises

```typescript
// ❌ Bad - Promise ignored
async function handler() {
  riskyOperation(); // May throw, not handled
}

// ✅ Good - Promise awaited
async function handler() {
  await riskyOperation();
}

// ✅ Good - Promise voided (intentionally fire-and-forget)
async function handler() {
  void riskyOperation(); // Explicitly indicates we're not waiting
}
```

#### 3. Fixing Misused Promises in Event Handlers

```typescript
// ❌ Bad - Async function in non-async context
app.post('/api', async (req, res) => {
  await doWork();
  res.json({ ok: true });
});

// ✅ Good - IIFE pattern for Express/event handlers
app.post('/api', (req, res) => void (async () => {
  await doWork();
  res.json({ ok: true });
})());
```

#### 4. Unused Variables

```typescript
// ❌ Bad
function handler(req, res) {
  // res unused
  return req.body;
}

// ✅ Good - Prefix with underscore
function handler(req, _res) {
  return req.body;
}
```

## Development Workflow

### Initial Setup

```bash
# Install dependencies
pnpm install

# Verify setup
pnpm nx run-many --target=lint --all
pnpm nx run-many --target=typecheck --all
```

### Before Committing

Pre-commit hooks will automatically run, but you can manually check:

```bash
# Lint affected projects
pnpm nx affected -t lint --base=HEAD~1

# Type check affected projects
pnpm nx affected -t typecheck --base=HEAD~1

# Run tests for affected projects
pnpm nx affected -t test --base=HEAD~1
```

### Bypassing Hooks (Emergency Only)

```bash
# Only use in emergencies (hotfix, etc.)
git commit --no-verify -m "hotfix: critical production issue"
```

**Warning**: CI will still block merge if quality checks fail.

## Commit Guidelines

### Commit Message Format

```
<type>(<scope>): <subject>

<body>

<footer>
```

**Types**:
- `feat`: New feature
- `fix`: Bug fix
- `refactor`: Code refactoring (no behavior change)
- `docs`: Documentation updates
- `test`: Test updates
- `chore`: Build/tooling updates
- `style`: Code style changes (formatting, etc.)

**Examples**:
```
feat(slide-system): Add deck generation with AI summaries

Implement new /generate endpoint that creates Slidev decks from
conversation transcripts using OpenAI summarization.

Issue: #123
```

```
fix(voice-demo-ui): Resolve race condition in Daily.co call cleanup

Add proper async handling to prevent floating promises during
call termination. Fixes intermittent errors in CI.

Issue: #456
```

### Commit Best Practices

- Write descriptive commit messages
- Reference related issues with `Issue: #123`
- Keep commits focused and atomic
- All commits must pass pre-commit hooks (or use `--no-verify` with justification)

## Pull Request Process

### Before Opening a PR

1. **Ensure all quality checks pass locally**:
   ```bash
   pnpm nx run-many --target=lint --all --max-warnings=0
   pnpm nx run-many --target=typecheck --all
   pnpm nx run-many --target=test --all
   ```

2. **Verify production builds** (if affected):
   ```bash
   pnpm nx build slide-system --configuration=production
   pnpm nx build voice-demo-ui --configuration=production
   ```

3. **Update documentation** if needed

### PR Requirements

All PRs must:

- ✅ Pass all CI checks (lint, typecheck, test, build)
- ✅ Have descriptive title and description
- ✅ Reference related issues
- ✅ Include tests for new features
- ✅ Update documentation for user-facing changes
- ✅ Have at least one approving review

### PR Template

```markdown
## Description
Brief description of changes

## Related Issues
Fixes #123
Related to #456

## Changes
- Bullet list of key changes

## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests pass
- [ ] Manual testing completed

## Checklist
- [ ] Code follows project standards
- [ ] Documentation updated
- [ ] All CI checks passing
- [ ] Breaking changes documented (if any)
```

## Questions or Issues?

- Review [TYPE_SAFETY.md](docs/development/TYPE_SAFETY.md) for lint rule explanations
- Check [GitHub Issues](https://github.com/BuzzTrail/video-extension/issues) for known issues
- Reach out to maintainers for guidance

---

**Last Updated**: 2025-10-20 (Issue #158 - CI/CD & Hook Verification)
