# Agent Coding Guidelines for Jomblo

## Build, Lint & Test Commands

```bash
# Development
pnpm dev              # Start dev server
pnpm build            # Production build
pnpm start            # Start production server

# Linting & Type Checking
pnpm lint             # ESLint check
pnpm typecheck        # TypeScript type checking (tsc --noEmit)

# Testing (Single Test Focus)
pnpm test             # Run all Vitest tests once
pnpm test:ui          # Run tests in UI mode
pnpm test:watch       # Run tests in watch mode
pnpm test -- path/to/file.test.ts     # Run single test file
pnpm vitest run path/to/file.test.ts # Alternative syntax

# Test Categories
pnpm test:unit        # Unit tests (node environment)
pnpm test:integration # Integration tests
pnpm test:component   # Component tests (jsdom environment)
pnpm test:e2e         # Playwright E2E tests
pnpm test:coverage    # Coverage report (100% threshold required)

# Database
pnpm db:generate      # Generate migration files
pnpm db:push          # Push schema changes
pnpm db:migrate       # Run migrations
pnpm db:studio        # Open Drizzle Studio
```

## Code Style Guidelines

### Imports
- Use `@/` path alias for project imports (e.g., `@/lib/db`, `@/lib/db/schemas/db`)
- Group imports: React/Next → External libs → Internal modules → Types
- No unused imports (ESLint enforced)
- Example:
```typescript
"use server";
import bcrypt from "bcryptjs";
import { db } from "@/lib/db";
import { UserSchema } from "@/lib/db/schemas/db";
import { User } from "@/types/db";
```

### Types & Naming
- **Interfaces**: PascalCase (e.g., `User`, `OrderItem`)
- **Type aliases**: PascalCase with `Type` suffix (e.g., `UserType`)
- **Schemas**: PascalCase with `Schema` suffix (e.g., `UserSchema`)
- **Zod inferred types**: Use `z.infer<typeof Schema>`
- **Safe variants**: Use `SafeUserSchema` for responses (removes sensitive fields)
- **Functions**: camelCase for utilities, PascalCase for React components
- **Files**: PascalCase for components (e.g., `UserCard.tsx`), camelCase for utilities (e.g., `auth-utils.ts`)
- **Constants**: UPPER_SNAKE_CASE for true constants

### Server Actions
- Always start with `"use server"` directive
- Use `async/await` with proper error handling
- Return standardized error format: `{ error?: string; code?: number; message?: string; data?: T }`
- Validate all inputs with Zod schemas before database operations
- Use `revalidatePath()` after mutations
- Wrap transactions with `BEGIN/COMMIT/ROLLBACK` for multi-step operations

### Error Handling
- Always catch and log errors with descriptive messages
- Use ZodError for validation errors (return 400 status)
- Database errors return 500 status
- Use transactions for related operations
- Release database clients in `finally` blocks

### Database (No ORM)
- Use `pg` Pool from `@/lib/db`
- Always validate inputs with Zod before querying
- Use parameterized queries (`$1`, `$2`) to prevent SQL injection
- Wrap queries in try-catch blocks
- Example pattern:
```typescript
const validatedId = UserSchema.pick({ id: true }).parse({ id });
const query = "SELECT * FROM users WHERE id = $1";
const { rows } = await db.query(query, [validatedId.id]);
```

### React Components
- Use functional components with TypeScript interfaces
- Props interface named `ComponentNameProps`
- Use shadcn/ui components from `@/components/ui/`
- Use `cn()` utility for className merging
- Support `asChild` pattern for composability
- Include loading states where applicable

### Zod Validation
- Define schemas in `schemas/db.ts` (database) and `schemas/api.ts` (API contracts)
- Use `.pick()` for partial validation
- Use `.partial()` for optional fields
- Use `.parse()` for runtime validation
- Safe variants strip sensitive data (passwords, etc.)

### Testing (100% Coverage Required)
- Unit tests: Co-located or in `tests/`
- Use Vitest with jsdom for components, node for utilities
- Mock external dependencies (db, Redis, Stripe)
- Test error paths and edge cases
- Coverage thresholds: 100% for lib/, actions/, schemas/
- Test file naming: `*.test.ts` or `*.test.tsx`

### Security
- No hardcoded secrets (use env vars)
- Use `bcryptjs` for password hashing (salt rounds: 10)
- Require admin for sensitive operations (`requireAdmin()`)
- Validate all inputs with Zod
- Use parameterized SQL queries only
- Check auth.ts for Auth.js v5 configuration

