# Development Workflow Guide

This guide covers the development workflow, coding standards, and contribution
process for the Lilith platform.

## Overview

The Lilith platform follows a structured development workflow with:

- Feature branching and pull request reviews
- Automated quality gates (lint, typecheck, security)
- 70% minimum code coverage requirement
- Conventional commit messages
- Comprehensive CI/CD pipelines

---

## Git Branching Strategy

### Branch Structure

```
main (production)
  │
  └── develop (integration)
        │
        ├── feature/TICKET-123-description
        ├── fix/TICKET-456-bug-description
        ├── docs/update-api-reference
        └── chore/update-dependencies
```

### Branch Naming Conventions

| Type          | Pattern                      | Example                                |
| ------------- | ---------------------------- | -------------------------------------- |
| Feature       | `feature/TICKET-description` | `feature/LIL-123-add-meditation-timer` |
| Bug Fix       | `fix/TICKET-description`     | `fix/LIL-456-auth-token-expiry`        |
| Documentation | `docs/description`           | `docs/update-api-versioning`           |
| Chore         | `chore/description`          | `chore/update-dependencies`            |
| Hotfix        | `hotfix/description`         | `hotfix/critical-security-patch`       |

### Branch Workflow

```bash
# 1. Create feature branch from develop
git checkout main
git pull origin main
git checkout -b feature/LIL-123-new-feature

# 2. Make changes and commit
git add .
git commit -m "feat(auth): add OAuth2 refresh token support"

# 3. Push and create PR
git push -u origin feature/LIL-123-new-feature
```

### Protected Branches

| Branch    | Protection                                   |
| --------- | -------------------------------------------- |
| `main`    | Requires PR, all status checks, 1+ approvals |
| `develop` | Requires PR, quality gates pass              |

---

## Pull Request Process

### Creating a Pull Request

1. **Ensure all checks pass locally**:

   ```bash
   npm run lint
   npm run typecheck
   npm run test
   npm run coverage:ci  # Must be ≥70%
   ```

2. **Push your branch** and create PR via GitHub

3. **Fill out the PR template** with:
   - Summary of changes
   - Related ticket/issue
   - Testing performed
   - Checklist completion

### PR Requirements Checklist

Before submitting:

- [ ] Lint, typecheck, and coverage pass locally
- [ ] OpenAPI validation passes (if API changes)
- [ ] New/changed endpoints reflected in `openapi/openapi.yaml`
- [ ] Added/updated tests for new behavior
- [ ] Tests are substantive (no placeholder/stub/skip-only)
- [ ] No secrets or credentials added
- [ ] Referenced ADRs when applicable

### Code Owners

PRs are automatically assigned reviewers based on file paths:

| Path          | Team                   |
| ------------- | ---------------------- |
| `services/**` | @lilith/backend-leads  |
| `web/**`      | @lilith/frontend-leads |
| `mobile/**`   | @lilith/mobile-leads   |
| `sdk/**`      | @lilith/sdk-leads      |
| `docs/**`     | @lilith/docs-team      |
| `openapi/**`  | @lilith/api-team       |
| `.github/**`  | @lilith/devops-leads   |

### Required Status Checks

All PRs must pass these automated checks:

| Check                                | Description               |
| ------------------------------------ | ------------------------- |
| `Quality Gates / lint`               | ESLint validation         |
| `Quality Gates / typecheck`          | TypeScript compilation    |
| `Quality Gates / format`             | Prettier formatting       |
| `Quality Gates / security-scan`      | npm audit (high severity) |
| `Quality Gates / openapi-validation` | API spec consistency      |
| `CI / coverage-threshold`            | ≥70% code coverage        |
| `CI / integration-tests`             | Cross-service tests       |

### Review Guidelines

Reviewers should check:

1. **Code Quality**: Follows style guide, readable, maintainable
2. **Testing**: Adequate coverage, meaningful assertions
3. **Security**: No vulnerabilities, secrets, or injection risks
4. **Performance**: No obvious bottlenecks or N+1 queries
5. **Documentation**: Updated docs for API changes

---

## Code Style Guidelines

### ESLint Configuration

