# Contributing to Mosaic Stack

Thank you for your interest in contributing to Mosaic Stack! This document provides guidelines and processes for contributing effectively.

## Table of Contents

- [Development Environment Setup](#development-environment-setup)
- [Code Style Guidelines](#code-style-guidelines)
- [Branch Naming Conventions](#branch-naming-conventions)
- [Commit Message Format](#commit-message-format)
- [Pull Request Process](#pull-request-process)
- [Testing Requirements](#testing-requirements)
- [Where to Ask Questions](#where-to-ask-questions)

## Development Environment Setup

### Prerequisites

- **Node.js:** 20.0.0 or higher
- **pnpm:** 10.19.0 or higher (package manager)
- **Docker:** 20.10+ and Docker Compose 2.x+ (for database services)
- **Git:** 2.30+ for version control

### Installation Steps

1. **Clone the repository**

   ```bash
   git clone https://git.mosaicstack.dev/mosaic/stack mosaic-stack
   cd mosaic-stack
   ```

2. **Install dependencies**

   ```bash
   pnpm install
   ```

3. **Set up environment variables**

   ```bash
   cp .env.example .env
   # Edit .env with your configuration
   ```

   Key variables to configure:
   - `DATABASE_URL` - PostgreSQL connection string
   - `OIDC_ISSUER` - Authentik OIDC issuer URL
   - `OIDC_CLIENT_ID` - OAuth client ID
   - `OIDC_CLIENT_SECRET` - OAuth client secret
   - `JWT_SECRET` - Random secret for session tokens

4. **Initialize the database**

   ```bash
   # Start Docker services (PostgreSQL, Valkey)
   docker compose up -d

   # Generate Prisma client
   pnpm prisma:generate

   # Run migrations
   pnpm prisma:migrate

   # Seed development data (optional)
   pnpm prisma:seed
   ```

5. **Start development servers**

   ```bash
   pnpm dev
   ```

   This starts all services:
   - Web: http://localhost:3000
   - API: http://localhost:3001

### Quick Reference Commands

| Command                  | Description                   |
| ------------------------ | ----------------------------- |
| `pnpm dev`               | Start all development servers |
| `pnpm dev:api`           | Start API only                |
| `pnpm dev:web`           | Start Web only                |
| `docker compose up -d`   | Start Docker services         |
| `docker compose logs -f` | View Docker logs              |
| `pnpm prisma:studio`     | Open Prisma Studio GUI        |
| `make help`              | View all available commands   |

## Code Style Guidelines

Mosaic Stack follows strict code style guidelines to maintain consistency and quality. For comprehensive guidelines, see [CLAUDE.md](./CLAUDE.md).

### Formatting

We use **Prettier** for consistent code formatting:

- **Semicolons:** Required
- **Quotes:** Double quotes (`"`)
- **Indentation:** 2 spaces
- **Trailing commas:** ES5 compatible
- **Line width:** 100 characters
- **End of line:** LF (Unix style)

Run the formatter:

```bash
pnpm format          # Format all files
pnpm format:check    # Check formatting without changes
```

### Linting

We use **ESLint** for code quality checks:

```bash
pnpm lint            # Run linter
pnpm lint:fix        # Auto-fix linting issues
```

### TypeScript

All code must be **strictly typed** TypeScript:

- No `any` types allowed
- Explicit type annotations for function returns
- Interfaces over type aliases for object shapes
- Use shared types from `@mosaic/shared` package

### PDA-Friendly Design (NON-NEGOTIABLE)

**Never** use demanding or stressful language in UI text:

| ❌ AVOID    | ✅ INSTEAD           |
| ----------- | -------------------- |
| OVERDUE     | Target passed        |
| URGENT      | Approaching target   |
| MUST DO     | Scheduled for        |
| CRITICAL    | High priority        |
| YOU NEED TO | Consider / Option to |
| REQUIRED    | Recommended          |

See [docs/3-architecture/3-design-principles/1-pda-friendly.md](./docs/3-architecture/3-design-principles/1-pda-friendly.md) for complete design principles.

## Branch Naming Conventions

We follow a Git-based workflow with the following branch types:

### Branch Types

| Prefix      | Purpose           | Example                      |
| ----------- | ----------------- | ---------------------------- |
| `feature/`  | New features      | `feature/42-user-dashboard`  |
| `fix/`      | Bug fixes         | `fix/123-auth-redirect`      |
| `docs/`     | Documentation     | `docs/contributing`          |
| `refactor/` | Code refactoring  | `refactor/prisma-queries`    |
| `test/`     | Test-only changes | `test/coverage-improvements` |

### Workflow

1. Always branch from `develop`
2. Merge back to `develop` via pull request
3. `main` is for stable releases only

```bash
# Start a new feature
git checkout develop
git pull --rebase
git checkout -b feature/my-feature-name

# Make your changes
# ...

# Commit and push
git push origin feature/my-feature-name
```

## Commit Message Format

We use **Conventional Commits** for clear, structured commit messages:

### Format

```
<type>(#issue): Brief description

Detailed explanation (optional).

References: #123
```

### Types

| Type       | Description                             |
| ---------- | --------------------------------------- |
| `feat`     | New feature                             |
| `fix`      | Bug fix                                 |
| `docs`     | Documentation changes                   |
| `test`     | Adding or updating tests                |
| `refactor` | Code refactoring (no functional change) |
| `chore`    | Maintenance tasks, dependencies         |

### Examples

```bash
feat(#42): add user dashboard widget

Implements the dashboard widget with task and event summary cards.
Responsive design with PDA-friendly language.

fix(#123): resolve auth redirect loop

Fixed OIDC token refresh causing redirect loops on session expiry.
refactor(#45): extract database query utilities

Moved duplicate query logic to shared utilities package.
test(#67): add coverage for activity service

Added unit tests for all activity service methods.
docs: update API documentation for endpoints

Clarified pagination and filtering parameters.
```

### Commit Guidelines

- Keep the subject line under 72 characters
- Use imperative mood ("add" not "added" or "adds")
- Reference issue numbers when applicable
- Group related commits before creating PR

## Pull Request Process

### Before Creating a PR

1. **Ensure tests pass**

   ```bash
   pnpm test
   pnpm build
   ```

2. **Check code coverage** (minimum 85%)

   ```bash
   pnpm test:coverage
   ```

3. **Format and lint**

   ```bash
   pnpm format
   pnpm lint
   ```

4. **Update documentation** if needed
   - API docs in `docs/4-api/`
   - Architecture docs in `docs/3-architecture/`

### Creating a Pull Request

1. Push your branch to the remote

   ```bash
   git push origin feature/my-feature
   ```

2. Create a PR via GitLab at:
   https://git.mosaicstack.dev/mosaic/stack/-/merge_requests

3. Target branch: `develop`

4. Fill in the PR template:
   - **Title:** `feat(#issue): Brief description` (follows commit format)
   - **Description:** Summary of changes, testing done, and any breaking changes

5. Link related issues using `Closes #123` or `References #123`

### PR Review Process

- **Automated checks:** CI runs tests, linting, and coverage
- **Code review:** At least one maintainer approval required
- **Feedback cycle:** Address review comments and push updates
- **Merge:** Maintainers merge after approval and checks pass

### Merge Guidelines

- **Rebase commits** before merging (keep history clean)
- **Squash** small fix commits into the main feature commit
- **Delete feature branch** after merge
- **Update milestone** if applicable

## Testing Requirements

### Test-Driven Development (TDD)

**All new code must follow TDD principles.** This is non-negotiable.

#### TDD Workflow: Red-Green-Refactor

1. **RED** - Write a failing test first

   ```bash
   # Write test for new functionality
   pnpm test:watch  # Watch it fail
   git add feature.test.ts
   git commit -m "test(#42): add test for getUserById"
   ```

2. **GREEN** - Write minimal code to pass the test

   ```bash
   # Implement just enough to pass
   pnpm test:watch  # Watch it pass
   git add feature.ts
   git commit -m "feat(#42): implement getUserById"
   ```

3. **REFACTOR** - Clean up while keeping tests green
   ```bash
   # Improve code quality
   pnpm test:watch  # Ensure still passing
   git add feature.ts
   git commit -m "refactor(#42): extract user mapping logic"
   ```

### Coverage Requirements

- **Minimum 85% code coverage** for all new code
- **Write tests BEFORE implementation** — no exceptions
- Test files co-located with source:
  - `feature.service.ts` → `feature.service.spec.ts`
  - `component.tsx` → `component.test.tsx`

### Test Types

| Type                  | Purpose                                 | Tool       |
| --------------------- | --------------------------------------- | ---------- |
| **Unit tests**        | Test functions/methods in isolation     | Vitest     |
| **Integration tests** | Test module interactions (service + DB) | Vitest     |
| **E2E tests**         | Test complete user workflows            | Playwright |

### Running Tests

```bash
pnpm test              # Run all tests
pnpm test:watch        # Watch mode for TDD
pnpm test:coverage     # Generate coverage report
pnpm test:api          # API tests only
pnpm test:web          # Web tests only
pnpm test:e2e          # Playwright E2E tests
```

### Coverage Verification

After implementation:

```bash
pnpm test:coverage
# Open coverage/index.html in browser
# Verify your files show ≥85% coverage
```

### Test Guidelines

- **Descriptive names:** `it("should return user when valid token provided")`
- **Group related tests:** Use `describe()` blocks
- **Mock external dependencies:** Database, APIs, file system
- **Avoid implementation details:** Test behavior, not internals

## Where to Ask Questions

### Issue Tracker

All questions, bug reports, and feature requests go through the issue tracker:
https://git.mosaicstack.dev/mosaic/stack/issues

### Issue Labels

| Category | Labels                                                                        |
| -------- | ----------------------------------------------------------------------------- |
| Priority | `p0` (critical), `p1` (high), `p2` (medium), `p3` (low)                       |
| Type     | `api`, `web`, `database`, `auth`, `plugin`, `ai`, `devops`, `docs`, `testing` |
| Status   | `todo`, `in-progress`, `review`, `blocked`, `done`                            |

### Documentation

Check existing documentation first:

- [README.md](./README.md) - Project overview
- [CLAUDE.md](./CLAUDE.md) - Comprehensive development guidelines
- [docs/](./docs/) - Full documentation suite

### Getting Help

1. **Search existing issues** - Your question may already be answered
2. **Create an issue** with:
   - Clear title and description
   - Steps to reproduce (for bugs)
   - Expected vs actual behavior
   - Environment details (Node version, OS, etc.)

### Communication Channels

- **Issues:** For bugs, features, and questions (primary channel)
- **Pull Requests:** For code review and collaboration
- **Documentation:** For clarifications and improvements

---

**Thank you for contributing to Mosaic Stack!** Every contribution helps make this platform better for everyone.

For more details, see:

- [Project README](./README.md)
- [Development Guidelines](./CLAUDE.md)
- [API Documentation](./docs/4-api/)
- [Architecture](./docs/3-architecture/)
