⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
docs: update backend API guidelines
Andrej Acevski5da5d1245823
diff --git a/.cursor/rules/backend-api.mdc b/.cursor/rules/backend-api.mdcindex c3de3883f..daa28da27 100644--- a/.cursor/rules/backend-api.mdc+++ b/.cursor/rules/backend-api.mdc@@ -1,56 +1,247 @@----description:-globs:+description: Backend API development guidelines for Hono, Drizzle ORM, and Better Auth+globs: apps/api/**/*alwaysApply: false----# Backend API Structure and Patterns+# Backend API Guidelines-The backend API is located in [apps/api/](mdc:apps/api) and follows a modular, domain-driven architecture.+The Kaneo API is built with Hono, Drizzle ORM, PostgreSQL, and Better Auth. This document outlines conventions and patterns for backend development.-## Project Structure+## Framework: Hono-### Core Files-- **Entry Point**: [apps/api/src/index.ts](mdc:apps/api/src/index.ts) - Main Hono application setup-- **Database**: [apps/api/src/database/index.ts](mdc:apps/api/src/database/index.ts) - Database connection-- **Schema**: [apps/api/src/database/schema.ts](mdc:apps/api/src/database/schema.ts) - Drizzle ORM schema definitions-- **Config**: [apps/api/src/config/index.ts](mdc:apps/api/src/config/index.ts) - Environment configuration+Hono is a lightweight web framework. Follow these patterns:-### Domain Modules+### Route Structure-Each domain follows the same structure pattern with `controllers/` and `index.ts`:+Routes are organized by feature in `apps/api/src/`:-- **Activity**: [apps/api/src/activity/](mdc:apps/api/src/activity) - Activity tracking and comments-- **Task**: [apps/api/src/task/](mdc:apps/api/src/task) - Task management (CRUD, updates, exports)-- **Project**: [apps/api/src/project/](mdc:apps/api/src/project) - Project management-- **Workspace**: [apps/api/src/workspace/](mdc:apps/api/src/workspace) - Workspace management-- **User**: [apps/api/src/user/](mdc:apps/api/src/user) - Authentication and user management-- **GitHub Integration**: [apps/api/src/github-integration/](mdc:apps/api/src/github-integration) - GitHub app integration-- **Time Entry**: [apps/api/src/time-entry/](mdc:apps/api/src/time-entry) - Time tracking-- **Notification**: [apps/api/src/notification/](mdc:apps/api/src/notification) - User notifications-- **Label**: [apps/api/src/label/](mdc:apps/api/src/label) - Task labeling system+```typescript+// apps/api/src/task/index.ts+import { Hono } from "hono";+import { describeRoute, resolver, validator } from "hono-openapi";+import * as v from "valibot";+import createTask from "./controllers/create-task";+import getTask from "./controllers/get-task";-## Architecture Patterns+const task = new Hono<{+ Variables: {+ userId: string;+ };+}>()+ .get(+ "/:id",+ describeRoute({+ operationId: "getTask",+ tags: ["Tasks"],+ description: "Get a specific task by ID",+ responses: {+ 200: {+ description: "Task details",+ content: {+ "application/json": { schema: resolver(taskSchema) },+ },+ },+ },+ }),+ validator("param", v.object({ id: v.string() })),+ async (c) => {+ const { id } = c.req.valid("param");+ const task = await getTask(id);+ return c.json(task);+ },+ );-### Controller Pattern-Each domain has controllers in `controllers/` directory that handle HTTP requests:-- Controllers use Hono framework-- Follow naming convention: `{action}-{resource}.ts` (e.g., `create-task.ts`)-- Each controller exports a Hono route handler+export default task;+```-### Module Exports-Each domain has an [index.ts](mdc:apps/api/src/task/index.ts) that exports all controllers as Hono routes.+### Best Practices-### Authentication-- Auth middleware: [apps/api/src/middlewares/auth.ts](mdc:apps/api/src/middlewares/auth.ts)-- Session management in [apps/api/src/user/utils/](mdc:apps/api/src/user/utils)+1. **Always use OpenAPI decorators**: Use `describeRoute` for all endpoints+2. **Validate inputs**: Use `validator` with Valibot schemas+3. **Extract controllers**: Keep route handlers thin, move logic to controller files+4. **Type safety**: Use Hono's type system for context variables-### Database Migrations-- Located in [apps/api/drizzle/](mdc:apps/api/drizzle)-- Managed by Drizzle ORM-- Configuration: [apps/api/drizzle.config.ts](mdc:apps/api/drizzle.config.ts)+```typescript+// Good: Thin route handler+.get("/:id", validator("param", v.object({ id: v.string() })), async (c) => {+ const { id } = c.req.valid("param");+ const task = await getTask(id);+ return c.json(task);+})-## Key Utilities+// Bad: Business logic in route handler+.get("/:id", async (c) => {+ const id = c.req.param("id");+ const task = await db.select().from(taskTable).where(eq(taskTable.id, id));+ // ... more logic+ return c.json(task);+})+```-- **Demo Data**: [apps/api/src/utils/create-demo-user.ts](mdc:apps/api/src/utils/create-demo-user.ts)-- **Settings**: [apps/api/src/utils/get-settings.ts](mdc:apps/api/src/utils/get-settings.ts)-- **Events**: [apps/api/src/events/index.ts](mdc:apps/api/src/events/index.ts)+## Database: Drizzle ORM++### Schema Definition++Define schemas in `apps/api/src/database/schema.ts`:++```typescript+import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";+import { createId } from "@paralleldrive/cuid2";++export const taskTable = pgTable("task", {+ id: text("id")+ .$defaultFn(() => createId())+ .primaryKey(),+ title: text("title").notNull(),+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),+ updatedAt: timestamp("updated_at", { mode: "date" })+ .defaultNow()+ .$onUpdate(() => new Date())+ .notNull(),+});+```++### Best Practices++1. **Use CUID2 for IDs**: Always use `createId()` from `@paralleldrive/cuid2`+2. **Timestamps**: Always include `createdAt` and `updatedAt` with proper defaults+3. **Foreign Keys**: Use cascade deletes/updates where appropriate+4. **Indexes**: Add indexes for frequently queried columns++```typescript+// Good: Proper schema with indexes+export const taskTable = pgTable(+ "task",+ {+ id: text("id").$defaultFn(() => createId()).primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projectTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ // ...+ },+ (table) => [index("task_projectId_idx").on(table.projectId)],+);+```++### Migrations++1. **Generate migrations**: `pnpm --filter @kaneo/api db:generate`+2. **Run migrations**: Automatically on API startup (see `apps/api/src/index.ts`)+3. **Migration files**: Stored in `apps/api/drizzle/`++## Authentication: Better Auth++Better Auth handles authentication. Access user context via Hono variables:++```typescript+// User is available in context after auth middleware+const userId = c.get("userId");+const user = c.get("user");+const session = c.get("session");+```++### API Key Authentication++API keys are supported via Bearer token:++```typescript+// Middleware in apps/api/src/index.ts handles this+// Authorization: Bearer <api-key>+```++## Validation: Valibot++Use Valibot for request validation:++```typescript+import * as v from "valibot";++validator(+ "json",+ v.object({+ title: v.string(),+ description: v.optional(v.string()),+ dueDate: v.optional(v.string()),+ }),+)+```++## Controller Pattern++Controllers contain business logic and are imported into route files:++```typescript+// apps/api/src/task/controllers/get-task.ts+import db from "../../database";+import { taskTable } from "../../database/schema";+import { eq } from "drizzle-orm";++export default async function getTask(id: string) {+ const [task] = await db+ .select()+ .from(taskTable)+ .where(eq(taskTable.id, id));++ if (!task) {+ throw new HTTPException(404, { message: "Task not found" });+ }++ return task;+}+```++## Error Handling++Use Hono's HTTPException for errors:++```typescript+import { HTTPException } from "hono/http-exception";++if (!task) {+ throw new HTTPException(404, { message: "Task not found" });+}+```++## Events++Publish events for activity tracking:++```typescript+import { publishEvent } from "../events";++await publishEvent("task.status_changed", {+ taskId: task.id,+ userId: user,+ oldStatus: task.status,+ newStatus: status,+ title: task.title,+ type: "status_changed",+});+```++## File Organization++```+apps/api/src/+├── activity/ # Activity feature+│ ├── controllers/+│ └── index.ts+├── auth.ts # Better Auth configuration+├── config/ # Configuration endpoints+├── database/ # Database schema and connection+│ ├── schema.ts+│ ├── relations.ts+│ └── index.ts+├── events/ # Event publishing+├── task/ # Task feature+│ ├── controllers/+│ └── index.ts+└── index.ts # Main entry point+```++## CORS Configuration++CORS is configured in `apps/api/src/index.ts`. Set `CORS_ORIGINS` environment variable for production.diff --git a/.cursor/rules/cursor-rules.mdc b/.cursor/rules/cursor-rules.mdcnew file mode 100644index 000000000..774d83ff2--- /dev/null+++ b/.cursor/rules/cursor-rules.mdc@@ -0,0 +1,66 @@+---+description: How to add or edit Cursor rules in our project+globs:+alwaysApply: false+---+# Cursor Rules Location++How to add new cursor rules to the project++1. Always place rule files in PROJECT_ROOT/.cursor/rules/:+ ```+ .cursor/rules/+ ├── your-rule-name.mdc+ ├── another-rule.mdc+ └── ...+ ```++2. Follow the naming convention:+ - Use kebab-case for filenames+ - Always use .mdc extension+ - Make names descriptive of the rule's purpose++3. Directory structure:+ ```+ PROJECT_ROOT/+ ├── .cursor/+ │ └── rules/+ │ ├── your-rule-name.mdc+ │ └── ...+ └── ...+ ```++4. Never place rule files:+ - In the project root+ - In subdirectories outside .cursor/rules+ - In any other location++5. Cursor rules have the following structure:++````+---+description: Short description of the rule's purpose+globs: optional/path/pattern/**/*+alwaysApply: false+---+# Rule Title++Main content explaining the rule with markdown formatting.++1. Step-by-step instructions+2. Code examples+3. Guidelines++Example:+```typescript+// Good example+function goodExample() {+ // Implementation following guidelines+}++// Bad example+function badExample() {+ // Implementation not following guidelines+}+```+````\ No newline at end of filediff --git a/.cursor/rules/database-schema.mdc b/.cursor/rules/database-schema.mdcindex 1002d8c93..3c4f9ac35 100644--- a/.cursor/rules/database-schema.mdc+++ b/.cursor/rules/database-schema.mdc@@ -1,89 +1,294 @@----description:-globs:+description: Database schema conventions and patterns using Drizzle ORM and PostgreSQL+globs: apps/api/src/database/**/*alwaysApply: false----# Database Schema and Data Model+# Database Schema Guidelines-The application uses **PostgreSQL** with **Drizzle ORM** for type-safe database operations and migrations.+Kaneo uses Drizzle ORM with PostgreSQL. This document outlines schema conventions and best practices.-## Core Schema Files+## Schema Definition-- **Schema Definition**: [apps/api/src/database/schema.ts](mdc:apps/api/src/database/schema.ts) - All table definitions-- **Database Connection**: [apps/api/src/database/index.ts](mdc:apps/api/src/database/index.ts) - Database client setup-- **Migration Config**: [apps/api/drizzle.config.ts](mdc:apps/api/drizzle.config.ts) - Drizzle configuration+All schemas are defined in `apps/api/src/database/schema.ts`:-## Migration Management+```typescript+import { pgTable, text, timestamp, boolean, integer, index } from "drizzle-orm/pg-core";+import { createId } from "@paralleldrive/cuid2";-### Migration Files-- **Directory**: [apps/api/drizzle/](mdc:apps/api/drizzle) - Contains all migration files-- **Journal**: [apps/api/drizzle/meta/_journal.json](mdc:apps/api/drizzle/meta/_journal.json) - Migration tracking-- **Snapshots**: [apps/api/drizzle/meta/](mdc:apps/api/drizzle/meta) - Schema snapshots for each migration+export const taskTable = pgTable(+ "task",+ {+ id: text("id")+ .$defaultFn(() => createId())+ .primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projectTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ title: text("title").notNull(),+ description: text("description"),+ status: text("status").notNull().default("to-do"),+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),+ updatedAt: timestamp("updated_at", { mode: "date" })+ .defaultNow()+ .$onUpdate(() => new Date())+ .notNull(),+ },+ (table) => [+ index("task_projectId_idx").on(table.projectId),+ ],+);+```-### Migration Commands-```bash-# Generate migration-npm run db:generate+## Naming Conventions++1. **Table names**: Use singular, lowercase with underscores: `task`, `workspace_user`+2. **Column names**: Use snake_case: `project_id`, `created_at`, `updated_at`+3. **Index names**: Format: `{table}_{column}_idx`+4. **Foreign key columns**: End with `_id`: `project_id`, `user_id`++```typescript+// Good: Consistent naming+export const workspaceUserTable = pgTable("workspace_user", {+ id: text("id").primaryKey(),+ workspaceId: text("workspace_id").notNull(),+ userId: text("user_id").notNull(),+ role: text("role").notNull(),+});++// Bad: Inconsistent naming+export const workspaceUserTable = pgTable("WorkspaceUsers", {+ ID: text("ID").primaryKey(),+ workspace: text("workspace").notNull(),+ user: text("user").notNull(),+});+```++## Required Fields++Every table should include:++1. **Primary Key**: `id` field using CUID2+2. **Timestamps**: `created_at` and `updated_at` with proper defaults+3. **Foreign Keys**: Proper references with cascade options++```typescript+export const exampleTable = pgTable("example", {+ // Required: Primary key with CUID2+ id: text("id")+ .$defaultFn(() => createId())+ .primaryKey(),++ // Required: Timestamps+ createdAt: timestamp("created_at", { mode: "date" })+ .defaultNow()+ .notNull(),+ updatedAt: timestamp("updated_at", { mode: "date" })+ .defaultNow()+ .$onUpdate(() => new Date())+ .notNull(),++ // Foreign keys with cascade+ projectId: text("project_id")+ .notNull()+ .references(() => projectTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+});+```++## ID Generation++Always use CUID2 for primary keys:++```typescript+import { createId } from "@paralleldrive/cuid2";++id: text("id")+ .$defaultFn(() => createId())+ .primaryKey(),+```++## Timestamps++Use consistent timestamp patterns:++```typescript+// Created timestamp (never changes)+createdAt: timestamp("created_at", { mode: "date" })+ .defaultNow()+ .notNull(),++// Updated timestamp (auto-updates on change)+updatedAt: timestamp("updated_at", { mode: "date" })+ .defaultNow()+ .$onUpdate(() => new Date())+ .notNull(),++// Optional timestamp (e.g., deleted_at)+deletedAt: timestamp("deleted_at", { mode: "date" }),+```++## Foreign Keys++Always specify cascade behavior:++```typescript+// Good: Explicit cascade behavior+userId: text("user_id")+ .notNull()+ .references(() => userTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),++// Bad: Missing cascade options+userId: text("user_id").references(() => userTable.id),+```++### Cascade Options-# Apply migrations-npm run db:migrate+- **`onDelete: "cascade"`**: Delete related records when parent is deleted+- **`onUpdate: "cascade"`**: Update foreign key when parent ID changes+- **`onDelete: "set null"`**: Set foreign key to null when parent is deleted (use nullable column)-# View database-npm run db:studio+## Indexes++Add indexes for frequently queried columns:++```typescript+export const taskTable = pgTable(+ "task",+ {+ // ... columns+ projectId: text("project_id").notNull(),+ userId: text("user_id"),+ status: text("status").notNull(),+ },+ (table) => [+ index("task_projectId_idx").on(table.projectId),+ index("task_userId_idx").on(table.userId),+ index("task_status_idx").on(table.status),+ ],+);+```++### When to Add Indexes++- Foreign key columns (always)+- Columns used in WHERE clauses frequently+- Columns used for sorting/ordering+- Composite indexes for multi-column queries++## Relations++Define relations in `apps/api/src/database/relations.ts`:++```typescript+import { relations } from "drizzle-orm";+import { taskTable } from "./schema";+import { projectTable } from "./schema";++export const taskTableRelations = relations(taskTable, ({ one, many }) => ({+ project: one(projectTable, {+ fields: [taskTable.projectId],+ references: [projectTable.id],+ }),+ labels: many(labelTable),+}));+```++## Data Types++Use appropriate PostgreSQL types:++```typescript+// Text (varchar)+title: text("title").notNull(),++// Optional text+description: text("description"),++// Boolean+isActive: boolean("is_active").default(true).notNull(),++// Integer+position: integer("position").default(0),++// Timestamp+createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),++// JSON (if needed)+metadata: json("metadata").$type<{ key: string }>(),+```++## Default Values++Provide sensible defaults:++```typescript+// Boolean defaults+isActive: boolean("is_active").default(true).notNull(),++// Integer defaults+position: integer("position").default(0),++// Text defaults+status: text("status").notNull().default("to-do"),++// Timestamp defaults+createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),```-## Data Model Overview+## Migrations-Based on the project structure, the main entities likely include:+### Generating Migrations-### Core Entities-- **Users** - User accounts and authentication-- **Workspaces** - Team/organization containers-- **WorkspaceUsers** - User membership in workspaces-- **Projects** - Project containers within workspaces-- **Tasks** - Individual work items within projects-- **Labels** - Task categorization and tagging-- **TimeEntries** - Time tracking for tasks-- **Activities** - Activity logs and comments-- **Notifications** - User notification system+After schema changes:-### Integration Entities-- **GitHubIntegrations** - GitHub app connections-- **Settings** - Application and user settings+```bash+pnpm --filter @kaneo/api db:generate+```-## Schema Patterns+This creates migration files in `apps/api/drizzle/`.-### Primary Keys-- Uses auto-incrementing integers or UUIDs-- Consistent naming: `id` for primary keys+### Running Migrations-### Foreign Keys-- Clear naming convention for references-- Proper cascading rules for data integrity+Migrations run automatically on API startup (see `apps/api/src/index.ts`):-### Timestamps-- `createdAt` and `updatedAt` fields on most entities-- Consistent timestamp handling+```typescript+await migrate(db, {+ migrationsFolder: `${process.cwd()}/drizzle`,+});+```++### Migration Best Practices-### Soft Deletes-- May use `deletedAt` for soft deletion patterns-- Preserves data integrity and audit trails+1. **Never edit existing migrations**: Create new migrations for changes+2. **Test migrations**: Test both up and down migrations+3. **Backup first**: Always backup production data before migrations+4. **Review SQL**: Check generated SQL before applying-## Database Operations+## Schema Export++Export all schemas and relations from `apps/api/src/database/index.ts`:-### Query Examples```typescript-// Import from schema-import { db } from './database'-import { tasks, projects } from './database/schema'--// Type-safe queries with Drizzle-const userTasks = await db- .select()- .from(tasks)- .where(eq(tasks.userId, userId))+export const schema = {+ taskTable,+ projectTable,+ // ... all tables+ taskTableRelations,+ projectTableRelations,+ // ... all relations+};++const db = drizzle(pool, {+ schema: schema,+});```-### Transaction Patterns-- Use database transactions for multi-table operations-- Ensure data consistency across related entities+This enables Drizzle's relational queries and type inference.diff --git a/.cursor/rules/deployment-devops.mdc b/.cursor/rules/deployment-devops.mdcindex 24db2fcf5..6219c8954 100644--- a/.cursor/rules/deployment-devops.mdc+++ b/.cursor/rules/deployment-devops.mdc@@ -1,116 +1,414 @@----description:-globs:+description: Deployment and DevOps guidelines for Docker Compose and Kubernetes+globs: compose.yml,charts/**/*alwaysApply: false----# Deployment and DevOps+# Deployment & DevOps Guidelines-This document covers the deployment infrastructure, containerization, and DevOps practices for the Kaneo project.+Kaneo supports multiple deployment methods: Docker Compose for development/testing and Kubernetes for production. This document outlines deployment patterns and best practices.-## Containerization+## Docker Compose-### Docker Configuration-- **API Dockerfile**: [apps/api/Dockerfile](mdc:apps/api/Dockerfile) - Backend API container-- **Web Dockerfile**: [apps/web/Dockerfile](mdc:apps/web/Dockerfile) - Frontend application container-- **Environment Script**: [apps/web/env.sh](mdc:apps/web/env.sh) - Runtime environment configuration+### Configuration-### Container Patterns-- **Multi-stage builds** for optimized production images-- **Node.js Alpine** base images for smaller footprint-- **Environment variables** for runtime configuration-- **Health checks** for container monitoring+The main Docker Compose configuration is in `compose.yml` at the project root.-## Kubernetes Deployment+### Service Structure-### Helm Charts-The project uses **Helm** for Kubernetes deployments:+```yaml+services:+ postgres:+ image: postgres:16-alpine+ env_file:+ - .env+ ports:+ - "5432:5432"+ volumes:+ - postgres_data:/var/lib/postgresql/data+ restart: unless-stopped+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U kaneo -d kaneo"]+ interval: 10s+ timeout: 5s+ retries: 5-- **Chart Directory**: [charts/kaneo/](mdc:charts/kaneo) - Main Helm chart-- **Chart.yaml**: [charts/kaneo/Chart.yaml](mdc:charts/kaneo/Chart.yaml) - Chart metadata-- **Values**: [charts/kaneo/values.yaml](mdc:charts/kaneo/values.yaml) - Default configuration values+ api:+ image: ghcr.io/usekaneo/api:latest+ ports:+ - "1337:1337"+ env_file:+ - .env+ depends_on:+ postgres:+ condition: service_healthy+ restart: unless-stopped-### Kubernetes Resources+ web:+ image: ghcr.io/usekaneo/web:latest+ ports:+ - "5173:5173"+ env_file:+ - .env+ depends_on:+ - api+ restart: unless-stopped+```-Located in [charts/kaneo/templates/](mdc:charts/kaneo/templates):+### Best Practices-- **Deployment**: [charts/kaneo/templates/deployment.yaml](mdc:charts/kaneo/templates/deployment.yaml) - Application deployment-- **Service**: Application service definitions-- **Ingress**: External traffic routing-- **ConfigMap**: Configuration management-- **Secret**: Sensitive data management-- **HPA**: [charts/kaneo/templates/hpa.yaml](mdc:charts/kaneo/templates/hpa.yaml) - Horizontal Pod Autoscaler+1. **Health Checks**: Always include health checks for databases+2. **Dependencies**: Use `depends_on` with `condition: service_healthy` for databases+3. **Volumes**: Use named volumes for persistent data+4. **Restart Policy**: Use `unless-stopped` for production-like behavior+5. **Environment Variables**: Use `.env` file, never hardcode secrets-### Deployment Features-- **Horizontal Pod Autoscaling** for traffic-based scaling-- **Rolling updates** for zero-downtime deployments-- **Resource limits** and requests for efficient resource usage-- **Liveness and readiness probes** for health monitoring+```yaml+# Good: Proper health check and dependency+services:+ api:+ depends_on:+ postgres:+ condition: service_healthy-## Environment Configuration+ postgres:+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U kaneo -d kaneo"]+ interval: 10s+ timeout: 5s+ retries: 5+```++## Kubernetes (Helm Charts)++### Chart Structure++Helm charts are located in `charts/kaneo/`:++```+charts/kaneo/+├── Chart.yaml # Chart metadata+├── values.yaml # Default values+├── README.md # Chart documentation+└── templates/+ ├── deployment.yaml # API and Web deployments+ ├── services.yaml # Service definitions+ ├── ingress.yaml # Ingress configuration+ ├── postgresql-deployment.yaml # PostgreSQL deployment+ ├── pvc.yaml # Persistent volume claims+ ├── hpa.yaml # Horizontal Pod Autoscaler+ └── serviceaccount.yaml # Service accounts+```++### Deployment Patterns++#### API Deployment++```yaml+apiVersion: apps/v1+kind: Deployment+metadata:+ name: {{ include "kaneo.fullname" . }}-api+spec:+ replicas: {{ .Values.api.replicaCount }}+ template:+ spec:+ containers:+ - name: api+ image: "{{ .Values.api.image.repository }}:{{ .Values.api.image.tag }}"+ env:+ - name: DATABASE_URL+ valueFrom:+ secretKeyRef:+ name: {{ include "kaneo.fullname" . }}-secrets+ key: database-url+```++#### Web Deployment++```yaml+apiVersion: apps/v1+kind: Deployment+metadata:+ name: {{ include "kaneo.fullname" . }}-web+spec:+ replicas: {{ .Values.web.replicaCount }}+ template:+ spec:+ containers:+ - name: web+ image: "{{ .Values.web.image.repository }}:{{ .Values.web.image.tag }}"+ env:+ - name: VITE_API_URL+ value: {{ .Values.web.apiUrl | quote }}+```++### Best Practices++1. **Secrets Management**: Use Kubernetes Secrets, never hardcode+2. **ConfigMaps**: Use ConfigMaps for non-sensitive configuration+3. **Resource Limits**: Always set resource requests and limits+4. **Health Checks**: Include liveness and readiness probes+5. **Replicas**: Configure appropriate replica counts for high availability++```yaml+# Good: Proper resource limits and health checks+containers:+- name: api+ resources:+ requests:+ memory: "256Mi"+ cpu: "100m"+ limits:+ memory: "512Mi"+ cpu: "500m"+ livenessProbe:+ httpGet:+ path: /api/health+ port: 1337+ initialDelaySeconds: 30+ periodSeconds: 10+ readinessProbe:+ httpGet:+ path: /api/health+ port: 1337+ initialDelaySeconds: 5+ periodSeconds: 5+```++## Environment Variables### Development-- **Local development** with Docker Compose (likely)-- **Hot reloading** for faster iteration-- **Development database** setup++All environment variables in a single `.env` file at project root:++```bash+# Database+DATABASE_URL=postgresql://kaneo_user:kaneo_password@localhost:5432/kaneo+POSTGRES_DB=kaneo+POSTGRES_USER=kaneo_user+POSTGRES_PASSWORD=kaneo_password++# API+KANEO_API_URL=http://localhost:1337+AUTH_SECRET=your-secret-key++# Web+KANEO_CLIENT_URL=http://localhost:5173+VITE_API_URL=http://localhost:1337+```### Production-- **Kubernetes cluster** deployment-- **External database** (managed PostgreSQL)-- **CDN integration** for static assets-- **SSL/TLS termination** at ingress level--## CI/CD Pipeline--### Build Process-- **Monorepo builds** with optimized caching-- **Multi-stage Docker builds** for production efficiency-- **TypeScript compilation** and type checking-- **Linting and formatting** with Biome--### Deployment Strategy-- **GitOps approach** with Helm charts-- **Environment promotion** (dev → staging → production)-- **Automated testing** before deployment-- **Rollback capabilities** for quick recovery--## Monitoring and Observability--### Application Monitoring-- **Health check endpoints** in API-- **Application metrics** collection-- **Error tracking** and alerting-- **Performance monitoring**--### Infrastructure Monitoring-- **Kubernetes cluster** health monitoring-- **Resource utilization** tracking-- **Pod status** and availability metrics-- **Network traffic** monitoring--## Configuration Management--### Environment Variables-- **Database connection** strings-- **API keys** and secrets-- **Feature flags** for environment-specific behavior-- **Third-party service** configurations++Use Kubernetes Secrets and ConfigMaps:++```yaml+# Secret for sensitive data+apiVersion: v1+kind: Secret+metadata:+ name: kaneo-secrets+type: Opaque+stringData:+ database-url: postgresql://user:pass@postgres:5432/kaneo+ auth-secret: your-secret-key++# ConfigMap for non-sensitive data+apiVersion: v1+kind: ConfigMap+metadata:+ name: kaneo-config+data:+ api-url: https://api.example.com+ client-url: https://app.example.com+```++## Database Migrations++### Automatic Migrations++Migrations run automatically on API startup:++```typescript+// apps/api/src/index.ts+await migrate(db, {+ migrationsFolder: `${process.cwd()}/drizzle`,+});+```++### Manual Migrations++For production, consider running migrations separately:++```bash+# In Kubernetes, use a Job+kubectl run migrate-db --image=ghcr.io/usekaneo/api:latest -- \+ node -e "require('./dist/migrate.js')"+```++## Health Checks++### API Health Endpoint++The API exposes a health check endpoint:++```typescript+// apps/api/src/index.ts+api.get("/health", (c) => {+ return c.json({ status: "ok" });+});+```++### Kubernetes Probes++```yaml+livenessProbe:+ httpGet:+ path: /api/health+ port: 1337+ initialDelaySeconds: 30+ periodSeconds: 10++readinessProbe:+ httpGet:+ path: /api/health+ port: 1337+ initialDelaySeconds: 5+ periodSeconds: 5+```++## Scaling++### Horizontal Pod Autoscaling++Configure HPA in `charts/kaneo/templates/hpa.yaml`:++```yaml+apiVersion: autoscaling/v2+kind: HorizontalPodAutoscaler+metadata:+ name: {{ include "kaneo.fullname" . }}-api+spec:+ minReplicas: 2+ maxReplicas: 10+ metrics:+ - type: Resource+ resource:+ name: cpu+ target:+ type: Utilization+ averageUtilization: 70+```++## Ingress++### TLS Configuration++Always use TLS in production:++```yaml+apiVersion: networking.k8s.io/v1+kind: Ingress+metadata:+ name: kaneo-ingress+ annotations:+ cert-manager.io/cluster-issuer: letsencrypt-prod+spec:+ tls:+ - hosts:+ - app.example.com+ secretName: kaneo-tls+ rules:+ - host: app.example.com+ http:+ paths:+ - path: /+ pathType: Prefix+ backend:+ service:+ name: kaneo-web+ port:+ number: 80+```++## Monitoring++### Logging++- Use structured logging+- Include request IDs for tracing+- Log errors with context++### Metrics++- Expose Prometheus metrics if needed+- Monitor database connection pools+- Track API response times++## Backup & Recovery++### Database Backups++For PostgreSQL:++```bash+# Backup+kubectl exec -it postgres-pod -- pg_dump -U kaneo kaneo > backup.sql++# Restore+kubectl exec -i postgres-pod -- psql -U kaneo kaneo < backup.sql+```++### Volume Backups++Use volume snapshots for persistent data:++```yaml+apiVersion: snapshot.storage.k8s.io/v1+kind: VolumeSnapshot+metadata:+ name: postgres-snapshot+spec:+ source:+ persistentVolumeClaimName: postgres-pvc+```++## Security++### Image Security++- Use specific image tags, not `latest`+- Scan images for vulnerabilities+- Use minimal base images (Alpine Linux)++### Network Policies++Restrict pod-to-pod communication:++```yaml+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: kaneo-api-policy+spec:+ podSelector:+ matchLabels:+ app: kaneo-api+ policyTypes:+ - Ingress+ - Egress+ ingress:+ - from:+ - podSelector:+ matchLabels:+ app: kaneo-web+ ports:+ - protocol: TCP+ port: 1337+```### Secrets Management-- **Kubernetes Secrets** for sensitive data-- **External secret management** (vault, cloud providers)-- **Secure key rotation** practices-- **Encryption at rest** and in transit--## Scaling Strategies--### Horizontal Scaling-- **Pod replication** based on CPU/memory usage-- **Load balancing** across multiple instances-- **Database connection pooling**-- **Stateless application design**--### Performance Optimization-- **CDN usage** for static assets-- **Database query optimization**-- **Caching strategies** (Redis, in-memory)-- **Bundle optimization** for frontend assets++- Never commit secrets to Git+- Use Kubernetes Secrets or external secret managers+- Rotate secrets regularly+- Use least privilege principlediff --git a/.cursor/rules/development-conventions.mdc b/.cursor/rules/development-conventions.mdcindex fee61bcc1..0838282b4 100644--- a/.cursor/rules/development-conventions.mdc+++ b/.cursor/rules/development-conventions.mdc@@ -1,147 +1,336 @@----description:-globs:-alwaysApply: false+description: Development conventions, code style, and best practices for the Kaneo project+globs:+alwaysApply: true----# Development Conventions and Best Practices+# Development Conventions-This document outlines the coding standards, patterns, and conventions used throughout the Kaneo project.+This document outlines coding standards, conventions, and best practices for the Kaneo project.-## Code Quality Tools+## Code Style-- **Biome**: [biome.json](mdc:biome.json) - Linting and formatting configuration-- **Commitlint**: [commitlint.config.js](mdc:commitlint.config.js) - Commit message conventions-- **TypeScript**: Strict type checking across all applications+### Biome Configuration-## File and Directory Naming+Kaneo uses **Biome** for linting and formatting. Configuration is in `biome.json`.-### General Conventions-- **kebab-case** for directory names: `github-integration/`, `time-entry/`-- **kebab-case** for file names: `create-task.ts`, `sign-in-form.tsx`-- **PascalCase** for React components: `TaskCard.tsx`, `SignInForm.tsx`+#### Formatting Rules-### Backend API Conventions-- **Controllers**: `{action}-{resource}.ts` pattern- - Examples: `create-task.ts`, `get-project.ts`, `delete-workspace.ts`-- **Utils**: Descriptive names in `utils/` directories-- **Domain Modules**: Each module has `controllers/` and `index.ts`+- **Indentation**: Tabs (not spaces) for TypeScript/TSX+- **JavaScript**: Spaces for indentation (legacy support)+- **Quote Style**: Double quotes (`"`)+- **Semicolons**: Required-### Frontend Conventions-- **Components**: Organized by feature in `components/`-- **Hooks**: Custom hooks in `hooks/mutations/` and `hooks/queries/`-- **Fetchers**: API calls organized by domain in `fetchers/`-- **Types**: TypeScript definitions in `types/` by domain+```typescript+// Good: Tabs, double quotes, semicolons+function example() {+ const value = "hello";+ return value;+}++// Bad: Spaces, single quotes, no semicolons+function example() {+ const value = 'hello'+ return value+}+```++#### Linting Rules++Key Biome rules enabled:++- `noParameterAssign`: Don't reassign function parameters+- `useAsConstAssertion`: Use `as const` for literal types+- `useDefaultParameterLast`: Default parameters must be last+- `useSelfClosingElements`: Use self-closing JSX elements+- `useSingleVarDeclarator`: One variable per declaration+- `noInferrableTypes`: Don't add explicit types that can be inferred++```typescript+// Good: Follows Biome rules+const items = ["a", "b"] as const;+function greet(name: string, greeting = "Hello") {+ return `${greeting}, ${name}`;+}+const x = 1;+const y = 2;++// Bad: Violates Biome rules+const items: string[] = ["a", "b"];+function greet(greeting = "Hello", name: string) {+ return `${greeting}, ${name}`;+}+const x = 1, y = 2;+```++### Running Linter++```bash+# Check and auto-fix+pnpm lint++# Check only (no fixes)+pnpm biome check .+```++## TypeScript Conventions++### Type Definitions++- **Types**: Prefer types for all type definitions (object shapes, unions, intersections, computed types)+- **Interfaces**: Only use interfaces when extending/merging is needed (rare)+- **Inference**: Prefer type inference when types are obvious++```typescript+// Good: Type for object shape+type Task = {+ id: string;+ title: string;+ status: string;+};-## Code Organization Patterns+// Good: Type for union+type Status = "to-do" | "in-progress" | "done";-### Backend Architecture+// Good: Type inference+const tasks: Task[] = []; // Explicit for arrays+const count = tasks.length; // Inferred```-src/-├── {domain}/-│ ├── controllers/-│ │ ├── create-{resource}.ts-│ │ ├── get-{resource}.ts-│ │ └── update-{resource}.ts-│ ├── utils/ (optional)-│ └── index.ts (exports routes)++### File Naming++- **Components**: PascalCase: `TaskCard.tsx`+- **Utilities**: kebab-case: `format-date.ts`+- **Hooks**: camelCase with `use` prefix: `use-task.ts`+- **Types**: kebab-case: `task-types.ts`++```+components/+├── TaskCard.tsx # Component+├── task-card.tsx # Also acceptable+└── utils/+ └── format-date.ts # Utility function```-### Frontend Architecture+## Git Conventions++### Commit Messages++Use [Conventional Commits](https://www.conventionalcommits.org/):+```-src/-├── components/-│ ├── {feature}/-│ │ ├── index.tsx-│ │ └── {sub-components}.tsx-├── fetchers/-│ └── {domain}/-├── hooks/-│ ├── mutations/-│ └── queries/-└── types/- └── {domain}/+<type>: <description>++[optional body]++[optional footer]```-## TypeScript Conventions+#### Commit Types-### Import Organization-1. **External libraries** (React, Hono, etc.)-2. **Internal shared packages** (@kaneo/libs)-3. **Relative imports** (./components, ../utils)+- `feat:` - New features+- `fix:` - Bug fixes+- `docs:` - Documentation changes+- `refactor:` - Code refactoring (no feature/fix)+- `test:` - Adding or updating tests+- `chore:` - Maintenance tasks (deps, config, etc.)+- `style:` - Code style changes (formatting, etc.)-### Type Definitions-- **Interfaces** for object shapes-- **Types** for unions and computed types-- **Enums** for constants with meaningful names-- **Generics** for reusable type patterns--## React Patterns--### Component Structure-```tsx-// Props type-type ComponentProps {- prop: string-}+#### Examples++```bash+feat: add bulk task operations+fix: resolve calendar date selection bug+docs: update deployment guide+refactor: simplify task controller logic+chore: update dependencies+```++### Branch Naming++Use descriptive branch names with prefixes:++- `feat/` - New features+- `fix/` - Bug fixes+- `docs/` - Documentation+- `refactor/` - Refactoring+- `chore/` - Maintenance++```bash+feat/bulk-task-operations+fix/calendar-date-bug+docs/update-deployment-guide+```++## Import Organization++Biome automatically organizes imports. Follow these patterns:++### Import Order-// Component with TypeScript-function Component({ prop }: ComponentProps) {- // Hooks first- const [state, setState] = useState()+1. External packages+2. Internal packages (`@/` aliases)+3. Relative imports- // Event handlers- const handleClick = () => {}+```typescript+// Good: Organized imports+import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Button } from "@/components/ui/button";+import { TaskCard } from "./task-card";+```++### Import Style++- Use named imports when possible+- Group related imports+- Remove unused imports (Biome does this automatically)++```typescript+// Good: Named imports+import { useState, useEffect } from "react";+import { Button, Input } from "@/components/ui";++// Avoid: Default imports when named available+import React from "react"; // Prefer named imports+```++## File Structure++### Component Files++```typescript+// 1. Imports (external, then internal)+import { useState } from "react";+import { Button } from "@/components/ui/button";++// 2. Types+type ComponentProps = {+ title: string;+};- // Render- return <div>{prop}</div>+// 3. Component+export function Component({ title }: ComponentProps) {+ // Implementation}+// 4. Exports (if needed)export default Component;```-### State Management-- **TanStack Query** for server state-- **Zustand** for client state: [apps/web/src/store/](mdc:apps/web/src/store)-- **React Context** for theme and auth: [apps/web/src/components/providers/](mdc:apps/web/src/components/providers)+### API Controller Files-## API Design Patterns+```typescript+// 1. Imports+import db from "../../database";+import { taskTable } from "../../database/schema";++// 2. Function+export default async function getTask(id: string) {+ // Implementation+}+```++## Error Handling++### Backend-### REST Conventions-- **GET** `/api/{resource}` - List resources-- **GET** `/api/{resource}/{id}` - Get single resource-- **POST** `/api/{resource}` - Create resource-- **PUT** `/api/{resource}/{id}` - Update resource-- **DELETE** `/api/{resource}/{id}` - Delete resource+Use Hono's HTTPException:-### Response Format```typescript-// Success response-{- data: T,- success: true+import { HTTPException } from "hono/http-exception";++if (!task) {+ throw new HTTPException(404, { message: "Task not found" });}+```++### Frontend++Use try-catch with user-friendly messages:++```typescript+import { toast } from "sonner";-// Error response-{- error: string,- success: false+try {+ await updateTask(taskId, data);+ toast.success("Task updated");+} catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Failed to update task",+ );}```-## Git Conventions+## Testing-### Commit Messages-Following [Conventional Commits](mdc:https:/www.conventionalcommits.org):-- `feat:` new features-- `fix:` bug fixes-- `docs:` documentation changes-- `style:` formatting changes-- `refactor:` code refactoring-- `test:` adding tests-- `chore:` maintenance tasks+### Test Structure-### Branch Naming-- `feature/description` for new features-- `fix/description` for bug fixes-- `docs/description` for documentation-- `refactor/description` for refactoring+```typescript+describe("Feature", () => {+ it("should do something", () => {+ // Arrange+ const input = "test";++ // Act+ const result = functionUnderTest(input);++ // Assert+ expect(result).toBe("expected");+ });+});+```++## Documentation++### Code Comments++- **Why, not what**: Explain reasoning, not obvious code+- **Complex logic**: Comment complex algorithms or business rules+- **TODOs**: Use `// TODO: description` for future work++```typescript+// Good: Explains why+// Use CUID2 instead of UUID for better database performance+const id = createId();++// Bad: States the obvious+// Create an ID+const id = createId();+```++### README Files++- Keep README files updated+- Include setup instructions+- Document environment variables+- Provide examples++## Environment Variables++- **Single `.env` file**: All variables in project root+- **Documentation**: Document all variables in `ENVIRONMENT_SETUP.md`+- **Never commit**: `.env` files are gitignored+- **Defaults**: Provide sensible defaults in code when possible++## Performance++### Backend++- Use database indexes for frequently queried columns+- Limit query results with pagination+- Use transactions for multi-step operations++### Frontend++- Use React Query for caching and data fetching+- Implement proper loading states+- Lazy load routes when possible+- Optimize images and assets++## Security++- **Never commit secrets**: Use environment variables+- **Validate inputs**: Always validate user input (Valibot on backend)+- **Sanitize outputs**: Sanitize data before rendering+- **Authentication**: Always check authentication in protected routes+- **Authorization**: Verify user permissions before operationsdiff --git a/.cursor/rules/frontend-web.mdc b/.cursor/rules/frontend-web.mdcindex c4268e49a..193040a8c 100644--- a/.cursor/rules/frontend-web.mdc+++ b/.cursor/rules/frontend-web.mdc@@ -1,67 +1,301 @@----description:-globs:+description: Frontend web development guidelines for React, TanStack Router, and TanStack Query+globs: apps/web/**/*alwaysApply: false----# Frontend Web Application Structure--The frontend web application is located in [apps/web/](mdc:apps/web) and is built with React, Vite, and TanStack Router.--## Project Structure--### Core Files-- **Entry Point**: [apps/web/src/main.tsx](mdc:apps/web/src/main.tsx) - React application root-- **Root Route**: [apps/web/src/routes/__root.tsx](mdc:apps/web/src/routes/__root.tsx) - Root layout and providers-- **Router Config**: [apps/web/src/tanstack/router.tsx](mdc:apps/web/src/tanstack/router.tsx) - TanStack Router setup-- **Route Tree**: [apps/web/src/routeTree.gen.ts](mdc:apps/web/src/routeTree.gen.ts) - Auto-generated route tree-- **Global Styles**: [apps/web/src/index.css](mdc:apps/web/src/index.css) - Tailwind CSS imports--### Routing Structure (`src/routes/`)-- **Dashboard**: [apps/web/src/routes/dashboard.tsx](mdc:apps/web/src/routes/dashboard.tsx) - Main dashboard layout-- **Auth Routes**: [apps/web/src/routes/auth/](mdc:apps/web/src/routes/auth) - Sign in/up pages-- **Home**: [apps/web/src/routes/index.tsx](mdc:apps/web/src/routes/index.tsx) - Landing page--### Components Architecture (`src/components/`)--#### Feature Components-- **Auth**: [apps/web/src/components/auth/](mdc:apps/web/src/components/auth) - Authentication forms and layouts-- **Dashboard**: [apps/web/src/components/dashboard/](mdc:apps/web/src/components/dashboard) - Dashboard specific components-- **Task Management**:- - [apps/web/src/components/kanban-board/](mdc:apps/web/src/components/kanban-board) - Kanban board view- - [apps/web/src/components/list-view/](mdc:apps/web/src/components/list-view) - List view for tasks- - [apps/web/src/components/backlog-list-view/](mdc:apps/web/src/components/backlog-list-view) - Backlog view- - [apps/web/src/components/task/](mdc:apps/web/src/components/task) - Task detail components-- **Project**: [apps/web/src/components/project/](mdc:apps/web/src/components/project) - Project management components-- **Team**: [apps/web/src/components/team/](mdc:apps/web/src/components/team) - Team management components--#### Common Components-- **UI Library**: [apps/web/src/components/ui/](mdc:apps/web/src/components/ui) - Shadcn/ui components-- **Common**: [apps/web/src/components/common/](mdc:apps/web/src/components/common) - Shared components (Editor, Logo, Sidebar)-- **Providers**: [apps/web/src/components/providers/](mdc:apps/web/src/components/providers) - React context providers--## Data Management--### API Integration (`src/fetchers/`)-- **TanStack Query**: [apps/web/src/query-client/index.ts](mdc:apps/web/src/query-client/index.ts) - Query client setup-- **Fetchers**: Domain-specific API calls organized by feature (task, project, user, etc.)-- **Hooks**:- - **Mutations**: [apps/web/src/hooks/mutations/](mdc:apps/web/src/hooks/mutations) - Data mutation hooks- - **Queries**: [apps/web/src/hooks/queries/](mdc:apps/web/src/hooks/queries) - Data fetching hooks--### State Management (`src/store/`)-- **Zustand Stores**:- - [apps/web/src/store/project.ts](mdc:apps/web/src/store/project.ts) - Project state- - [apps/web/src/store/workspace.ts](mdc:apps/web/src/store/workspace.ts) - Workspace state- - [apps/web/src/store/user-preferences.ts](mdc:apps/web/src/store/user-preferences.ts) - User preferences--## Type Definitions (`src/types/`)-- **API Types**: [apps/web/src/types/api-response.ts](mdc:apps/web/src/types/api-response.ts)-- **Domain Types**: Organized by feature (task, project, workspace, etc.)--## Utilities and Constants-- **Utilities**: [apps/web/src/lib/](mdc:apps/web/src/lib) - Helper functions and utilities-- **Constants**: [apps/web/src/constants/](mdc:apps/web/src/constants) - App constants (columns, colors, icons)--## Configuration-- **Components**: [apps/web/components.json](mdc:apps/web/components.json) - Shadcn/ui configuration-- **Package**: [apps/web/package.json](mdc:apps/web/package.json) - Dependencies and scripts+# Frontend Web Guidelines++The Kaneo web application is built with React, TanStack Router, TanStack Query, and Vite. This document outlines conventions and patterns for frontend development.++## Framework: React++### Component Structure++Components are organized in `apps/web/src/components/`:++```typescript+// apps/web/src/components/task/task-card.tsx+import { Task } from "@/types/task";++type TaskCardProps = {+ task: Task;+ onUpdate?: (task: Task) => void;+};++export function TaskCard({ task, onUpdate }: TaskCardProps) {+ return (+ <div className="p-4 border rounded-lg">+ <h3>{task.title}</h3>+ {/* ... */}+ </div>+ );+}+```++### Best Practices++1. **TypeScript**: Always type props and component return types+2. **Component naming**: Use PascalCase for component files and exports+3. **Props destructuring**: Destructure props in function parameters+4. **Conditional rendering**: Use ternary or logical operators clearly++```typescript+// Good: Typed component with clear structure+type ButtonProps = {+ variant?: "primary" | "secondary";+ children: React.ReactNode;+ onClick?: () => void;+};++export function Button({ variant = "primary", children, onClick }: ButtonProps) {+ return (+ <button+ className={cn("px-4 py-2", variant === "primary" && "bg-blue-500")}+ onClick={onClick}+ >+ {children}+ </button>+ );+}++// Bad: Untyped, unclear structure+export function Button(props: any) {+ return <button onClick={props.onClick}>{props.children}</button>;+}+```++## Routing: TanStack Router++### File-Based Routing++Routes are defined using file-based routing in `apps/web/src/routes/`:++```typescript+// apps/web/src/routes/tasks/$taskId.tsx+import { createFileRoute } from "@tanstack/react-router";+import { useTask } from "@/hooks/queries/task/use-task";++export const Route = createFileRoute("/tasks/$taskId")({+ component: TaskPage,+});++function TaskPage() {+ const { taskId } = Route.useParams();+ const { data: task } = useTask(taskId);++ if (!task) return <div>Loading...</div>;++ return <div>{task.title}</div>;+}+```++### Route Patterns++- **Layout routes**: Use `_layout.tsx` for shared layouts+- **Auth routes**: Grouped in `auth/` directory+- **Dynamic routes**: Use `$param` syntax for route parameters++```typescript+// Layout route: apps/web/src/routes/_layout.tsx+export const Route = createFileRoute("/_layout")({+ component: Layout,+});++// Dynamic route: apps/web/src/routes/tasks/$taskId.tsx+export const Route = createFileRoute("/tasks/$taskId")({+ component: TaskPage,+});+```++## Data Fetching: TanStack Query++### Query Hooks++Create query hooks in `apps/web/src/hooks/queries/`:++```typescript+// apps/web/src/hooks/queries/task/use-task.ts+import { useQuery } from "@tanstack/react-query";+import { getTask } from "@/fetchers/task/get-task";++export function useTask(taskId: string) {+ return useQuery({+ queryKey: ["task", taskId],+ queryFn: () => getTask(taskId),+ });+}+```++### Mutation Hooks++Create mutation hooks in `apps/web/src/hooks/mutations/`:++```typescript+// apps/web/src/hooks/mutations/task/use-update-task.ts+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { updateTask } from "@/fetchers/task/update-task";+import { toast } from "sonner";++export function useUpdateTask() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: updateTask,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ["task"] });+ toast.success("Task updated");+ },+ onError: (error) => {+ toast.error(error.message);+ },+ });+}+```++### Best Practices++1. **Query keys**: Use arrays with consistent structure: `["resource", id]`+2. **Invalidation**: Invalidate related queries after mutations+3. **Error handling**: Use toast notifications for user feedback+4. **Loading states**: Handle loading and error states in components++```typescript+// Good: Proper query with error handling+function TaskPage() {+ const { taskId } = Route.useParams();+ const { data: task, isLoading, error } = useTask(taskId);++ if (isLoading) return <Skeleton />;+ if (error) return <Error message={error.message} />;+ if (!task) return <NotFound />;++ return <TaskDetails task={task} />;+}+```++## Fetchers++API calls are abstracted in `apps/web/src/fetchers/`:++```typescript+// apps/web/src/fetchers/task/get-task.ts+import { apiClient } from "@/lib/api-client";++export async function getTask(taskId: string) {+ const response = await apiClient.get(`/api/task/${taskId}`);+ return response.data;+}+```++### Fetcher Organization++Organize fetchers by feature, mirroring API structure:++```+apps/web/src/fetchers/+├── task/+│ ├── get-task.ts+│ ├── update-task.ts+│ └── create-task.ts+├── project/+│ └── ...+└── workspace/+ └── ...+```++## Styling: Tailwind CSS++Use Tailwind CSS utility classes:++```typescript+<div className="flex items-center gap-4 p-4 bg-white rounded-lg shadow">+ <h2 className="text-xl font-semibold">Title</h2>+</div>+```++### Utility Functions++Use `cn()` utility for conditional classes:++```typescript+import { cn } from "@/lib/cn";++<button+ className={cn(+ "px-4 py-2 rounded",+ isActive && "bg-blue-500 text-white",+ disabled && "opacity-50 cursor-not-allowed",+ )}+>+ Click me+</button>+```++## Authentication++Use Better Auth client for authentication:++```typescript+import { authClient } from "@/lib/auth-client";++// Sign in+await authClient.signIn.email({+ email: "[email protected]",+ password: "password",+});++// Get current user+const session = await authClient.getSession();+```++## File Organization++```+apps/web/src/+├── components/ # React components+│ ├── ui/ # Base UI components+│ └── ...+├── fetchers/ # API call functions+├── hooks/ # Custom React hooks+│ ├── queries/ # TanStack Query hooks+│ └── mutations/ # TanStack Query mutations+├── lib/ # Utility functions+├── routes/ # TanStack Router routes+├── store/ # Global state (Zustand)+├── types/ # TypeScript types+└── main.tsx # Entry point+```++## Type Safety++Share types between frontend and backend when possible:++```typescript+// apps/web/src/types/task.ts+export type Task = {+ id: string;+ title: string;+ description?: string;+ status: string;+ priority: string;+ dueDate?: string;+ createdAt: string;+};+```++## Error Handling++Handle errors gracefully with user-friendly messages:++```typescript+import { toast } from "sonner";++try {+ await updateTask(taskId, data);+ toast.success("Task updated");+} catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Failed to update task",+ );+}+```diff --git a/.cursor/rules/project-overview.mdc b/.cursor/rules/project-overview.mdcindex 872bde5b4..7adbd756c 100644--- a/.cursor/rules/project-overview.mdc+++ b/.cursor/rules/project-overview.mdc@@ -1,42 +1,84 @@----description:-globs:-alwaysApply: false+description: Overview of the Kaneo project structure, architecture, and key technologies+globs:+alwaysApply: true----# Kaneo Project Overview+# Project Overview-Kaneo is a modern project management application built as a monorepo with multiple applications and shared packages.+Kaneo is a self-hosted project management platform built with a focus on simplicity and performance. This document provides an overview of the project structure and architecture.-## Architecture+## Project Structure-This is a **monorepo** containing:+Kaneo is organized as a **monorepo** using pnpm workspaces:-### Applications (`apps/`)-- **`api/`** - Backend API built with Hono framework and TypeScript-- **`web/`** - Frontend React application with Vite and TanStack Router-- **`docs/`** - Documentation website built with Next.js+```+kaneo/+├── apps/+│ ├── api/ # Backend API (Hono/Node.js)+│ ├── docs/ # Documentation site (Next.js)+│ └── web/ # Frontend app (React/Vite)+├── packages/ # Shared code and configs+│ ├── email/ # Email utilities+│ ├── libs/ # Shared libraries+│ └── typescript-config/ # TypeScript configurations+├── charts/ # Kubernetes Helm charts+├── .cursor/ # Cursor IDE rules+└── compose.yml # Docker Compose configuration+```-### Packages (`packages/`)-- **`libs/`** - Shared TypeScript utilities and Hono extensions-- **`typescript-config/`** - Shared TypeScript configurations+## Technology Stack-## Key Technologies+### Backend (API)+- **Framework**: Hono (lightweight web framework)+- **Runtime**: Node.js+- **Database**: PostgreSQL with Drizzle ORM+- **Authentication**: Better Auth+- **Validation**: Valibot+- **API Documentation**: OpenAPI (hono-openapi)+- **Build Tool**: esbuild-- **Backend**: Hono, TypeScript, Drizzle ORM, PostgreSQL-- **Frontend**: React, Vite, TanStack Router, TanStack Query, Tailwind CSS-- **Database**: PostgreSQL with Drizzle ORM migrations-- **Deployment**: Docker, Kubernetes (Helm charts)-- **Monorepo**: Turborepo for build orchestration+### Frontend (Web)+- **Framework**: React 18++- **Routing**: TanStack Router+- **Data Fetching**: TanStack Query (React Query)+- **Build Tool**: Vite+- **Styling**: Tailwind CSS+- **UI Components**: Custom component library-## Entry Points+### Development Tools+- **Package Manager**: pnpm+- **Linting/Formatting**: Biome+- **TypeScript**: Strict mode enabled+- **Git Hooks**: Husky-- Backend API: [apps/api/src/index.ts](mdc:apps/api/src/index.ts)-- Frontend Web App: [apps/web/src/main.tsx](mdc:apps/web/src/main.tsx)-- Documentation: [apps/docs/app/layout.tsx](mdc:apps/docs/app/layout.tsx)+## Key Principles-## Configuration Files+1. **Simplicity First**: Features exist to solve real problems, not to impress+2. **Performance**: Fast load times and responsive interactions+3. **Self-Hosted**: Your data stays yours+4. **Open Source**: Free forever, MIT licensed-- Database config: [apps/api/drizzle.config.ts](mdc:apps/api/drizzle.config.ts)-- Database schema: [apps/api/src/database/schema.ts](mdc:apps/api/src/database/schema.ts)-- Backend package.json: [apps/api/package.json](mdc:apps/api/package.json)-- Frontend package.json: [apps/web/package.json](mdc:apps/web/package.json)+## Development Workflow++1. **Install dependencies**: `pnpm install`+2. **Start development**: `pnpm dev` (starts both API and web)+3. **Lint code**: `pnpm lint` (runs Biome)+4. **Database migrations**: `pnpm --filter @kaneo/api db:generate` and `db:migrate`++## Environment Setup++All environment variables are configured in a single `.env` file at the project root. See `ENVIRONMENT_SETUP.md` for detailed configuration instructions.++## Deployment++- **Docker Compose**: Quick setup for development/testing+- **Kubernetes**: Production-ready Helm charts in `charts/`+- **Self-Hosted**: Designed to run on your infrastructure++## Contributing++See `CONTRIBUTING.md` for guidelines on:+- Code style (Biome configuration)+- Commit messages (Conventional Commits)+- Project structure conventions+- Getting help