Key rules enforced:

```javascript
{
  // Quotes
  "quotes": ["error", "single", { "allowTemplateLiterals": true }],

  // Indentation
  "indent": ["error", 2],

  // No console (except warn/error)
  "no-console": ["warn", { "allow": ["warn", "error"] }],

  // Prefer const and arrow functions
  "prefer-const": "error",
  "prefer-arrow-callback": "error",

  // No var
  "no-var": "error",

  // Strict equality
  "eqeqeq": ["error", "always"],

  // Max complexity
  "complexity": ["warn", 15]
}
```

### Prettier Configuration

```json
{
  "semi": true,
  "trailingComma": "none",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "avoid",
  "endOfLine": "lf"
}
```

### TypeScript Standards

- Use ESM modules (`import`/`export`)
- Strict mode enabled
- Explicit return types for public functions
- No `any` without justification
- Use interfaces over type aliases for objects

### Code Style Examples

**Good**:

```typescript
// Single quotes, 2-space indent, arrow functions
const getUserById = async (id: string): Promise<User | null> => {
  const user = await db.users.findUnique({ where: { id } });
  return user;
};
```

**Bad**:

```typescript
// Double quotes, var, function keyword
var getUserById = async function (id) {
  var user = await db.users.findUnique({ where: { id } });
  return user;
};
```

---

## Commit Message Conventions

### Format

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

[optional body]

[optional footer]
```

### Types

| Type       | Description                |
| ---------- | -------------------------- |
| `feat`     | New feature                |
| `fix`      | Bug fix                    |
| `docs`     | Documentation only         |
| `style`    | Formatting, no code change |
| `refactor` | Code restructuring         |
| `perf`     | Performance improvement    |
| `test`     | Adding/updating tests      |
| `chore`    | Maintenance tasks          |

### Examples

```bash
# Feature
feat(auth): add WebAuthn passkey authentication

# Bug fix
fix(conversation): resolve message ordering in threads

# Documentation
docs: update API versioning guide

# Refactor
refactor(ai): extract LLM provider abstraction layer

# With body and footer
feat(meditation): add group meditation sessions

Implements real-time synchronization for group meditation
with WebRTC audio and shared timer state.

Closes #123
Ref: ADR-0005
```

### Commit Guidelines

- Keep commits scoped and focused
- Minimum 10 characters in message
- First line ≤100 characters
- Reference ADRs when applicable (e.g., `Ref: ADR-0007`)
- Include ticket/issue numbers

---

## Testing Requirements

### Coverage Requirements

| Metric     | Minimum |
| ---------- | ------- |
| Branches   | 70%     |
| Functions  | 70%     |
| Lines      | 70%     |
| Statements | 70%     |

### Test Commands

```bash
# Run all E2E tests
npm test

# Run with CI output
npm run test:ci

# Run service-specific tests
npm test --workspace services/auth

# Check coverage
npm run coverage:ci

# Run integration tests
npm run test:integration

# Run performance tests
npm run test:performance
```

### Testing Frameworks

| Type        | Framework        | Usage         |
| ----------- | ---------------- | ------------- |
| Unit Tests  | Jest             | Service logic |
| Integration | Jest + Supertest | API endpoints |
| E2E         | Playwright       | Full system   |
| Performance | k6               | Load testing  |

### Jest Configuration

```javascript
// jest.config.service.cjs
module.exports = {
  preset: 'ts-jest/presets/default-esm',
  testMatch: ['{__tests__,tests}/**/*.{test,spec}.{js,ts}'],
  testTimeout: 30000,
  coverageThreshold: {
    global: {
      branches: 70,
      functions: 70,
      lines: 70,
      statements: 70,
    },
  },
};
```

### Writing Good Tests

**Do**:

```typescript
describe('AuthService', () => {
  it('should return user when valid token provided', async () => {
    const token = await authService.createToken(testUser);
    const result = await authService.validateToken(token);

    expect(result.valid).toBe(true);
    expect(result.userId).toBe(testUser.id);
  });
});
```

**Don't**:

```typescript
// Empty or placeholder tests
it.skip('should work', () => {});

