# Developer Onboarding Guide

Welcome to the Stratofusion development team! This guide will help you get set up and productive quickly.

---

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Initial Setup](#initial-setup)
3. [Development Workflow](#development-workflow)
4. [Project Structure](#project-structure)
5. [Key Concepts](#key-concepts)
6. [Billing & Subscription Features](#billing--subscription-features)
7. [Common Tasks](#common-tasks)
8. [Best Practices](#best-practices)
9. [Getting Help](#getting-help)

---

## Prerequisites

### Required Software

- **Node.js** - Version 18+ (LTS recommended).
- **pnpm** - Version 8+ (package manager).
- **Git** - Latest version.
- **PowerShell on Windows** - Default shell for repo work, PNPM, tests, and git.
- **Git Bash for Windows** - Required only for `.sh` scripts or POSIX-specific workflows; invoke it explicitly with `C:\Program Files\Git\bin\bash.exe`.
- **VS Code** - Recommended IDE (or your preferred editor).
- **Stripe CLI** - Recommended for local webhook testing.

### Recommended VS Code Extensions

- **ESLint** - Code linting.
- **Prettier** - Code formatting.
- **TypeScript** - Enhanced TypeScript support.
- **Tailwind CSS IntelliSense** - Tailwind class autocomplete.
- **GitLens** - Enhanced Git integration.

### Required Accounts

- **GitHub** - For code access.
- **Vercel** - For deployment (optional for local dev).
- **Clerk** - For authentication (get keys from team).
- **Cloud Service Developer Accounts**.
  - Google Cloud Console (for Google Drive API).
  - Microsoft Azure (for OneDrive API).
  - Dropbox Developer Portal.

---

## Initial Setup

### 1. Clone the Repository

```bash
git clone https://github.com/your-org/stratofusion.git
cd stratofusion
```

### 2. Verify The Native Shell And Install Dependencies

```powershell
pnpm env:guard
pnpm install
```

The guard fails when the repo is opened through WSL or a WSL-mounted path.

### 3. Bootstrap the Local rclone Binary on Windows

On Windows, local `fly-rclone` now expects a pinned repo-local binary at `fly-rclone/rclone.exe` instead of relying on a globally installed `rclone.exe`.

```bash
pnpm rclone:bootstrap
pnpm rclone:check
```

The bootstrap script reads the pinned `RCLONE_VERSION` directly from [fly-rclone/Dockerfile](../../fly-rclone/Dockerfile), downloads the matching upstream Windows zip, installs `fly-rclone/rclone.exe`, and verifies that local resolution points to that binary.

If you intentionally set `RCLONE_PATH` or `FLY_RCLONE_PATH`, `pnpm rclone:check` will flag that override because it bypasses the deterministic repo-local binary.

### 4. Set Up Environment Variables

Create `.env.local` file in the project root:

```bash
# Copy the main app template
cp .env.example.template .env.local

# Copy the Fly rclone template if you need the local service
cp fly-rclone/.env.example.template fly-rclone/.env
```

Edit `.env.local` with your credentials:

Review `public/docs/CREDENTIAL_ROTATION_CHECKLIST.md` before reusing any previously exposed secret.

`.env.local` is the local runtime source of truth. `.env.development` and `.env.production` are repo-side reference snapshots for the deployed environments and should not replace local values.

```bash
# App URLs
NEXT_PUBLIC_SITE_URL=http://localhost:3000
NEXT_PUBLIC_APP_URL=http://localhost:3000

# Database (local isolated Neon database)
DATABASE_URL=postgresql://username:password@hostname/stratofusion-local?sslmode=require

# OAuth Configuration
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REDIRECT_URI=http://localhost:3000/api/google
ONEDRIVE_CLIENT_ID=your_onedrive_client_id
ONEDRIVE_CLIENT_SECRET=your_onedrive_client_secret
ONEDRIVE_REDIRECT_URI=http://localhost:3000/api/onedrive
DROPBOX_CLIENT_ID=your_dropbox_client_id
DROPBOX_CLIENT_SECRET=your_dropbox_client_secret
DROPBOX_REDIRECT_URI=http://localhost:3000/api/dropbox

# Clerk Authentication
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_clerk_publishable_key
CLERK_SECRET_KEY=your_clerk_secret_key

# Optional role assignments (server-only)
ADMIN_USER_IDS=user_admin_clerk_id
DEV_USER_IDS=user_dev_clerk_id

# Stripe (test mode locally)
NEXT_PUBLIC_STRIPE_ENABLED=true
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_PRICE_ID_FREE=price_...
STRIPE_PRICE_ID_PRO=price_...
STRIPE_PRICE_ID_UNLIMITED=price_...

# Rclone Service (optional for local dev)
FLYIO_RCLONE_SERVICE_URL=http://127.0.0.1:3001
NEXT_PUBLIC_FLYIO_RCLONE_SERVICE_URL=http://127.0.0.1:3001

# Cron Secret
CRON_SECRET=generate-a-unique-local-secret

# Sentry (server-side)
SENTRY_DSN=https://examplePublicKey@o0.ingest.us.sentry.io/0
# Optional; defaults to NODE_ENV
SENTRY_ENVIRONMENT=development
# Optional; defaults to VERCEL_GIT_COMMIT_SHA on Vercel
SENTRY_RELEASE=
```

On Vercel deployments, server `console.error` logs are forwarded to Sentry and tagged with Vercel deployment metadata automatically.
Role assignments are also server-only. Do not add `NEXT_PUBLIC_ADMIN_USER_IDS` or `NEXT_PUBLIC_DEV_USER_IDS`; the client resolves the current user role through the server.

**Get credentials from:**

- Team lead or senior developer.
- Team password manager.
- Project documentation.

### 5. Set Up Database

```bash
# Push schema to the isolated local database
pnpm db:push

# Verify local environment isolation before starting the app
pnpm env:doctor:local

# (Optional) Open Drizzle Studio to view database
pnpm db:studio
```

Use the local environment only against `stratofusion-local`. Do not point `.env.local` at the dev or prod database.
`pnpm env:doctor:local` checks that `.env.local` is localhost-only and flags shared Clerk, Stripe, database, or provider configuration when compared against the repo's dev snapshots or a dev env file you pass via `--compare`.

### 6. Start Development Servers

**Terminal 1 - Next.js App:**

```bash
pnpm dev
```

**Terminal 2 - Rclone Service (optional):**

```bash
pnpm rclone:check
cd fly-rclone
node server.js
```

**Terminal 3 - Stripe webhook forwarding (optional, but recommended for billing work):**

```bash
stripe listen --forward-to localhost:3000/api/webhooks/stripe
```

### 7. Verify Setup

1. Open **http://localhost:3000** in your browser
2. Sign in with your test account
3. Connect a test cloud service
4. Browse files to verify everything works
5. Confirm OAuth callbacks stay on `localhost`

✅ You're ready to develop!

---

## Development Workflow

### Daily Workflow

1. **Pull latest changes**

   ```bash
   git pull origin dev
   ```

2. **Create a feature branch from `dev`**

   ```bash
   git checkout dev
   git checkout -b feature/your-feature-name
   ```

3. **Make changes and test**

   ```bash
   pnpm dev          # Start dev server
   pnpm test:watch   # Run tests in watch mode
   ```

4. **Run quality checks**

   ```bash
   pnpm check        # Runs lint + typecheck
   pnpm test         # Run all tests
   ```

5. **Commit changes**

   ```bash
   git add .
   git commit -m "feat: your feature description"
   ```

6. **Push and create PR**
   ```bash
   git push origin feature/your-feature-name
   # Create PR on GitHub
   ```

### Pre-Commit Checklist

Before committing, always run:

```bash
pnpm check        # Lint + TypeScript check
pnpm test         # All tests
pnpm format:write # Format code
```

---

## Project Structure

### Key Directories

```
stratofusion/
├── src/
│   ├── app/                # Next.js App Router (pages and API routes)
│   ├── components/         # React UI components
│   ├── contexts/           # State management contexts
│   ├── hooks/              # Custom React hooks
│   ├── infrastructure/     # Adapters for external infra (e.g., rclone)
│   ├── shared/             # Application-wide validation, builders, and errors
│   ├── services/           # Implementation logic
│   │   ├── adapters/       # Port implementations for cloud providers
│   │   └── base/           # Base service abstractions
│   ├── types/              # Domain ports and common type definitions
│   └── lib/                # General utility functions
├── public/                 # Static assets and Markdown docs
├── fly-rclone/             # Specialized transfer microservice
└── tests/                  # Mirror of src/ structure for testing
```

### Important Files

- **`AGENTS.md`** - AI assistant and repo operating protocol.
- **`README.md`** - Project overview.
- **`TASKS.md`** - Current tasks and TODOs.
- **`package.json`** - Dependencies and scripts.
- **`.env.local`** - Local environment variables (not committed).

---

## Key Concepts

### Service Abstraction Layer (Ports & Adapters)

The application follows a Ports & Adapters (Hexagonal) architecture. This separates our core application logic from external service providers.

- **Ports**: Defined in `src/types/cloud-storage.ts`, these describe _what_ our application can do (e.g., `CloudStoragePort`).
- **Adapters**: Found in `src/services/adapters/`, these are concrete implementations that describe _how_ we talk to Google Drive, OneDrive, etc.

**Key Architecture Files:**

- `src/types/cloud-storage.ts` - Domain Port definitions.
- `src/services/adapters/` - Provider-specific and cross-cutting adapters.
- `src/shared/` - Centralized validation and error handling logic.

### Data Flow Pattern

```
Component → Hook → API Route → Port (Interface) → Adapter (Implementation) → Cloud Provider API
```

**Example:**

```typescript
// 1. Component uses hook
const { files, loading } = useDriveFiles(service, accountId, folderId);
```

_Note: API routes now leverage shared builders and validation from `src/shared` for consistency._

### State Management

- **ServiceManagerContext** - Global service state.
- **FileSelectionContext** - File selection state.
- **DriveNavigationContext** - Navigation state.
- **Custom hooks** - Feature-specific state logic.

---

## Billing & Subscription Features

### Key Components

- `src/components/billing/BillingSettingsContent.tsx` - Main billing settings experience.
- `src/components/billing/ManageSubscriptionButton.tsx` - Stripe Billing Portal access.
- `src/components/billing/UpgradeButton.tsx` - Stripe Checkout entry point.
- `src/lib/stripe/billing-summary.ts` - Payment method summary lookup.
- `src/contexts/SubscriptionContext.tsx` - Subscription tier, status, and feature availability.

### Search Gating

- `src/components/search/EnhancedSearchInput.tsx` - Inline upgrade prompts for gated search modes.
- `src/components/search/SearchModeSelector.tsx` - Search mode selection and billing CTA entry point.
- `src/lib/subscription.ts` - Tier capabilities and search-mode availability.

### Navigation

- `src/components/Header.tsx` - Header integration for subscription-aware navigation.
- `src/components/SettingsMenu.tsx` - Role-aware settings dropdown for dashboard, billing, jobs, and activity links.
- `src/app/user/settings/page.tsx` - Settings route in the authenticated user area.
- `src/app/user/billing/page.tsx` - Billing route in the authenticated user area.

---

## Common Tasks

### Adding a New Component

1. **Create component file**

   ```bash
   # For UI components
   src/components/ui/MyComponent.tsx

   # For feature components
   src/components/MyFeatureComponent.tsx
   ```

2. **Create Storybook story**

   ```bash
   src/components/ui/MyComponent.stories.tsx
   ```

3. **Create tests**

   ```bash
   src/components/ui/MyComponent.test.tsx
   ```

4. **Export from index** (if needed)
   ```typescript
   // src/components/ui/index.ts
   export { MyComponent } from "./MyComponent";
   ```

### Adding a New API Route

1. **Create route file**

   ```bash
   src/app/api/my-endpoint/route.ts
   ```

2. **Implement handler**

   ```typescript
   import {
     createSuccessResponse,
     createErrorResponse,
   } from "~/lib/api-response";

   export async function GET(request: Request) {
     try {
       const data = await fetchData();
       return createSuccessResponse(data);
     } catch (error) {
       return createErrorResponse(error);
     }
   }
   ```

3. **Add tests**
   ```bash
   src/app/api/my-endpoint/route.test.ts
   ```

### Adding a New Cloud Service

See [ARCHITECTURE.md](ARCHITECTURE.md#adding-new-cloud-services) for detailed instructions.

### Running Tests

```bash
# Run all tests once
pnpm test

# Run tests in watch mode
pnpm test:watch

# Run tests with UI
pnpm test:ui

# Run tests with coverage
pnpm test:coverage
```

### Running Storybook

```bash
# Start Storybook dev server
pnpm storybook

# Build Storybook for deployment
pnpm build-storybook
```

---

## Best Practices

### Code Style

- **Use TypeScript** - No `any` types.
- **Follow ESLint rules** - Run `pnpm lint:fix`.
- **Format with Prettier** - Run `pnpm format:write`.
- **Prefix unused vars** - Use `_` prefix for unused variables.

### File Organization

- **Max 500 lines per file** - Split into modules if longer.
- **Group by feature** - Keep related code together.
- **Mirror test structure** - Tests should mirror src structure.

### Component Development

- **Atomic design** - Build from small to large components.
- **Story-driven** - Create Storybook stories for all components.
- **Accessibility first** - Use semantic HTML and ARIA labels.
- **Mobile-first** - Design for mobile, enhance for desktop.

### Testing

- **Write tests first** - TDD when possible.
- **Test behavior** - Not implementation details.
- **Use React Testing Library** - For component tests.
- **Mock external services** - Don't call real APIs in tests.

### Git Workflow

- **Small commits** - One logical change per commit.
- **Descriptive messages** - Use conventional commits format.
- **Feature branches** - Never commit directly to main.
- **PR reviews** - All code must be reviewed.

---

## Getting Help

### Documentation

- **[Architecture](ARCHITECTURE.md)** - System architecture.
- **[Testing](TESTING.md)** - Testing guidelines.
- **[Deployment](DEPLOYMENT.md)** - Deployment guides.
- **[Environment Separation Validation](ENVIRONMENT_SEPARATION_VALIDATION_2026-03-24.md)** - final rollout closeout.
- **[AI Operating Protocol](developer/AI_OPERATING_PROTOCOL.md)** - AI assistant guidelines.

### Team Resources

- **Slack** - #stratofusion-dev channel.
- **GitHub Discussions** - For longer discussions.
- **Weekly Standup** - Mondays at 10am.
- **Code Reviews** - Request reviews in PR.

### Common Issues

See [Troubleshooting](DEPLOYMENT.md#troubleshooting) in the deployment guide.

---

**Welcome to the team!** 🎉

---

**Last Updated:** 2026-03-24
**Estimated Setup Time:** 30-60 minutes