### Styling
- Use Tailwind CSS utility classes
- Use shadcn/ui design tokens (e.g., `bg-primary`, `text-primary-foreground`)
- Support dark mode via CSS variables
- Responsive design with Tailwind breakpoints
- Use `class-variance-authority` for component variants

## Opencode Agents & Skills

Das Projekt verwendet einen `.opencode/` Ordner mit spezialisierten Agents und Skills für automatisierte Code-Analyse und Qualitätssicherung.

### Verfügbare Agents (`.opencode/agents/`)

| Agent | Zweck |
|-------|-------|
| `tech-stack-detector.md` | Analysiert den Tech Stack aus package.json und Config-Dateien |
| `architecture-mapper.md` | Mapped die Next.js App Router Struktur und API-Organisation |
| `api-endpoint-mapper.md` | Dokumentiert alle API-Endpunkte und ihre Spezifikationen |
| `database-schema-analyzer.md` | Analysiert PostgreSQL Schema und Beziehungen |
| `zod-schema-validator.md` | Prüft Zod-Schemas auf Konsistenz und Vollständigkeit |
| `auth-security-auditor.md` | Auditiert Auth.js v5 Konfiguration und Sicherheit |
| `security-vulnerability-scanner.md` | Scannt auf Sicherheitslücken und Anti-Patterns |
| `zustand-store-analyzer.md` | Analysiert Zustand-State-Management |
| `shadcn-ui-inventory.md` | Inventarisiert alle shadcn/ui Komponenten |
| `vitest-test-inventory.md` | Analysiert Testabdeckung und Teststruktur |
| `playwright-e2e-tester.md` | Prüft E2E-Tests mit Playwright |
| `performance-profiler.md` | Identifiziert Performance-Bottlenecks |
| `accessibility-auditor.md` | Auditiert Accessibility (a11y) Compliance |
| `stripe-integration-tester.md` | Testet Stripe-Integration und Webhooks |
| `redis-cache-analyzer.md` | Analysiert Redis-Caching-Strategien |
| `environment-config-auditor.md` | Prüft Umgebungsvariablen und Konfiguration |
| `github-actions-analyzer.md` | Analysiert CI/CD-Pipelines |
| `typescript-strictness-checker.md` | Prüft TypeScript-Striktheit und Typensicherheit |
| `python-backend-mapper.md` | Mapped Python-Backend-Struktur (falls vorhanden) |
| `documentation-reviewer.md` | Überprüft Dokumentationsvollständigkeit |

### Verfügbare Skills (`.opencode/skills/`)

| Skill | Zweck |
|-------|-------|
| `architecture-analysis.md` | Next.js App Router Struktur und Route Groups |
| `code-analysis.md` | Core TypeScript/React Patterns und Best Practices |
| `tech-stack-verification.md` | Package.json Analyse und Dependency-Management |
| `api-analysis.md` | REST/GraphQL API Patterns und Dokumentation |
| `database-analysis.md` | PostgreSQL Schema-Design und Queries |
| `state-management-analysis.md` | Zustand/Context State Management Patterns |
| `ui-component-analysis.md` | shadcn/ui Komponenten-Patterns |
| `auth-analysis.md` | Auth.js v5 und Authentifizierungs-Patterns |
| `security-audit.md` | Sicherheits-Audits und Best Practices |
| `performance-analysis.md` | Performance-Optimierung und Profiling |
| `test-analysis.md` | Testing-Patterns (Vitest, Playwright) |
| `ci-cd-analysis.md` | CI/CD-Pipeline Analyse |

### Agent-Verwendung
Nutze so viele Agents/Sub-Agents wie möglich um recherchen zu begehen
Agents werden automatisch von opencode bei bestimmten Aufgaben geladen. Jeder Agent hat:
- **Beschreibung**: Was der Agent analysiert
- **Erforderliche Skills**: Welche Skills geladen werden müssen
- **Permissions**: Lese- und Schreibberechtigungen
- **Projekt-Kontext**: Spezifische Jomblo-Details

### Anti-Pattern Knowledge

Agents greifen auf Anti-Pattern Dokumentationen zu:
- `.jules/sentinel-context/ANTI_PATTERNS_BREADTH.md` - Quick reference
- `.jules/sentinel-context/ANTI_PATTERNS_DEPTH.md` - Detaillierte Analysen