// Coverage-only tests
it('covers the function', () => {
  myFunction(); // No assertions!
});
```

### Test Best Practices

1. **Use `app.inject()` instead of `app.listen()`** for service tests
2. **No `test.skip`/`describe.skip`** without linked issues
3. **Meaningful assertions** - not just for coverage
4. **Isolate tests** - no shared state between tests
5. **Mock external services** - don't hit real APIs in tests

---

## CI/CD Pipeline

### Pipeline Stages

```
┌─────────────┐   ┌─────────────┐   ┌─────────────┐   ┌─────────────┐
│ Quality     │──►│ Unit Tests  │──►│ Integration │──►│ Security    │
│ Gates       │   │             │   │ Tests       │   │ Scan        │
└─────────────┘   └─────────────┘   └─────────────┘   └─────────────┘
       │                 │                 │                 │
       ▼                 ▼                 ▼                 ▼
┌─────────────┐   ┌─────────────┐   ┌─────────────┐   ┌─────────────┐
│ Build       │──►│ Container   │──►│ Performance │──►│ Publish     │
│ Services    │   │ Security    │   │ Tests       │   │ Images      │
└─────────────┘   └─────────────┘   └─────────────┘   └─────────────┘
```

### Quality Gates (Run on Every PR)

| Gate      | Tool       | Threshold       |
| --------- | ---------- | --------------- |
| Lint      | ESLint     | 0 errors        |
| Typecheck | TypeScript | 0 errors        |
| Format    | Prettier   | 0 violations    |
| Security  | npm audit  | 0 high severity |
| OpenAPI   | Spectral   | 0 errors        |

### Automated Checks

**Pre-commit Hooks** (via Husky):

1. Secrets scanning
2. License header validation
3. Incremental linting (`lint-staged`)
4. Performance SLA check
5. TypeScript type checking

### Container Publishing

Published to GitHub Container Registry (ghcr.io):

- `auth`, `bff`, `content`, `conversation`
- `ai`, `moderation`, `media`, `notification`
- `rag`, `metaverse`

---

## Development Workflow Summary

### Daily Development

```bash
# 1. Sync with develop
git checkout main && git pull

# 2. Create feature branch
git checkout -b feature/LIL-123-my-feature

# 3. Develop in service directory
cd services/conversation
npm install
npm start  # or npm test

# 4. Run quality checks
npm run lint
npm run typecheck
npm run coverage:ci

# 5. Commit with conventional message
git add .
git commit -m "feat(conversation): add thread archiving"

# 6. Push and create PR
git push -u origin feature/LIL-123-my-feature
```

### Before Submitting PR

```bash
# Run all quality gates
npm run lint
npm run typecheck
npm run openapi:validate

# Check coverage (must be ≥70%)
npm run coverage:ci

# Run tests
npm test
```

### Fast Path Development

For rapid iteration on a single service:

```bash
cd services/auth
npm install
npm test  # Uses app.inject(), no containers needed
```

### Full Stack Development

For cross-service testing:

```bash
npm run deploy           # Start all services
npm run health:wait      # Wait for health
npm run seed:dev         # Seed test data
npm test                 # Run E2E tests
```

---

## Architecture Decision Records (ADRs)

Reference ADRs in commits and PRs when relevant:

| ADR      | Topic                              |
| -------- | ---------------------------------- |
| ADR-0001 | Fastify Microservices Architecture |
| ADR-0002 | Deployment Strategy                |
| ADR-0003 | Stub Services Remediation          |
| ADR-0004 | Token Service Consolidation        |
| ADR-0005 | Meditation Service Consolidation   |
| ADR-0006 | Transaction Service Consolidation  |
| ADR-0007 | Service Interaction Patterns       |
| ADR-0008 | Web3 Services Phase 3 Deferral     |

**Location**: `docs/adr/`

---

## Related Documentation

- [Local Development Setup](./local-development-setup.md)
- [System Architecture](../architecture/system-architecture.md)
- [CONTRIBUTING.md](../../CONTRIBUTING.md)
- [CLAUDE.md](../../CLAUDE.md) - AI development guidelines
