Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

first commit

Lewis Carhart2fa1a91b2ddb
diff --git a/.agents/skills/better-auth-best-practices/SKILL.md b/.agents/skills/better-auth-best-practices/SKILL.md
new file mode 100644
index 00000000..ddeedc81
--- /dev/null
+++ b/.agents/skills/better-auth-best-practices/SKILL.md
@@ -0,0 +1,182 @@
+---
+name: better-auth-best-practices
+description: Configure Better Auth server and client, set up database adapters, manage sessions, add plugins, and handle environment variables. Use when users mention Better Auth, betterauth, auth.ts, or need to set up TypeScript authentication with email/password, OAuth, or plugin configuration.
+---
+
+# Better Auth Integration Guide
+
+**Always consult [better-auth.com/docs](https://better-auth.com/docs) for code examples and latest API.**
+
+---
+
+## Setup Workflow
+
+1. Install: `npm install better-auth`
+2. Set env vars: `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL`
+3. Create `auth.ts` with database + config
+4. Create route handler for your framework
+5. Run migrations:
+ - **Built-in adapter:** `npx @better-auth/cli@latest migrate`
+ - **Drizzle:** `npx @better-auth/cli@latest generate --output src/db/auth-schema.ts` then `npx drizzle-kit push` (dev) or `npx drizzle-kit generate && npx drizzle-kit migrate` (prod)
+ - **Prisma:** `npx @better-auth/cli@latest generate --output prisma/schema.prisma` then `npx prisma migrate dev`
+6. Verify: call `GET /api/auth/ok` — should return `{ status: "ok" }`
+
+---
+
+## Quick Reference
+
+### Environment Variables
+- `BETTER_AUTH_SECRET` - Encryption secret (min 32 chars). Generate: `openssl rand -base64 32`
+- `BETTER_AUTH_URL` - Base URL (e.g., `https://example.com`)
+
+Only define `baseURL`/`secret` in config if env vars are NOT set.
+
+### File Location
+CLI looks for `auth.ts` in: `./`, `./lib`, `./utils`, or under `./src`. Use `--config` for custom path.
+
+### CLI Commands
+- `npx @better-auth/cli@latest migrate` - Apply schema (built-in adapter)
+- `npx @better-auth/cli@latest generate` - Generate schema for Prisma/Drizzle
+- `npx @better-auth/cli mcp --cursor` - Add MCP to AI tools
+
+**Re-run after adding/changing plugins.**
+
+---
+
+## Core Config Options
+
+| Option | Notes |
+|--------|-------|
+| `appName` | Optional display name |
+| `baseURL` | Only if `BETTER_AUTH_URL` not set |
+| `basePath` | Default `/api/auth`. Set `/` for root. |
+| `secret` | Only if `BETTER_AUTH_SECRET` not set |
+| `database` | Required for most features. See adapters docs. |
+| `secondaryStorage` | Redis/KV for sessions & rate limits |
+| `emailAndPassword` | `{ enabled: true }` to activate |
+| `socialProviders` | `{ google: { clientId, clientSecret }, ... }` |
+| `plugins` | Array of plugins |
+| `trustedOrigins` | CSRF whitelist |
+
+---
+
+## Database
+
+**Direct connections:** Pass `pg.Pool`, `mysql2` pool, `better-sqlite3`, or `bun:sqlite` instance. For Postgres, also supports `postgres` (postgres.js) and `@neondatabase/serverless`.
+
+**ORM adapters:** Import from `better-auth/adapters/drizzle`, `better-auth/adapters/prisma`, `better-auth/adapters/mongodb`.
+
+**Drizzle provider values:** `"pg"` (PostgreSQL), `"mysql"` (MySQL), `"sqlite"` (SQLite). Must match the driver used.
+
+**Critical:** Better Auth uses adapter model names, NOT underlying table names. If Prisma model is `User` mapping to table `users`, use `modelName: "user"` (Prisma reference), not `"users"`.
+
+---
+
+## Session Management
+
+**Storage priority:**
+1. If `secondaryStorage` defined → sessions go there (not DB)
+2. Set `session.storeSessionInDatabase: true` to also persist to DB
+3. No database + `cookieCache` → fully stateless mode
+
+**Cookie cache strategies:**
+- `compact` (default) - Base64url + HMAC. Smallest.
+- `jwt` - Standard JWT. Readable but signed.
+- `jwe` - Encrypted. Maximum security.
+
+**Key options:** `session.expiresIn` (default 7 days), `session.updateAge` (refresh interval), `session.cookieCache.maxAge`, `session.cookieCache.version` (change to invalidate all sessions).
+
+---
+
+## User & Account Config
+
+**User:** `user.modelName`, `user.fields` (column mapping), `user.additionalFields`, `user.changeEmail.enabled` (disabled by default), `user.deleteUser.enabled` (disabled by default).
+
+**Account:** `account.modelName`, `account.accountLinking.enabled`, `account.storeAccountCookie` (for stateless OAuth).
+
+**Required for registration:** `email` and `name` fields.
+
+---
+
+## Email Flows
+
+- `emailVerification.sendVerificationEmail` - Must be defined for verification to work
+- `emailVerification.sendOnSignUp` / `sendOnSignIn` - Auto-send triggers
+- `emailAndPassword.sendResetPassword` - Password reset email handler
+
+---
+
+## Security
+
+**In `advanced`:**
+- `useSecureCookies` - Force HTTPS cookies
+- `disableCSRFCheck` - ⚠️ Security risk
+- `disableOriginCheck` - ⚠️ Security risk
+- `crossSubDomainCookies.enabled` - Share cookies across subdomains
+- `ipAddress.ipAddressHeaders` - Custom IP headers for proxies
+- `database.generateId` - Custom ID generation or `"serial"`/`"uuid"`/`false`
+
+**Rate limiting:** `rateLimit.enabled`, `rateLimit.window`, `rateLimit.max`, `rateLimit.storage` ("memory" | "database" | "secondary-storage").
+
+---
+
+## Hooks
+
+**Endpoint hooks:** `hooks.before` / `hooks.after` - Array of `{ matcher, handler }`. Use `createAuthMiddleware`. Access `ctx.path`, `ctx.context.returned` (after), `ctx.context.session`.
+
+**Database hooks:** `databaseHooks.user.create.before/after`, same for `session`, `account`. Useful for adding default values or post-creation actions.
+
+**Hook context (`ctx.context`):** `session`, `secret`, `authCookies`, `password.hash()`/`verify()`, `adapter`, `internalAdapter`, `generateId()`, `tables`, `baseURL`.
+
+---
+
+## Plugins
+
+**Import from dedicated paths for tree-shaking:**
+```
+import { twoFactor } from "better-auth/plugins/two-factor"
+```
+NOT `from "better-auth/plugins"`.
+
+**Popular plugins:** `twoFactor`, `organization`, `passkey`, `magicLink`, `emailOtp`, `username`, `phoneNumber`, `admin`, `apiKey`, `bearer`, `jwt`, `multiSession`, `sso`, `oauthProvider`, `oidcProvider`, `openAPI`, `genericOAuth`.
+
+Client plugins go in `createAuthClient({ plugins: [...] })`.
+
+---
+
+## Client
+
+Import from: `better-auth/client` (vanilla), `better-auth/react`, `better-auth/vue`, `better-auth/svelte`, `better-auth/solid`.
+
+Key methods: `signUp.email()`, `signIn.email()`, `signIn.social()`, `signOut()`, `useSession()`, `getSession()`, `revokeSession()`, `revokeSessions()`.
+
+---
+
+## Type Safety
+
+Infer types: `typeof auth.$Infer.Session`, `typeof auth.$Infer.Session.user`.
+
+For separate client/server projects: `createAuthClient<typeof auth>()`.
+
+---
+
+## Common Gotchas
+
+1. **Model vs table name** - Config uses ORM model name, not DB table name
+2. **Plugin schema** - Re-run CLI after adding plugins
+3. **Secondary storage** - Sessions go there by default, not DB
+4. **Cookie cache** - Custom session fields NOT cached, always re-fetched
+5. **Stateless mode** - No DB = session in cookie only, logout on cache expiry
+6. **Change email flow** - Sends to current email first, then new email
+7. **Drizzle: db not initialized** - `drizzleAdapter(db, ...)` requires a `db` instance from `drizzle()`. See `create-auth` skill for setup examples (node-postgres, postgres.js, Neon).
+8. **Drizzle: missing drizzle.config.ts** - `drizzle-kit` commands require a `drizzle.config.ts` pointing to the generated schema file and DB credentials.
+
+---
+
+## Resources
+
+- [Docs](https://better-auth.com/docs)
+- [Options Reference](https://better-auth.com/docs/reference/options)
+- [LLMs.txt](https://better-auth.com/llms.txt)
+- [GitHub](https://github.com/better-auth/better-auth)
+- [Init Options Source](https://github.com/better-auth/better-auth/blob/main/packages/core/src/types/init-options.ts)
\ No newline at end of file
diff --git a/.agents/skills/eve/SKILL.md b/.agents/skills/eve/SKILL.md
new file mode 100644
index 00000000..4f6778ef
--- /dev/null
+++ b/.agents/skills/eve/SKILL.md
@@ -0,0 +1,27 @@
+---
+name: eve
+description: Build durable backend AI agents with the eve framework. Use when creating, editing, or debugging an eve project — agent instructions, skills, tools, connections, channels, sandboxes, subagents, schedules, or evals.
+---
+
+# eve
+
+eve is a filesystem-first framework for durable backend AI agents. An agent is
+a directory on disk — instructions, skills, tools, connections, channels,
+subagents, and schedules are all files — and eve compiles and runs it.
+
+## Source of truth
+
+The complete documentation ships inside the `eve` package. Do not rely on this
+skill for guidance — always read the bundled docs, which match the installed
+version exactly:
+
+```
+node_modules/eve/docs/
+```
+
+Start with `node_modules/eve/docs/README.md`. It contains the full
+index and recommended reading order. Before writing any eve code, read the
+relevant guide there first.
+
+If `eve` is not installed yet, install it (`npm install eve`) or scaffold a new
+agent with `npx eve init <agent-name>`, then read the bundled docs.
diff --git a/.agents/skills/nestjs-best-practices/SKILL.md b/.agents/skills/nestjs-best-practices/SKILL.md
new file mode 100644
index 00000000..c3a83abf
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/SKILL.md
@@ -0,0 +1,131 @@
+---
+name: nestjs-best-practices
+description: NestJS best practices and architecture patterns for building production-ready applications. This skill should be used when writing, reviewing, or refactoring NestJS code to ensure proper patterns for modules, dependency injection, security, and performance.
+license: MIT
+metadata:
+ author: Kadajett
+ version: "1.2.0"
+---
+
+# NestJS Best Practices
+
+Comprehensive best practices guide for NestJS applications. Contains 40 rules across 10 categories, prioritized by impact to guide automated refactoring and code generation.
+
+## When to Apply
+
+Reference these guidelines when:
+
+- Writing new NestJS modules, controllers, or services
+- Implementing authentication and authorization
+- Reviewing code for architecture and security issues
+- Refactoring existing NestJS codebases
+- Optimizing performance or database queries
+- Building microservices architectures
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Architecture | CRITICAL | `arch-` |
+| 2 | Dependency Injection | CRITICAL | `di-` |
+| 3 | Error Handling | HIGH | `error-` |
+| 4 | Security | HIGH | `security-` |
+| 5 | Performance | HIGH | `perf-` |
+| 6 | Testing | MEDIUM-HIGH | `test-` |
+| 7 | Database & ORM | MEDIUM-HIGH | `db-` |
+| 8 | API Design | MEDIUM | `api-` |
+| 9 | Microservices | MEDIUM | `micro-` |
+| 10 | DevOps & Deployment | LOW-MEDIUM | `devops-` |
+
+## Quick Reference
+
+### 1. Architecture (CRITICAL)
+
+- `arch-avoid-circular-deps` - Avoid circular module dependencies
+- `arch-feature-modules` - Organize by feature, not technical layer
+- `arch-module-sharing` - Proper module exports/imports, avoid duplicate providers
+- `arch-single-responsibility` - Focused services over "god services"
+- `arch-use-repository-pattern` - Abstract database logic for testability
+- `arch-use-events` - Event-driven architecture for decoupling
+
+### 2. Dependency Injection (CRITICAL)
+
+- `di-avoid-service-locator` - Avoid service locator anti-pattern
+- `di-interface-segregation` - Interface Segregation Principle (ISP)
+- `di-liskov-substitution` - Liskov Substitution Principle (LSP)
+- `di-prefer-constructor-injection` - Constructor over property injection
+- `di-scope-awareness` - Understand singleton/request/transient scopes
+- `di-use-interfaces-tokens` - Use injection tokens for interfaces
+
+### 3. Error Handling (HIGH)
+
+- `error-use-exception-filters` - Centralized exception handling
+- `error-throw-http-exceptions` - Use NestJS HTTP exceptions
+- `error-handle-async-errors` - Handle async errors properly
+
+### 4. Security (HIGH)
+
+- `security-auth-jwt` - Secure JWT authentication
+- `security-validate-all-input` - Validate with class-validator
+- `security-use-guards` - Authentication and authorization guards
+- `security-sanitize-output` - Prevent XSS attacks
+- `security-rate-limiting` - Implement rate limiting
+
+### 5. Performance (HIGH)
+
+- `perf-async-hooks` - Proper async lifecycle hooks
+- `perf-use-caching` - Implement caching strategies
+- `perf-optimize-database` - Optimize database queries
+- `perf-lazy-loading` - Lazy load modules for faster startup
+
+### 6. Testing (MEDIUM-HIGH)
+
+- `test-use-testing-module` - Use NestJS testing utilities
+- `test-e2e-supertest` - E2E testing with Supertest
+- `test-mock-external-services` - Mock external dependencies
+
+### 7. Database & ORM (MEDIUM-HIGH)
+
+- `db-use-transactions` - Transaction management
+- `db-avoid-n-plus-one` - Avoid N+1 query problems
+- `db-use-migrations` - Use migrations for schema changes
+
+### 8. API Design (MEDIUM)
+
+- `api-use-dto-serialization` - DTO and response serialization
+- `api-use-interceptors` - Cross-cutting concerns
+- `api-versioning` - API versioning strategies
+- `api-use-pipes` - Input transformation with pipes
+
+### 9. Microservices (MEDIUM)
+
+- `micro-use-patterns` - Message and event patterns
+- `micro-use-health-checks` - Health checks for orchestration
+- `micro-use-queues` - Background job processing
+
+### 10. DevOps & Deployment (LOW-MEDIUM)
+
+- `devops-use-config-module` - Environment configuration
+- `devops-use-logging` - Structured logging
+- `devops-graceful-shutdown` - Zero-downtime deployments
+
+## How to Use
+
+Read individual rule files for detailed explanations and code examples:
+
+```
+rules/arch-avoid-circular-deps.md
+rules/security-validate-all-input.md
+rules/_sections.md
+```
+
+Each rule file contains:
+- Brief explanation of why it matters
+- Incorrect code example with explanation
+- Correct code example with explanation
+- Additional context and references
+
+## Full Compiled Document
+
+For the complete guide with all rules expanded in a single document, see
+[AGENTS.md in the repository](https://github.com/Kadajett/agent-nestjs-skills/blob/main/AGENTS.md).
diff --git a/.agents/skills/nestjs-best-practices/rules/_sections.md b/.agents/skills/nestjs-best-practices/rules/_sections.md
new file mode 100644
index 00000000..91bc8029
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/_sections.md
@@ -0,0 +1,56 @@
+# Sections
+
+This file defines all sections, their ordering, impact levels, and descriptions.
+The section ID (in parentheses) is the filename prefix used to group rules.
+
+---
+
+## 1. Architecture (arch)
+
+**Impact:** CRITICAL
+**Description:** Proper module organization and dependency management are the foundation of maintainable NestJS applications. Circular dependencies and god services are the #1 architecture killer.
+
+## 2. Dependency Injection (di)
+
+**Impact:** CRITICAL
+**Description:** NestJS's IoC container is powerful but can be misused. Understanding scopes, injection tokens, and proper patterns is essential for testable code.
+
+## 3. Error Handling (error)
+
+**Impact:** HIGH
+**Description:** Consistent error handling improves debugging, user experience, and API reliability. Centralized exception filters ensure uniform error responses.
+
+## 4. Security (security)
+
+**Impact:** HIGH
+**Description:** Security vulnerabilities can be catastrophic. Input validation, authentication, authorization, and data protection are non-negotiable.
+
+## 5. Performance (perf)
+
+**Impact:** HIGH
+**Description:** Optimizing request handling, caching, and database queries directly impacts application responsiveness and scalability.
+
+## 6. Testing (test)
+
+**Impact:** MEDIUM-HIGH
+**Description:** Well-tested applications are more reliable. NestJS testing utilities enable comprehensive unit and e2e coverage.
+
+## 7. Database & ORM (db)
+
+**Impact:** MEDIUM-HIGH
+**Description:** Proper database access patterns, transactions, and query optimization are crucial for data-intensive applications.
+
+## 8. API Design (api)
+
+**Impact:** MEDIUM
+**Description:** RESTful conventions, versioning, DTOs, and consistent response formats improve API usability and maintainability.
+
+## 9. Microservices (micro)
+
+**Impact:** MEDIUM
+**Description:** Building distributed systems requires understanding message patterns, health checks, and inter-service communication.
+
+## 10. DevOps & Deployment (devops)
+
+**Impact:** LOW-MEDIUM
+**Description:** Configuration management, structured logging, and graceful shutdown ensure production readiness and zero-downtime deployments.
diff --git a/.agents/skills/nestjs-best-practices/rules/_template.md b/.agents/skills/nestjs-best-practices/rules/_template.md
new file mode 100644
index 00000000..1e9e7070
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/_template.md
@@ -0,0 +1,28 @@
+---
+title: Rule Title Here
+impact: MEDIUM
+impactDescription: Optional description of impact (e.g., "20-50% improvement")
+tags: tag1, tag2
+---
+
+## Rule Title Here
+
+**Impact: MEDIUM (optional impact description)**
+
+Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
+
+**Incorrect (description of what's wrong):**
+
+```typescript
+// Bad code example here
+const bad = example()
+```
+
+**Correct (description of what's right):**
+
+```typescript
+// Good code example here
+const good = example()
+```
+
+Reference: [Link to documentation or resource](https://example.com)
diff --git a/.agents/skills/nestjs-best-practices/rules/api-use-dto-serialization.md b/.agents/skills/nestjs-best-practices/rules/api-use-dto-serialization.md
new file mode 100644
index 00000000..be95c07f
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/api-use-dto-serialization.md
@@ -0,0 +1,182 @@
+---
+title: Use DTOs and Serialization for API Responses
+impact: MEDIUM
+impactDescription: Response DTOs prevent accidental data exposure and ensure consistency
+tags: api, dto, serialization, class-transformer
+---
+
+## Use DTOs and Serialization for API Responses
+
+Never return entity objects directly from controllers. Use response DTOs with class-transformer's `@Exclude()` and `@Expose()` decorators to control exactly what data is sent to clients. This prevents accidental exposure of sensitive fields and provides a stable API contract.
+
+**Incorrect (returning entities directly or manual spreading):**
+
+```typescript
+// Return entities directly
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<User> {
+ return this.usersService.findById(id);
+ // Returns: { id, email, passwordHash, ssn, internalNotes, ... }
+ // Exposes sensitive data!
+ }
+}
+
+// Manual object spreading (error-prone)
+@Get(':id')
+async findOne(@Param('id') id: string) {
+ const user = await this.usersService.findById(id);
+ return {
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ // Easy to forget to exclude sensitive fields
+ // Hard to maintain across endpoints
+ };
+}
+```
+
+**Correct (use class-transformer with @Exclude and response DTOs):**
+
+```typescript
+// Enable class-transformer globally
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule);
+ app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
+ await app.listen(3000);
+}
+
+// Entity with serialization control
+@Entity()
+export class User {
+ @PrimaryGeneratedColumn('uuid')
+ id: string;
+
+ @Column()
+ email: string;
+
+ @Column()
+ name: string;
+
+ @Column()
+ @Exclude() // Never include in responses
+ passwordHash: string;
+
+ @Column({ nullable: true })
+ @Exclude()
+ ssn: string;
+
+ @Column({ default: false })
+ @Exclude({ toPlainOnly: true }) // Exclude from response, allow in requests
+ isAdmin: boolean;
+
+ @CreateDateColumn()
+ createdAt: Date;
+
+ @Column()
+ @Exclude()
+ internalNotes: string;
+}
+
+// Now returning entity is safe
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<User> {
+ return this.usersService.findById(id);
+ // Returns: { id, email, name, createdAt }
+ // Sensitive fields excluded automatically
+ }
+}
+
+// For different response shapes, use explicit DTOs
+export class UserResponseDto {
+ @Expose()
+ id: string;
+
+ @Expose()
+ email: string;
+
+ @Expose()
+ name: string;
+
+ @Expose()
+ @Transform(({ obj }) => obj.posts?.length || 0)
+ postCount: number;
+
+ constructor(partial: Partial<User>) {
+ Object.assign(this, partial);
+ }
+}
+
+export class UserDetailResponseDto extends UserResponseDto {
+ @Expose()
+ createdAt: Date;
+
+ @Expose()
+ @Type(() => PostResponseDto)
+ posts: PostResponseDto[];
+}
+
+// Controller with explicit DTOs
+@Controller('users')
+export class UsersController {
+ @Get()
+ @SerializeOptions({ type: UserResponseDto })
+ async findAll(): Promise<UserResponseDto[]> {
+ const users = await this.usersService.findAll();
+ return users.map(u => plainToInstance(UserResponseDto, u));
+ }
+
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<UserDetailResponseDto> {
+ const user = await this.usersService.findByIdWithPosts(id);
+ return plainToInstance(UserDetailResponseDto, user, {
+ excludeExtraneousValues: true,
+ });
+ }
+}
+
+// Groups for conditional serialization
+export class UserDto {
+ @Expose()
+ id: string;
+
+ @Expose()
+ name: string;
+
+ @Expose({ groups: ['admin'] })
+ email: string;
+
+ @Expose({ groups: ['admin'] })
+ createdAt: Date;
+
+ @Expose({ groups: ['admin', 'owner'] })
+ settings: UserSettings;
+}
+
+@Controller('users')
+export class UsersController {
+ @Get()
+ @SerializeOptions({ groups: ['public'] })
+ async findAllPublic(): Promise<UserDto[]> {
+ // Returns: { id, name }
+ }
+
+ @Get('admin')
+ @UseGuards(AdminGuard)
+ @SerializeOptions({ groups: ['admin'] })
+ async findAllAdmin(): Promise<UserDto[]> {
+ // Returns: { id, name, email, createdAt }
+ }
+
+ @Get('me')
+ @SerializeOptions({ groups: ['owner'] })
+ async getProfile(@CurrentUser() user: User): Promise<UserDto> {
+ // Returns: { id, name, settings }
+ }
+}
+```
+
+Reference: [NestJS Serialization](https://docs.nestjs.com/techniques/serialization)
diff --git a/.agents/skills/nestjs-best-practices/rules/api-use-interceptors.md b/.agents/skills/nestjs-best-practices/rules/api-use-interceptors.md
new file mode 100644
index 00000000..522ab3d5
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/api-use-interceptors.md
@@ -0,0 +1,202 @@
+---
+title: Use Interceptors for Cross-Cutting Concerns
+impact: MEDIUM-HIGH
+impactDescription: Interceptors provide clean separation for cross-cutting logic
+tags: api, interceptors, logging, caching
+---
+
+## Use Interceptors for Cross-Cutting Concerns
+
+Interceptors can transform responses, add logging, handle caching, and measure performance without polluting your business logic. They wrap the route handler execution, giving you access to both the request and response streams.
+
+**Incorrect (logging and transformation in every method):**
+
+```typescript
+// Logging in every controller method
+@Controller('users')
+export class UsersController {
+ @Get()
+ async findAll(): Promise<User[]> {
+ const start = Date.now();
+ this.logger.log('findAll called');
+
+ const users = await this.usersService.findAll();
+
+ this.logger.log(`findAll completed in ${Date.now() - start}ms`);
+ return users;
+ }
+
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<User> {
+ const start = Date.now();
+ this.logger.log(`findOne called with id: ${id}`);
+
+ const user = await this.usersService.findOne(id);
+
+ this.logger.log(`findOne completed in ${Date.now() - start}ms`);
+ return user;
+ }
+ // Repeated in every method!
+}
+
+// Manual response wrapping
+@Get()
+async findAll(): Promise<{ data: User[]; meta: Meta }> {
+ const users = await this.usersService.findAll();
+ return {
+ data: users,
+ meta: { timestamp: new Date(), count: users.length },
+ };
+}
+```
+
+**Correct (use interceptors for cross-cutting concerns):**
+
+```typescript
+// Logging interceptor
+@Injectable()
+export class LoggingInterceptor implements NestInterceptor {
+ private readonly logger = new Logger('HTTP');
+
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
+ const request = context.switchToHttp().getRequest();
+ const { method, url, body } = request;
+ const now = Date.now();
+
+ return next.handle().pipe(
+ tap({
+ next: (data) => {
+ const response = context.switchToHttp().getResponse();
+ this.logger.log(
+ `${method} ${url} ${response.statusCode} - ${Date.now() - now}ms`,
+ );
+ },
+ error: (error) => {
+ this.logger.error(
+ `${method} ${url} ${error.status || 500} - ${Date.now() - now}ms`,
+ error.stack,
+ );
+ },
+ }),
+ );
+ }
+}
+
+// Response transformation interceptor
+@Injectable()
+export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
+ intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
+ return next.handle().pipe(
+ map((data) => ({
+ data,
+ meta: {
+ timestamp: new Date().toISOString(),
+ path: context.switchToHttp().getRequest().url,
+ },
+ })),
+ );
+ }
+}
+
+// Timeout interceptor
+@Injectable()
+export class TimeoutInterceptor implements NestInterceptor {
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
+ return next.handle().pipe(
+ timeout(5000),
+ catchError((err) => {
+ if (err instanceof TimeoutError) {
+ throw new RequestTimeoutException('Request timed out');
+ }
+ throw err;
+ }),
+ );
+ }
+}
+
+// Apply globally or per-controller
+@Module({
+ providers: [
+ { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor },
+ { provide: APP_INTERCEPTOR, useClass: TransformInterceptor },
+ ],
+})
+export class AppModule {}
+
+// Or per-controller
+@Controller('users')
+@UseInterceptors(LoggingInterceptor)
+export class UsersController {
+ @Get()
+ async findAll(): Promise<User[]> {
+ // Clean business logic only
+ return this.usersService.findAll();
+ }
+}
+
+// Custom cache interceptor with TTL
+@Injectable()
+export class HttpCacheInterceptor implements NestInterceptor {
+ constructor(
+ private cacheManager: Cache,
+ private reflector: Reflector,
+ ) {}
+
+ async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
+ const request = context.switchToHttp().getRequest();
+
+ // Only cache GET requests
+ if (request.method !== 'GET') {
+ return next.handle();
+ }
+
+ const cacheKey = this.generateKey(request);
+ const ttl = this.reflector.get<number>('cacheTTL', context.getHandler()) || 300;
+
+ const cached = await this.cacheManager.get(cacheKey);
+ if (cached) {
+ return of(cached);
+ }
+
+ return next.handle().pipe(
+ tap((response) => {
+ this.cacheManager.set(cacheKey, response, ttl);
+ }),
+ );
+ }
+
+ private generateKey(request: Request): string {
+ return `cache:${request.url}:${JSON.stringify(request.query)}`;
+ }
+}
+
+// Usage with custom TTL
+@Get()
+@SetMetadata('cacheTTL', 600)
+@UseInterceptors(HttpCacheInterceptor)
+async findAll(): Promise<User[]> {
+ return this.usersService.findAll();
+}
+
+// Error mapping interceptor
+@Injectable()
+export class ErrorMappingInterceptor implements NestInterceptor {
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
+ return next.handle().pipe(
+ catchError((error) => {
+ if (error instanceof EntityNotFoundError) {
+ throw new NotFoundException(error.message);
+ }
+ if (error instanceof QueryFailedError) {
+ if (error.message.includes('duplicate')) {
+ throw new ConflictException('Resource already exists');
+ }
+ }
+ throw error;
+ }),
+ );
+ }
+}
+```
+
+Reference: [NestJS Interceptors](https://docs.nestjs.com/interceptors)
diff --git a/.agents/skills/nestjs-best-practices/rules/api-use-pipes.md b/.agents/skills/nestjs-best-practices/rules/api-use-pipes.md
new file mode 100644
index 00000000..72b9a6e9
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/api-use-pipes.md
@@ -0,0 +1,205 @@
+---
+title: Use Pipes for Input Transformation
+impact: MEDIUM
+impactDescription: Pipes ensure clean, validated data reaches your handlers
+tags: api, pipes, validation, transformation
+---
+
+## Use Pipes for Input Transformation
+
+Use built-in pipes like `ParseIntPipe`, `ParseUUIDPipe`, and `DefaultValuePipe` for common transformations. Create custom pipes for business-specific transformations. Pipes separate validation/transformation logic from controllers.
+
+**Incorrect (manual type parsing in handlers):**
+
+```typescript
+// Manual type parsing in handlers
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<User> {
+ // Manual validation in every handler
+ const uuid = id.trim();
+ if (!isUUID(uuid)) {
+ throw new BadRequestException('Invalid UUID');
+ }
+ return this.usersService.findOne(uuid);
+ }
+
+ @Get()
+ async findAll(
+ @Query('page') page: string,
+ @Query('limit') limit: string,
+ ): Promise<User[]> {
+ // Manual parsing and defaults
+ const pageNum = parseInt(page) || 1;
+ const limitNum = parseInt(limit) || 10;
+ return this.usersService.findAll(pageNum, limitNum);
+ }
+}
+
+// Type coercion without validation
+@Get()
+async search(@Query('price') price: string): Promise<Product[]> {
+ const priceNum = +price; // NaN if invalid, no error
+ return this.productsService.findByPrice(priceNum);
+}
+```
+
+**Correct (use built-in and custom pipes):**
+
+```typescript
+// Use built-in pipes for common transformations
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(@Param('id', ParseUUIDPipe) id: string): Promise<User> {
+ // id is guaranteed to be a valid UUID
+ return this.usersService.findOne(id);
+ }
+
+ @Get()
+ async findAll(
+ @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
+ @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,
+ ): Promise<User[]> {
+ // Automatic defaults and type conversion
+ return this.usersService.findAll(page, limit);
+ }
+
+ @Get('by-status/:status')
+ async findByStatus(
+ @Param('status', new ParseEnumPipe(UserStatus)) status: UserStatus,
+ ): Promise<User[]> {
+ return this.usersService.findByStatus(status);
+ }
+}
+
+// Custom pipe for business logic
+@Injectable()
+export class ParseDatePipe implements PipeTransform<string, Date> {
+ transform(value: string): Date {
+ const date = new Date(value);
+ if (isNaN(date.getTime())) {
+ throw new BadRequestException('Invalid date format');
+ }
+ return date;
+ }
+}
+
+@Get('reports')
+async getReports(
+ @Query('from', ParseDatePipe) from: Date,
+ @Query('to', ParseDatePipe) to: Date,
+): Promise<Report[]> {
+ return this.reportsService.findBetween(from, to);
+}
+
+// Custom transformation pipes
+@Injectable()
+export class NormalizeEmailPipe implements PipeTransform<string, string> {
+ transform(value: string): string {
+ if (!value) return value;
+ return value.trim().toLowerCase();
+ }
+}
+
+// Parse comma-separated values
+@Injectable()
+export class ParseArrayPipe implements PipeTransform<string, string[]> {
+ transform(value: string): string[] {
+ if (!value) return [];
+ return value.split(',').map((v) => v.trim()).filter(Boolean);
+ }
+}
+
+@Get('products')
+async findProducts(
+ @Query('ids', ParseArrayPipe) ids: string[],
+ @Query('email', NormalizeEmailPipe) email: string,
+): Promise<Product[]> {
+ // ids is already an array, email is normalized
+ return this.productsService.findByIds(ids);
+}
+
+// Sanitize HTML input
+@Injectable()
+export class SanitizeHtmlPipe implements PipeTransform<string, string> {
+ transform(value: string): string {
+ if (!value) return value;
+ return sanitizeHtml(value, { allowedTags: [] });
+ }
+}
+
+// Global validation pipe with transformation
+app.useGlobalPipes(
+ new ValidationPipe({
+ whitelist: true, // Strip non-DTO properties
+ transform: true, // Auto-transform to DTO types
+ transformOptions: {
+ enableImplicitConversion: true, // Convert query strings to numbers
+ },
+ forbidNonWhitelisted: true, // Throw on extra properties
+ }),
+);
+
+// DTO with transformation decorators
+export class FindProductsDto {
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(1)
+ page?: number = 1;
+
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(1)
+ @Max(100)
+ limit?: number = 10;
+
+ @IsOptional()
+ @Transform(({ value }) => value?.toLowerCase())
+ @IsString()
+ search?: string;
+
+ @IsOptional()
+ @Transform(({ value }) => value?.split(','))
+ @IsArray()
+ @IsString({ each: true })
+ categories?: string[];
+}
+
+@Get()
+async findAll(@Query() dto: FindProductsDto): Promise<Product[]> {
+ // dto is already transformed and validated
+ return this.productsService.findAll(dto);
+}
+
+// Pipe error customization
+@Injectable()
+export class CustomParseIntPipe extends ParseIntPipe {
+ constructor() {
+ super({
+ exceptionFactory: (error) =>
+ new BadRequestException(`${error} must be a valid integer`),
+ });
+ }
+}
+
+// Or use options on built-in pipes
+@Get(':id')
+async findOne(
+ @Param(
+ 'id',
+ new ParseIntPipe({
+ errorHttpStatusCode: HttpStatus.NOT_ACCEPTABLE,
+ exceptionFactory: () => new NotAcceptableException('ID must be numeric'),
+ }),
+ )
+ id: number,
+): Promise<Item> {
+ return this.itemsService.findOne(id);
+}
+```
+
+Reference: [NestJS Pipes](https://docs.nestjs.com/pipes)
diff --git a/.agents/skills/nestjs-best-practices/rules/api-versioning.md b/.agents/skills/nestjs-best-practices/rules/api-versioning.md
new file mode 100644
index 00000000..5e4546ca
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/api-versioning.md
@@ -0,0 +1,191 @@
+---
+title: Use API Versioning for Breaking Changes
+impact: MEDIUM
+impactDescription: Versioning allows you to evolve APIs without breaking existing clients
+tags: api, versioning, breaking-changes, compatibility
+---
+
+## Use API Versioning for Breaking Changes
+
+Use NestJS built-in versioning when making breaking changes to your API. Choose a versioning strategy (URI, header, or media type) and apply it consistently. This allows old clients to continue working while new clients use updated endpoints.
+
+**Incorrect (breaking changes without versioning):**
+
+```typescript
+// Breaking changes without versioning
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<User> {
+ // Original response: { id, name, email }
+ // Later changed to: { id, firstName, lastName, emailAddress }
+ // Old clients break!
+ return this.usersService.findOne(id);
+ }
+}
+
+// Manual versioning in routes
+@Controller('v1/users')
+export class UsersV1Controller {}
+
+@Controller('v2/users')
+export class UsersV2Controller {}
+// Inconsistent, error-prone, hard to maintain
+```
+
+**Correct (use NestJS built-in versioning):**
+
+```typescript
+// Enable versioning in main.ts
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule);
+
+ // URI versioning: /v1/users, /v2/users
+ app.enableVersioning({
+ type: VersioningType.URI,
+ defaultVersion: '1',
+ });
+
+ // Or header versioning: X-API-Version: 1
+ app.enableVersioning({
+ type: VersioningType.HEADER,
+ header: 'X-API-Version',
+ defaultVersion: '1',
+ });
+
+ // Or media type: Accept: application/json;v=1
+ app.enableVersioning({
+ type: VersioningType.MEDIA_TYPE,
+ key: 'v=',
+ defaultVersion: '1',
+ });
+
+ await app.listen(3000);
+}
+
+// Version-specific controllers
+@Controller('users')
+@Version('1')
+export class UsersV1Controller {
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<UserV1Response> {
+ const user = await this.usersService.findOne(id);
+ // V1 response format
+ return {
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ };
+ }
+}
+
+@Controller('users')
+@Version('2')
+export class UsersV2Controller {
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<UserV2Response> {
+ const user = await this.usersService.findOne(id);
+ // V2 response format with breaking changes
+ return {
+ id: user.id,
+ firstName: user.firstName,
+ lastName: user.lastName,
+ emailAddress: user.email,
+ createdAt: user.createdAt,
+ };
+ }
+}
+
+// Per-route versioning - different versions for different routes
+@Controller('users')
+export class UsersController {
+ @Get()
+ @Version('1')
+ findAllV1(): Promise<UserV1Response[]> {
+ return this.usersService.findAllV1();
+ }
+
+ @Get()
+ @Version('2')
+ findAllV2(): Promise<UserV2Response[]> {
+ return this.usersService.findAllV2();
+ }
+
+ @Get(':id')
+ @Version(['1', '2']) // Same handler for multiple versions
+ findOne(@Param('id') id: string): Promise<User> {
+ return this.usersService.findOne(id);
+ }
+
+ @Post()
+ @Version(VERSION_NEUTRAL) // Available in all versions
+ create(@Body() dto: CreateUserDto): Promise<User> {
+ return this.usersService.create(dto);
+ }
+}
+
+// Shared service with version-specific logic
+@Injectable()
+export class UsersService {
+ async findOne(id: string, version: string): Promise<any> {
+ const user = await this.repo.findOne({ where: { id } });
+
+ if (version === '1') {
+ return this.toV1Response(user);
+ }
+ return this.toV2Response(user);
+ }
+
+ private toV1Response(user: User): UserV1Response {
+ return {
+ id: user.id,
+ name: `${user.firstName} ${user.lastName}`,
+ email: user.email,
+ };
+ }
+
+ private toV2Response(user: User): UserV2Response {
+ return {
+ id: user.id,
+ firstName: user.firstName,
+ lastName: user.lastName,
+ emailAddress: user.email,
+ createdAt: user.createdAt,
+ };
+ }
+}
+
+// Controller extracts version
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(
+ @Param('id') id: string,
+ @Headers('X-API-Version') version: string = '1',
+ ): Promise<any> {
+ return this.usersService.findOne(id, version);
+ }
+}
+
+// Deprecation strategy - mark old versions as deprecated
+@Controller('users')
+@Version('1')
+@UseInterceptors(DeprecationInterceptor)
+export class UsersV1Controller {
+ // All V1 routes will include deprecation warning
+}
+
+@Injectable()
+export class DeprecationInterceptor implements NestInterceptor {
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
+ const response = context.switchToHttp().getResponse();
+ response.setHeader('Deprecation', 'true');
+ response.setHeader('Sunset', 'Sat, 1 Jan 2025 00:00:00 GMT');
+ response.setHeader('Link', '</v2/users>; rel="successor-version"');
+
+ return next.handle();
+ }
+}
+```
+
+Reference: [NestJS Versioning](https://docs.nestjs.com/techniques/versioning)
diff --git a/.agents/skills/nestjs-best-practices/rules/arch-avoid-circular-deps.md b/.agents/skills/nestjs-best-practices/rules/arch-avoid-circular-deps.md
new file mode 100644
index 00000000..aea5c8be
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/arch-avoid-circular-deps.md
@@ -0,0 +1,80 @@
+---
+title: Avoid Circular Dependencies
+impact: CRITICAL
+impactDescription: "#1 cause of runtime crashes"
+tags: architecture, modules, dependencies
+---
+
+## Avoid Circular Dependencies
+
+Circular dependencies occur when Module A imports Module B, and Module B imports Module A (directly or transitively). NestJS can sometimes resolve these through forward references, but they indicate architectural problems and should be avoided. This is the #1 cause of runtime crashes in NestJS applications.
+
+**Incorrect (circular module imports):**
+
+```typescript
+// users.module.ts
+@Module({
+ imports: [OrdersModule], // Orders needs Users, Users needs Orders = circular
+ providers: [UsersService],
+ exports: [UsersService],
+})
+export class UsersModule {}
+
+// orders.module.ts
+@Module({
+ imports: [UsersModule], // Circular dependency!
+ providers: [OrdersService],
+ exports: [OrdersService],
+})
+export class OrdersModule {}
+```
+
+**Correct (extract shared logic or use events):**
+
+```typescript
+// Option 1: Extract shared logic to a third module
+// shared.module.ts
+@Module({
+ providers: [SharedService],
+ exports: [SharedService],
+})
+export class SharedModule {}
+
+// users.module.ts
+@Module({
+ imports: [SharedModule],
+ providers: [UsersService],
+})
+export class UsersModule {}
+
+// orders.module.ts
+@Module({
+ imports: [SharedModule],
+ providers: [OrdersService],
+})
+export class OrdersModule {}
+
+// Option 2: Use events for decoupled communication
+// users.service.ts
+@Injectable()
+export class UsersService {
+ constructor(private eventEmitter: EventEmitter2) {}
+
+ async createUser(data: CreateUserDto) {
+ const user = await this.userRepo.save(data);
+ this.eventEmitter.emit('user.created', user);
+ return user;
+ }
+}
+
+// orders.service.ts
+@Injectable()
+export class OrdersService {
+ @OnEvent('user.created')
+ handleUserCreated(user: User) {
+ // React to user creation without direct dependency
+ }
+}
+```
+
+Reference: [NestJS Circular Dependency](https://docs.nestjs.com/fundamentals/circular-dependency)
diff --git a/.agents/skills/nestjs-best-practices/rules/arch-feature-modules.md b/.agents/skills/nestjs-best-practices/rules/arch-feature-modules.md
new file mode 100644
index 00000000..4f3ef567
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/arch-feature-modules.md
@@ -0,0 +1,82 @@
+---
+title: Organize by Feature Modules
+impact: CRITICAL
+impactDescription: "3-5x faster onboarding and development"
+tags: architecture, modules, organization
+---
+
+## Organize by Feature Modules
+
+Organize your application into feature modules that encapsulate related functionality. Each feature module should be self-contained with its own controllers, services, entities, and DTOs. Avoid organizing by technical layer (all controllers together, all services together). This enables 3-5x faster onboarding and feature development.
+
+**Incorrect (technical layer organization):**
+
+```typescript
+// Technical layer organization (anti-pattern)
+src/
+├── controllers/
+│ ├── users.controller.ts
+│ ├── orders.controller.ts
+│ └── products.controller.ts
+├── services/
+│ ├── users.service.ts
+│ ├── orders.service.ts
+│ └── products.service.ts
+├── entities/
+│ ├── user.entity.ts
+│ ├── order.entity.ts
+│ └── product.entity.ts
+└── app.module.ts // Imports everything directly
+```
+
+**Correct (feature module organization):**
+
+```typescript
+// Feature module organization
+src/
+├── users/
+│ ├── dto/
+│ │ ├── create-user.dto.ts
+│ │ └── update-user.dto.ts
+│ ├── entities/
+│ │ └── user.entity.ts
+│ ├── users.controller.ts
+│ ├── users.service.ts
+│ ├── users.repository.ts
+│ └── users.module.ts
+├── orders/
+│ ├── dto/
+│ ├── entities/
+│ ├── orders.controller.ts
+│ ├── orders.service.ts
+│ └── orders.module.ts
+├── shared/
+│ ├── guards/
+│ ├── interceptors/
+│ ├── filters/
+│ └── shared.module.ts
+└── app.module.ts
+
+// users.module.ts
+@Module({
+ imports: [TypeOrmModule.forFeature([User])],
+ controllers: [UsersController],
+ providers: [UsersService, UsersRepository],
+ exports: [UsersService], // Only export what others need
+})
+export class UsersModule {}
+
+// app.module.ts
+@Module({
+ imports: [
+ ConfigModule.forRoot(),
+ TypeOrmModule.forRoot(),
+ UsersModule,
+ OrdersModule,
+ SharedModule,
+ ],
+})
+export class AppModule {}
+```
+
+Reference: [NestJS Modules](https://docs.nestjs.com/modules)
diff --git a/.agents/skills/nestjs-best-practices/rules/arch-module-sharing.md b/.agents/skills/nestjs-best-practices/rules/arch-module-sharing.md
new file mode 100644
index 00000000..06ab7678
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/arch-module-sharing.md
@@ -0,0 +1,141 @@
+---
+title: Use Proper Module Sharing Patterns
+impact: CRITICAL
+impactDescription: Prevents duplicate instances, memory leaks, and state inconsistency
+tags: architecture, modules, sharing, exports
+---
+
+## Use Proper Module Sharing Patterns
+
+NestJS modules are singletons by default. When a service is properly exported from a module and that module is imported elsewhere, the same instance is shared. However, providing a service in multiple modules creates separate instances, leading to memory waste, state inconsistency, and confusing behavior. Always encapsulate services in dedicated modules, export them explicitly, and import the module where needed.
+
+**Incorrect (service provided in multiple modules):**
+
+```typescript
+// StorageService provided directly in multiple modules - WRONG
+// storage.service.ts
+@Injectable()
+export class StorageService {
+ private cache = new Map(); // Each instance has separate state!
+
+ store(key: string, value: any) {
+ this.cache.set(key, value);
+ }
+}
+
+// app.module.ts
+@Module({
+ providers: [StorageService], // Instance #1
+ controllers: [AppController],
+})
+export class AppModule {}
+
+// videos.module.ts
+@Module({
+ providers: [StorageService], // Instance #2 - different from AppModule!
+ controllers: [VideosController],
+})
+export class VideosModule {}
+
+// Problems:
+// 1. Two separate StorageService instances exist
+// 2. cache.set() in VideosModule doesn't affect AppModule's cache
+// 3. Memory wasted on duplicate instances
+// 4. Debugging nightmares when state doesn't sync
+```
+
+**Correct (dedicated module with exports):**
+
+```typescript
+// storage/storage.module.ts
+@Module({
+ providers: [StorageService],
+ exports: [StorageService], // Make available to importers
+})
+export class StorageModule {}
+
+// videos/videos.module.ts
+@Module({
+ imports: [StorageModule], // Import the module, not the service
+ controllers: [VideosController],
+ providers: [VideosService],
+})
+export class VideosModule {}
+
+// channels/channels.module.ts
+@Module({
+ imports: [StorageModule], // Same instance shared
+ controllers: [ChannelsController],
+ providers: [ChannelsService],
+})
+export class ChannelsModule {}
+
+// app.module.ts
+@Module({
+ imports: [
+ StorageModule, // Only if AppModule itself needs StorageService
+ VideosModule,
+ ChannelsModule,
+ ],
+})
+export class AppModule {}
+
+// Now all modules share the SAME StorageService instance
+```
+
+**When to use @Global() (sparingly):**
+
+```typescript
+// ONLY for truly cross-cutting concerns
+@Global()
+@Module({
+ providers: [ConfigService, LoggerService],
+ exports: [ConfigService, LoggerService],
+})
+export class CoreModule {}
+
+// Import once in AppModule
+@Module({
+ imports: [CoreModule], // Registered globally, available everywhere
+})
+export class AppModule {}
+
+// Other modules don't need to import CoreModule
+@Module({
+ controllers: [UsersController],
+ providers: [UsersService], // Can inject ConfigService without importing
+})
+export class UsersModule {}
+
+// WARNING: Don't make everything global!
+// - Hides dependencies (can't see what a module needs from imports)
+// - Makes testing harder
+// - Reserve for: config, logging, database connections
+```
+
+**Module re-exporting pattern:**
+
+```typescript
+// common.module.ts - shared utilities
+@Module({
+ providers: [DateService, ValidationService],
+ exports: [DateService, ValidationService],
+})
+export class CommonModule {}
+
+// core.module.ts - re-exports common for convenience
+@Module({
+ imports: [CommonModule, DatabaseModule],
+ exports: [CommonModule, DatabaseModule], // Re-export for consumers
+})
+export class CoreModule {}
+
+// feature.module.ts - imports CoreModule, gets both
+@Module({
+ imports: [CoreModule], // Gets CommonModule + DatabaseModule
+ controllers: [FeatureController],
+})
+export class FeatureModule {}
+```
+
+Reference: [NestJS Modules](https://docs.nestjs.com/modules#shared-modules)
diff --git a/.agents/skills/nestjs-best-practices/rules/arch-single-responsibility.md b/.agents/skills/nestjs-best-practices/rules/arch-single-responsibility.md
new file mode 100644
index 00000000..6ffc46eb
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/arch-single-responsibility.md
@@ -0,0 +1,106 @@
+---
+title: Single Responsibility for Services
+impact: CRITICAL
+impactDescription: "40%+ improvement in testability"
+tags: architecture, services, single-responsibility
+---
+
+## Single Responsibility for Services
+
+Each service should have a single, well-defined responsibility. Avoid "god services" that handle multiple unrelated concerns. If a service name includes "And" or handles more than one domain concept, it likely violates single responsibility. This reduces complexity and improves testability by 40%+.
+
+**Incorrect (god service anti-pattern):**
+
+```typescript
+// God service anti-pattern
+@Injectable()
+export class UserAndOrderService {
+ constructor(
+ private userRepo: UserRepository,
+ private orderRepo: OrderRepository,
+ private mailer: MailService,
+ private payment: PaymentService,
+ ) {}
+
+ async createUser(dto: CreateUserDto) {
+ const user = await this.userRepo.save(dto);
+ await this.mailer.sendWelcome(user);
+ return user;
+ }
+
+ async createOrder(userId: string, dto: CreateOrderDto) {
+ const order = await this.orderRepo.save({ userId, ...dto });
+ await this.payment.charge(order);
+ await this.mailer.sendOrderConfirmation(order);
+ return order;
+ }
+
+ async calculateOrderStats(userId: string) {
+ // Stats logic mixed in
+ }
+
+ async validatePayment(orderId: string) {
+ // Payment logic mixed in
+ }
+}
+```
+
+**Correct (focused services with single responsibility):**
+
+```typescript
+// Focused services with single responsibility
+@Injectable()
+export class UsersService {
+ constructor(private userRepo: UserRepository) {}
+
+ async create(dto: CreateUserDto): Promise<User> {
+ return this.userRepo.save(dto);
+ }
+
+ async findById(id: string): Promise<User> {
+ return this.userRepo.findOneOrFail({ where: { id } });
+ }
+}
+
+@Injectable()
+export class OrdersService {
+ constructor(private orderRepo: OrderRepository) {}
+
+ async create(userId: string, dto: CreateOrderDto): Promise<Order> {
+ return this.orderRepo.save({ userId, ...dto });
+ }
+
+ async findByUser(userId: string): Promise<Order[]> {
+ return this.orderRepo.find({ where: { userId } });
+ }
+}
+
+@Injectable()
+export class OrderStatsService {
+ constructor(private orderRepo: OrderRepository) {}
+
+ async calculateForUser(userId: string): Promise<OrderStats> {
+ // Focused stats calculation
+ }
+}
+
+// Orchestration in controller or dedicated orchestrator
+@Controller('orders')
+export class OrdersController {
+ constructor(
+ private orders: OrdersService,
+ private payment: PaymentService,
+ private notifications: NotificationService,
+ ) {}
+
+ @Post()
+ async create(@CurrentUser() user: User, @Body() dto: CreateOrderDto) {
+ const order = await this.orders.create(user.id, dto);
+ await this.payment.charge(order);
+ await this.notifications.sendOrderConfirmation(order);
+ return order;
+ }
+}
+```
+
+Reference: [NestJS Providers](https://docs.nestjs.com/providers)
diff --git a/.agents/skills/nestjs-best-practices/rules/arch-use-events.md b/.agents/skills/nestjs-best-practices/rules/arch-use-events.md
new file mode 100644
index 00000000..f8cda270
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/arch-use-events.md
@@ -0,0 +1,108 @@
+---
+title: Use Event-Driven Architecture for Decoupling
+impact: MEDIUM-HIGH
+impactDescription: Enables async processing and modularity
+tags: architecture, events, decoupling
+---
+
+## Use Event-Driven Architecture for Decoupling
+
+Use `@nestjs/event-emitter` for intra-service events and message brokers for inter-service communication. Events allow modules to react to changes without direct dependencies, improving modularity and enabling async processing.
+
+**Incorrect (direct service coupling):**
+
+```typescript
+// Direct service coupling
+@Injectable()
+export class OrdersService {
+ constructor(
+ private inventoryService: InventoryService,
+ private emailService: EmailService,
+ private analyticsService: AnalyticsService,
+ private notificationService: NotificationService,
+ private loyaltyService: LoyaltyService,
+ ) {}
+
+ async createOrder(dto: CreateOrderDto): Promise<Order> {
+ const order = await this.repo.save(dto);
+
+ // Tight coupling - OrdersService knows about all consumers
+ await this.inventoryService.reserve(order.items);
+ await this.emailService.sendConfirmation(order);
+ await this.analyticsService.track('order_created', order);
+ await this.notificationService.push(order.userId, 'Order placed');
+ await this.loyaltyService.addPoints(order.userId, order.total);
+
+ // Adding new behavior requires modifying this service
+ return order;
+ }
+}
+```
+
+**Correct (event-driven decoupling):**
+
+```typescript
+// Use EventEmitter for decoupling
+import { EventEmitter2 } from '@nestjs/event-emitter';
+
+// Define event
+export class OrderCreatedEvent {
+ constructor(
+ public readonly orderId: string,
+ public readonly userId: string,
+ public readonly items: OrderItem[],
+ public readonly total: number,
+ ) {}
+}
+
+// Service emits events
+@Injectable()
+export class OrdersService {
+ constructor(
+ private eventEmitter: EventEmitter2,
+ private repo: Repository<Order>,
+ ) {}
+
+ async createOrder(dto: CreateOrderDto): Promise<Order> {
+ const order = await this.repo.save(dto);
+
+ // Emit event - no knowledge of consumers
+ this.eventEmitter.emit(
+ 'order.created',
+ new OrderCreatedEvent(order.id, order.userId, order.items, order.total),
+ );
+
+ return order;
+ }
+}
+
+// Listeners in separate modules
+@Injectable()
+export class InventoryListener {
+ @OnEvent('order.created')
+ async handleOrderCreated(event: OrderCreatedEvent): Promise<void> {
+ await this.inventoryService.reserve(event.items);
+ }
+}
+
+@Injectable()
+export class EmailListener {
+ @OnEvent('order.created')
+ async handleOrderCreated(event: OrderCreatedEvent): Promise<void> {
+ await this.emailService.sendConfirmation(event.orderId);
+ }
+}
+
+@Injectable()
+export class AnalyticsListener {
+ @OnEvent('order.created')
+ async handleOrderCreated(event: OrderCreatedEvent): Promise<void> {
+ await this.analyticsService.track('order_created', {
+ orderId: event.orderId,
+ total: event.total,
+ });
+ }
+}
+```
+
+Reference: [NestJS Events](https://docs.nestjs.com/techniques/events)
diff --git a/.agents/skills/nestjs-best-practices/rules/arch-use-repository-pattern.md b/.agents/skills/nestjs-best-practices/rules/arch-use-repository-pattern.md
new file mode 100644
index 00000000..75df3810
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/arch-use-repository-pattern.md
@@ -0,0 +1,97 @@
+---
+title: Use Repository Pattern for Data Access
+impact: HIGH
+impactDescription: Decouples business logic from database
+tags: architecture, repository, data-access
+---
+
+## Use Repository Pattern for Data Access
+
+Create custom repositories to encapsulate complex queries and database logic. This keeps services focused on business logic, makes testing easier with mock repositories, and allows changing database implementations without affecting business code.
+
+**Incorrect (complex queries in services):**
+
+```typescript
+// Complex queries in services
+@Injectable()
+export class UsersService {
+ constructor(
+ @InjectRepository(User) private repo: Repository<User>,
+ ) {}
+
+ async findActiveWithOrders(minOrders: number): Promise<User[]> {
+ // Complex query logic mixed with business logic
+ return this.repo
+ .createQueryBuilder('user')
+ .leftJoinAndSelect('user.orders', 'order')
+ .where('user.isActive = :active', { active: true })
+ .andWhere('user.deletedAt IS NULL')
+ .groupBy('user.id')
+ .having('COUNT(order.id) >= :min', { min: minOrders })
+ .orderBy('user.createdAt', 'DESC')
+ .getMany();
+ }
+
+ // Service becomes bloated with query logic
+}
+```
+
+**Correct (custom repository with encapsulated queries):**
+
+```typescript
+// Custom repository with encapsulated queries
+@Injectable()
+export class UsersRepository {
+ constructor(
+ @InjectRepository(User) private repo: Repository<User>,
+ ) {}
+
+ async findById(id: string): Promise<User | null> {
+ return this.repo.findOne({ where: { id } });
+ }
+
+ async findByEmail(email: string): Promise<User | null> {
+ return this.repo.findOne({ where: { email } });
+ }
+
+ async findActiveWithMinOrders(minOrders: number): Promise<User[]> {
+ return this.repo
+ .createQueryBuilder('user')
+ .leftJoinAndSelect('user.orders', 'order')
+ .where('user.isActive = :active', { active: true })
+ .andWhere('user.deletedAt IS NULL')
+ .groupBy('user.id')
+ .having('COUNT(order.id) >= :min', { min: minOrders })
+ .orderBy('user.createdAt', 'DESC')
+ .getMany();
+ }
+
+ async save(user: User): Promise<User> {
+ return this.repo.save(user);
+ }
+}
+
+// Clean service with business logic only
+@Injectable()
+export class UsersService {
+ constructor(private usersRepo: UsersRepository) {}
+
+ async getActiveUsersWithOrders(): Promise<User[]> {
+ return this.usersRepo.findActiveWithMinOrders(1);
+ }
+
+ async create(dto: CreateUserDto): Promise<User> {
+ const existing = await this.usersRepo.findByEmail(dto.email);
+ if (existing) {
+ throw new ConflictException('Email already registered');
+ }
+
+ const user = new User();
+ user.email = dto.email;
+ user.name = dto.name;
+ return this.usersRepo.save(user);
+ }
+}
+```
+
+Reference: [Repository Pattern](https://martinfowler.com/eaaCatalog/repository.html)
diff --git a/.agents/skills/nestjs-best-practices/rules/db-avoid-n-plus-one.md b/.agents/skills/nestjs-best-practices/rules/db-avoid-n-plus-one.md
new file mode 100644
index 00000000..a93ec4b5
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/db-avoid-n-plus-one.md
@@ -0,0 +1,139 @@
+---
+title: Avoid N+1 Query Problems
+impact: HIGH
+impactDescription: N+1 queries are one of the most common performance killers
+tags: database, n-plus-one, queries, performance
+---
+
+## Avoid N+1 Query Problems
+
+N+1 queries occur when you fetch a list of entities, then make an additional query for each entity to load related data. Use eager loading with `relations`, query builder joins, or DataLoader to batch queries efficiently.
+
+**Incorrect (lazy loading in loops causes N+1):**
+
+```typescript
+// Lazy loading in loops causes N+1
+@Injectable()
+export class OrdersService {
+ async getOrdersWithItems(userId: string): Promise<Order[]> {
+ const orders = await this.orderRepo.find({ where: { userId } });
+ // 1 query for orders
+
+ for (const order of orders) {
+ // N additional queries - one per order!
+ order.items = await this.itemRepo.find({ where: { orderId: order.id } });
+ }
+
+ return orders;
+ }
+}
+
+// Accessing lazy relations without loading
+@Controller('users')
+export class UsersController {
+ @Get()
+ async findAll(): Promise<User[]> {
+ const users = await this.userRepo.find();
+ // If User.posts is lazy-loaded, serializing triggers N queries
+ return users; // Each user.posts access = 1 query
+ }
+}
+```
+
+**Correct (use relations for eager loading):**
+
+```typescript
+// Use relations option for eager loading
+@Injectable()
+export class OrdersService {
+ async getOrdersWithItems(userId: string): Promise<Order[]> {
+ // Single query with JOIN
+ return this.orderRepo.find({
+ where: { userId },
+ relations: ['items', 'items.product'],
+ });
+ }
+}
+
+// Use QueryBuilder for complex joins
+@Injectable()
+export class UsersService {
+ async getUsersWithPostCounts(): Promise<UserWithPostCount[]> {
+ return this.userRepo
+ .createQueryBuilder('user')
+ .leftJoin('user.posts', 'post')
+ .select('user.id', 'id')
+ .addSelect('user.name', 'name')
+ .addSelect('COUNT(post.id)', 'postCount')
+ .groupBy('user.id')
+ .getRawMany();
+ }
+
+ async getActiveUsersWithPosts(): Promise<User[]> {
+ return this.userRepo
+ .createQueryBuilder('user')
+ .leftJoinAndSelect('user.posts', 'post')
+ .leftJoinAndSelect('post.comments', 'comment')
+ .where('user.isActive = :active', { active: true })
+ .andWhere('post.status = :status', { status: 'published' })
+ .getMany();
+ }
+}
+
+// Use find options for specific fields
+async getOrderSummaries(userId: string): Promise<OrderSummary[]> {
+ return this.orderRepo.find({
+ where: { userId },
+ relations: ['items'],
+ select: {
+ id: true,
+ total: true,
+ status: true,
+ items: {
+ id: true,
+ quantity: true,
+ price: true,
+ },
+ },
+ });
+}
+
+// Use DataLoader for GraphQL to batch and cache queries
+import DataLoader from 'dataloader';
+
+@Injectable({ scope: Scope.REQUEST })
+export class PostsLoader {
+ constructor(private postsService: PostsService) {}
+
+ readonly batchPosts = new DataLoader<string, Post[]>(async (userIds) => {
+ // Single query for all users' posts
+ const posts = await this.postsService.findByUserIds([...userIds]);
+
+ // Group by userId
+ const postsMap = new Map<string, Post[]>();
+ for (const post of posts) {
+ const userPosts = postsMap.get(post.userId) || [];
+ userPosts.push(post);
+ postsMap.set(post.userId, userPosts);
+ }
+
+ // Return in same order as input
+ return userIds.map((id) => postsMap.get(id) || []);
+ });
+}
+
+// In resolver
+@ResolveField()
+async posts(@Parent() user: User): Promise<Post[]> {
+ // DataLoader batches multiple calls into single query
+ return this.postsLoader.batchPosts.load(user.id);
+}
+
+// Enable query logging in development to detect N+1
+TypeOrmModule.forRoot({
+ logging: ['query', 'error'],
+ logger: 'advanced-console',
+});
+```
+
+Reference: [TypeORM Relations](https://typeorm.io/relations)
diff --git a/.agents/skills/nestjs-best-practices/rules/db-use-migrations.md b/.agents/skills/nestjs-best-practices/rules/db-use-migrations.md
new file mode 100644
index 00000000..4c3b7240
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/db-use-migrations.md
@@ -0,0 +1,129 @@
+---
+title: Use Database Migrations
+impact: HIGH
+impactDescription: Enables safe, repeatable database schema changes
+tags: database, migrations, typeorm, schema
+---
+
+## Use Database Migrations
+
+Never use `synchronize: true` in production. Use migrations for all schema changes. Migrations provide version control for your database, enable safe rollbacks, and ensure consistency across all environments.
+
+**Incorrect (using synchronize or manual SQL):**
+
+```typescript
+// Use synchronize in production
+TypeOrmModule.forRoot({
+ type: 'postgres',
+ synchronize: true, // DANGEROUS in production!
+ // Can drop columns, tables, or data
+});
+
+// Manual SQL in production
+@Injectable()
+export class DatabaseService {
+ async addColumn(): Promise<void> {
+ await this.dataSource.query('ALTER TABLE users ADD COLUMN age INT');
+ // No version control, no rollback, inconsistent across envs
+ }
+}
+
+// Modify entities without migration
+@Entity()
+export class User {
+ @Column()
+ email: string;
+
+ @Column() // Added without migration
+ newField: string; // Will crash in production if synchronize is false
+}
+```
+
+**Correct (use migrations for all schema changes):**
+
+```typescript
+// Configure TypeORM for migrations
+// data-source.ts
+export const dataSource = new DataSource({
+ type: 'postgres',
+ host: process.env.DB_HOST,
+ port: parseInt(process.env.DB_PORT),
+ username: process.env.DB_USERNAME,
+ password: process.env.DB_PASSWORD,
+ database: process.env.DB_NAME,
+ entities: ['dist/**/*.entity.js'],
+ migrations: ['dist/migrations/*.js'],
+ synchronize: false, // Always false in production
+ migrationsRun: true, // Run migrations on startup
+});
+
+// app.module.ts
+TypeOrmModule.forRootAsync({
+ inject: [ConfigService],
+ useFactory: (config: ConfigService) => ({
+ type: 'postgres',
+ host: config.get('DB_HOST'),
+ synchronize: config.get('NODE_ENV') === 'development', // Only in dev
+ migrations: ['dist/migrations/*.js'],
+ migrationsRun: true,
+ }),
+});
+
+// migrations/1705312800000-AddUserAge.ts
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+export class AddUserAge1705312800000 implements MigrationInterface {
+ name = 'AddUserAge1705312800000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ // Add column with default to handle existing rows
+ await queryRunner.query(`
+ ALTER TABLE "users" ADD "age" integer DEFAULT 0
+ `);
+
+ // Add index for frequently queried columns
+ await queryRunner.query(`
+ CREATE INDEX "IDX_users_age" ON "users" ("age")
+ `);
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ // Always implement down for rollback
+ await queryRunner.query(`DROP INDEX "IDX_users_age"`);
+ await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "age"`);
+ }
+}
+
+// Safe column rename (two-step)
+export class RenameNameToFullName1705312900000 implements MigrationInterface {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ // Step 1: Add new column
+ await queryRunner.query(`
+ ALTER TABLE "users" ADD "full_name" varchar(255)
+ `);
+
+ // Step 2: Copy data
+ await queryRunner.query(`
+ UPDATE "users" SET "full_name" = "name"
+ `);
+
+ // Step 3: Add NOT NULL constraint
+ await queryRunner.query(`
+ ALTER TABLE "users" ALTER COLUMN "full_name" SET NOT NULL
+ `);
+
+ // Step 4: Drop old column (after verifying app works)
+ await queryRunner.query(`
+ ALTER TABLE "users" DROP COLUMN "name"
+ `);
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`ALTER TABLE "users" ADD "name" varchar(255)`);
+ await queryRunner.query(`UPDATE "users" SET "name" = "full_name"`);
+ await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "full_name"`);
+ }
+}
+```
+
+Reference: [TypeORM Migrations](https://typeorm.io/migrations)
diff --git a/.agents/skills/nestjs-best-practices/rules/db-use-transactions.md b/.agents/skills/nestjs-best-practices/rules/db-use-transactions.md
new file mode 100644
index 00000000..543bf974
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/db-use-transactions.md
@@ -0,0 +1,140 @@
+---
+title: Use Transactions for Multi-Step Operations
+impact: HIGH
+impactDescription: Ensures data consistency in multi-step operations
+tags: database, transactions, typeorm, consistency
+---
+
+## Use Transactions for Multi-Step Operations
+
+When multiple database operations must succeed or fail together, wrap them in a transaction. This prevents partial updates that leave your data in an inconsistent state. Use TypeORM's transaction APIs or the DataSource query runner for complex scenarios.
+
+**Incorrect (multiple saves without transaction):**
+
+```typescript
+// Multiple saves without transaction
+@Injectable()
+export class OrdersService {
+ async createOrder(userId: string, items: OrderItem[]): Promise<Order> {
+ // If any step fails, data is inconsistent
+ const order = await this.orderRepo.save({ userId, status: 'pending' });
+
+ for (const item of items) {
+ await this.orderItemRepo.save({ orderId: order.id, ...item });
+ await this.inventoryRepo.decrement({ productId: item.productId }, 'stock', item.quantity);
+ }
+
+ await this.paymentService.charge(order.id);
+ // If payment fails, order and inventory are already modified!
+
+ return order;
+ }
+}
+```
+
+**Correct (use DataSource.transaction for automatic rollback):**
+
+```typescript
+// Use DataSource.transaction() for automatic rollback
+@Injectable()
+export class OrdersService {
+ constructor(private dataSource: DataSource) {}
+
+ async createOrder(userId: string, items: OrderItem[]): Promise<Order> {
+ return this.dataSource.transaction(async (manager) => {
+ // All operations use the same transactional manager
+ const order = await manager.save(Order, { userId, status: 'pending' });
+
+ for (const item of items) {
+ await manager.save(OrderItem, { orderId: order.id, ...item });
+ await manager.decrement(
+ Inventory,
+ { productId: item.productId },
+ 'stock',
+ item.quantity,
+ );
+ }
+
+ // If this throws, everything rolls back
+ await this.paymentService.chargeWithManager(manager, order.id);
+
+ return order;
+ });
+ }
+}
+
+// QueryRunner for manual transaction control
+@Injectable()
+export class TransferService {
+ constructor(private dataSource: DataSource) {}
+
+ async transfer(fromId: string, toId: string, amount: number): Promise<void> {
+ const queryRunner = this.dataSource.createQueryRunner();
+ await queryRunner.connect();
+ await queryRunner.startTransaction();
+
+ try {
+ // Debit source account
+ await queryRunner.manager.decrement(
+ Account,
+ { id: fromId },
+ 'balance',
+ amount,
+ );
+
+ // Verify sufficient funds
+ const source = await queryRunner.manager.findOne(Account, {
+ where: { id: fromId },
+ });
+ if (source.balance < 0) {
+ throw new BadRequestException('Insufficient funds');
+ }
+
+ // Credit destination account
+ await queryRunner.manager.increment(
+ Account,
+ { id: toId },
+ 'balance',
+ amount,
+ );
+
+ // Log the transaction
+ await queryRunner.manager.save(TransactionLog, {
+ fromId,
+ toId,
+ amount,
+ timestamp: new Date(),
+ });
+
+ await queryRunner.commitTransaction();
+ } catch (error) {
+ await queryRunner.rollbackTransaction();
+ throw error;
+ } finally {
+ await queryRunner.release();
+ }
+ }
+}
+
+// Repository method with transaction support
+@Injectable()
+export class UsersRepository {
+ constructor(
+ @InjectRepository(User) private repo: Repository<User>,
+ private dataSource: DataSource,
+ ) {}
+
+ async createWithProfile(
+ userData: CreateUserDto,
+ profileData: CreateProfileDto,
+ ): Promise<User> {
+ return this.dataSource.transaction(async (manager) => {
+ const user = await manager.save(User, userData);
+ await manager.save(Profile, { ...profileData, userId: user.id });
+ return user;
+ });
+ }
+}
+```
+
+Reference: [TypeORM Transactions](https://typeorm.io/transactions)
diff --git a/.agents/skills/nestjs-best-practices/rules/devops-graceful-shutdown.md b/.agents/skills/nestjs-best-practices/rules/devops-graceful-shutdown.md
new file mode 100644
index 00000000..b3b18f82
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/devops-graceful-shutdown.md
@@ -0,0 +1,222 @@
+---
+title: Implement Graceful Shutdown
+impact: MEDIUM-HIGH
+impactDescription: Proper shutdown handling ensures zero-downtime deployments
+tags: devops, graceful-shutdown, lifecycle, kubernetes
+---
+
+## Implement Graceful Shutdown
+
+Handle SIGTERM and SIGINT signals to gracefully shutdown your NestJS application. Stop accepting new requests, wait for in-flight requests to complete, close database connections, and clean up resources. This prevents data loss and connection errors during deployments.
+
+**Incorrect (ignoring shutdown signals):**
+
+```typescript
+// Ignore shutdown signals
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule);
+ await app.listen(3000);
+ // App crashes immediately on SIGTERM
+ // In-flight requests fail
+ // Database connections are abruptly closed
+}
+
+// Long-running tasks without cancellation
+@Injectable()
+export class ProcessingService {
+ async processLargeFile(file: File): Promise<void> {
+ // No way to interrupt this during shutdown
+ for (let i = 0; i < file.chunks.length; i++) {
+ await this.processChunk(file.chunks[i]);
+ // May run for minutes, blocking shutdown
+ }
+ }
+}
+```
+
+**Correct (enable shutdown hooks and handle cleanup):**
+
+```typescript
+// Enable shutdown hooks in main.ts
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule);
+
+ // Enable shutdown hooks
+ app.enableShutdownHooks();
+
+ // Optional: Add timeout for forced shutdown
+ const server = await app.listen(3000);
+ server.setTimeout(30000); // 30 second timeout
+
+ // Handle graceful shutdown
+ const signals = ['SIGTERM', 'SIGINT'];
+ signals.forEach((signal) => {
+ process.on(signal, async () => {
+ console.log(`Received ${signal}, starting graceful shutdown...`);
+
+ // Stop accepting new connections
+ server.close(async () => {
+ console.log('HTTP server closed');
+ await app.close();
+ process.exit(0);
+ });
+
+ // Force exit after timeout
+ setTimeout(() => {
+ console.error('Forced shutdown after timeout');
+ process.exit(1);
+ }, 30000);
+ });
+ });
+}
+
+// Lifecycle hooks for cleanup
+@Injectable()
+export class DatabaseService implements OnApplicationShutdown {
+ private readonly connections: Connection[] = [];
+
+ async onApplicationShutdown(signal?: string): Promise<void> {
+ console.log(`Database service shutting down on ${signal}`);
+
+ // Close all connections gracefully
+ await Promise.all(
+ this.connections.map((conn) => conn.close()),
+ );
+
+ console.log('All database connections closed');
+ }
+}
+
+// Queue processor with graceful shutdown
+@Injectable()
+export class QueueService implements OnApplicationShutdown, OnModuleDestroy {
+ private isShuttingDown = false;
+
+ onModuleDestroy(): void {
+ this.isShuttingDown = true;
+ }
+
+ async onApplicationShutdown(): Promise<void> {
+ // Wait for current jobs to complete
+ await this.queue.close();
+ }
+
+ async processJob(job: Job): Promise<void> {
+ if (this.isShuttingDown) {
+ throw new Error('Service is shutting down');
+ }
+ await this.doWork(job);
+ }
+}
+
+// WebSocket gateway cleanup
+@WebSocketGateway()
+export class EventsGateway implements OnApplicationShutdown {
+ @WebSocketServer()
+ server: Server;
+
+ async onApplicationShutdown(): Promise<void> {
+ // Notify all connected clients
+ this.server.emit('shutdown', { message: 'Server is shutting down' });
+
+ // Close all connections
+ this.server.disconnectSockets();
+ }
+}
+
+// Health check integration
+@Injectable()
+export class ShutdownService {
+ private isShuttingDown = false;
+
+ startShutdown(): void {
+ this.isShuttingDown = true;
+ }
+
+ isShutdown(): boolean {
+ return this.isShuttingDown;
+ }
+}
+
+@Controller('health')
+export class HealthController {
+ constructor(private shutdownService: ShutdownService) {}
+
+ @Get('ready')
+ @HealthCheck()
+ readiness(): Promise<HealthCheckResult> {
+ // Return 503 during shutdown - k8s stops sending traffic
+ if (this.shutdownService.isShutdown()) {
+ throw new ServiceUnavailableException('Shutting down');
+ }
+
+ return this.health.check([
+ () => this.db.pingCheck('database'),
+ ]);
+ }
+}
+
+// Integrate with shutdown
+@Injectable()
+export class AppShutdownService implements OnApplicationShutdown {
+ constructor(private shutdownService: ShutdownService) {}
+
+ async onApplicationShutdown(): Promise<void> {
+ // Mark as unhealthy first
+ this.shutdownService.startShutdown();
+
+ // Wait for k8s to update endpoints
+ await this.sleep(5000);
+
+ // Then proceed with cleanup
+ }
+}
+
+// Request tracking for in-flight requests
+@Injectable()
+export class RequestTracker implements NestMiddleware, OnApplicationShutdown {
+ private activeRequests = 0;
+ private isShuttingDown = false;
+ private shutdownPromise: Promise<void> | null = null;
+ private resolveShutdown: (() => void) | null = null;
+
+ use(req: Request, res: Response, next: NextFunction): void {
+ if (this.isShuttingDown) {
+ res.status(503).send('Service Unavailable');
+ return;
+ }
+
+ this.activeRequests++;
+
+ res.on('finish', () => {
+ this.activeRequests--;
+ if (this.isShuttingDown && this.activeRequests === 0 && this.resolveShutdown) {
+ this.resolveShutdown();
+ }
+ });
+
+ next();
+ }
+
+ async onApplicationShutdown(): Promise<void> {
+ this.isShuttingDown = true;
+
+ if (this.activeRequests > 0) {
+ console.log(`Waiting for ${this.activeRequests} requests to complete`);
+ this.shutdownPromise = new Promise((resolve) => {
+ this.resolveShutdown = resolve;
+ });
+
+ // Wait with timeout
+ await Promise.race([
+ this.shutdownPromise,
+ new Promise((resolve) => setTimeout(resolve, 30000)),
+ ]);
+ }
+
+ console.log('All requests completed');
+ }
+}
+```
+
+Reference: [NestJS Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events)
diff --git a/.agents/skills/nestjs-best-practices/rules/devops-use-config-module.md b/.agents/skills/nestjs-best-practices/rules/devops-use-config-module.md
new file mode 100644
index 00000000..a9483ded
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/devops-use-config-module.md
@@ -0,0 +1,167 @@
+---
+title: Use ConfigModule for Environment Configuration
+impact: LOW-MEDIUM
+impactDescription: Proper configuration prevents deployment failures
+tags: devops, configuration, environment, validation
+---
+
+## Use ConfigModule for Environment Configuration
+
+Use `@nestjs/config` for environment-based configuration. Validate configuration at startup to fail fast on misconfigurations. Use namespaced configuration for organization and type safety.
+
+**Incorrect (accessing process.env directly):**
+
+```typescript
+// Access process.env directly
+@Injectable()
+export class DatabaseService {
+ constructor() {
+ // No validation, can fail at runtime
+ this.connection = new Pool({
+ host: process.env.DB_HOST,
+ port: parseInt(process.env.DB_PORT), // NaN if missing
+ password: process.env.DB_PASSWORD, // undefined if missing
+ });
+ }
+}
+
+// Scattered env access
+@Injectable()
+export class EmailService {
+ sendEmail() {
+ // Different services access env differently
+ const apiKey = process.env.SENDGRID_API_KEY || 'default';
+ // Typos go unnoticed: process.env.SENDGRID_API_KY
+ }
+}
+```
+
+**Correct (use @nestjs/config with validation):**
+
+```typescript
+// Setup validated configuration
+import { ConfigModule, ConfigService, registerAs } from '@nestjs/config';
+import * as Joi from 'joi';
+
+// config/database.config.ts
+export const databaseConfig = registerAs('database', () => ({
+ host: process.env.DB_HOST,
+ port: parseInt(process.env.DB_PORT, 10),
+ username: process.env.DB_USERNAME,
+ password: process.env.DB_PASSWORD,
+ database: process.env.DB_NAME,
+}));
+
+// config/app.config.ts
+export const appConfig = registerAs('app', () => ({
+ port: parseInt(process.env.PORT, 10) || 3000,
+ environment: process.env.NODE_ENV || 'development',
+ apiPrefix: process.env.API_PREFIX || 'api',
+}));
+
+// config/validation.schema.ts
+export const validationSchema = Joi.object({
+ NODE_ENV: Joi.string()
+ .valid('development', 'production', 'test')
+ .default('development'),
+ PORT: Joi.number().default(3000),
+ DB_HOST: Joi.string().required(),
+ DB_PORT: Joi.number().default(5432),
+ DB_USERNAME: Joi.string().required(),
+ DB_PASSWORD: Joi.string().required(),
+ DB_NAME: Joi.string().required(),
+ JWT_SECRET: Joi.string().min(32).required(),
+ REDIS_URL: Joi.string().uri().required(),
+});
+
+// app.module.ts
+@Module({
+ imports: [
+ ConfigModule.forRoot({
+ isGlobal: true, // Available everywhere without importing
+ load: [databaseConfig, appConfig],
+ validationSchema,
+ validationOptions: {
+ abortEarly: true, // Stop on first error
+ allowUnknown: true, // Allow other env vars
+ },
+ }),
+ TypeOrmModule.forRootAsync({
+ inject: [ConfigService],
+ useFactory: (config: ConfigService) => ({
+ type: 'postgres',
+ host: config.get('database.host'),
+ port: config.get('database.port'),
+ username: config.get('database.username'),
+ password: config.get('database.password'),
+ database: config.get('database.database'),
+ autoLoadEntities: true,
+ }),
+ }),
+ ],
+})
+export class AppModule {}
+
+// Type-safe configuration access
+export interface AppConfig {
+ port: number;
+ environment: 'development' | 'production' | 'test';
+ apiPrefix: string;
+}
+
+export interface DatabaseConfig {
+ host: string;
+ port: number;
+ username: string;
+ password: string;
+ database: string;
+}
+
+// Type-safe access
+@Injectable()
+export class AppService {
+ constructor(private config: ConfigService) {}
+
+ getPort(): number {
+ // Type-safe with generic
+ return this.config.get<number>('app.port');
+ }
+
+ getDatabaseConfig(): DatabaseConfig {
+ return this.config.get<DatabaseConfig>('database');
+ }
+}
+
+// Inject namespaced config directly
+@Injectable()
+export class DatabaseService {
+ constructor(
+ @Inject(databaseConfig.KEY)
+ private dbConfig: ConfigType<typeof databaseConfig>,
+ ) {
+ // Full type inference!
+ const host = this.dbConfig.host; // string
+ const port = this.dbConfig.port; // number
+ }
+}
+
+// Environment files support
+ConfigModule.forRoot({
+ envFilePath: [
+ `.env.${process.env.NODE_ENV}.local`,
+ `.env.${process.env.NODE_ENV}`,
+ '.env.local',
+ '.env',
+ ],
+});
+
+// .env.development
+// DB_HOST=localhost
+// DB_PORT=5432
+
+// .env.production
+// DB_HOST=prod-db.example.com
+// DB_PORT=5432
+```
+
+Reference: [NestJS Configuration](https://docs.nestjs.com/techniques/configuration)
diff --git a/.agents/skills/nestjs-best-practices/rules/devops-use-logging.md b/.agents/skills/nestjs-best-practices/rules/devops-use-logging.md
new file mode 100644
index 00000000..5fb0162b
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/devops-use-logging.md
@@ -0,0 +1,232 @@
+---
+title: Use Structured Logging
+impact: MEDIUM-HIGH
+impactDescription: Structured logging enables effective debugging and monitoring
+tags: devops, logging, structured-logs, pino
+---
+
+## Use Structured Logging
+
+Use NestJS Logger with structured JSON output in production. Include contextual information (request ID, user ID, operation) to trace requests across services. Avoid console.log and implement proper log levels.
+
+**Incorrect (using console.log in production):**
+
+```typescript
+// Use console.log in production
+@Injectable()
+export class UsersService {
+ async createUser(dto: CreateUserDto): Promise<User> {
+ console.log('Creating user:', dto);
+ // Not structured, no levels, lost in production logs
+
+ try {
+ const user = await this.repo.save(dto);
+ console.log('User created:', user.id);
+ return user;
+ } catch (error) {
+ console.log('Error:', error); // Using log for errors
+ throw error;
+ }
+ }
+}
+
+// Log sensitive data
+console.log('Login attempt:', { email, password }); // SECURITY RISK!
+
+// Inconsistent log format
+logger.log('User ' + userId + ' created at ' + new Date());
+// Hard to parse, no structure
+```
+
+**Correct (use structured logging with context):**
+
+```typescript
+// Configure logger in main.ts
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule, {
+ logger:
+ process.env.NODE_ENV === 'production'
+ ? ['error', 'warn', 'log']
+ : ['error', 'warn', 'log', 'debug', 'verbose'],
+ });
+}
+
+// Use NestJS Logger with context
+@Injectable()
+export class UsersService {
+ private readonly logger = new Logger(UsersService.name);
+
+ async createUser(dto: CreateUserDto): Promise<User> {
+ this.logger.log('Creating user', { email: dto.email });
+
+ try {
+ const user = await this.repo.save(dto);
+ this.logger.log('User created', { userId: user.id });
+ return user;
+ } catch (error) {
+ this.logger.error('Failed to create user', error.stack, {
+ email: dto.email,
+ });
+ throw error;
+ }
+ }
+}
+
+// Custom logger for JSON output
+@Injectable()
+export class JsonLogger implements LoggerService {
+ log(message: string, context?: object): void {
+ console.log(
+ JSON.stringify({
+ level: 'info',
+ timestamp: new Date().toISOString(),
+ message,
+ ...context,
+ }),
+ );
+ }
+
+ error(message: string, trace?: string, context?: object): void {
+ console.error(
+ JSON.stringify({
+ level: 'error',
+ timestamp: new Date().toISOString(),
+ message,
+ trace,
+ ...context,
+ }),
+ );
+ }
+
+ warn(message: string, context?: object): void {
+ console.warn(
+ JSON.stringify({
+ level: 'warn',
+ timestamp: new Date().toISOString(),
+ message,
+ ...context,
+ }),
+ );
+ }
+
+ debug(message: string, context?: object): void {
+ console.debug(
+ JSON.stringify({
+ level: 'debug',
+ timestamp: new Date().toISOString(),
+ message,
+ ...context,
+ }),
+ );
+ }
+}
+
+// Request context logging with ClsModule
+import { ClsModule, ClsService } from 'nestjs-cls';
+
+@Module({
+ imports: [
+ ClsModule.forRoot({
+ global: true,
+ middleware: {
+ mount: true,
+ generateId: true,
+ },
+ }),
+ ],
+})
+export class AppModule {}
+
+// Middleware to set request context
+@Injectable()
+export class RequestContextMiddleware implements NestMiddleware {
+ constructor(private cls: ClsService) {}
+
+ use(req: Request, res: Response, next: NextFunction): void {
+ const requestId = req.headers['x-request-id'] || randomUUID();
+ this.cls.set('requestId', requestId);
+ this.cls.set('userId', req.user?.id);
+
+ res.setHeader('x-request-id', requestId);
+ next();
+ }
+}
+
+// Logger that includes request context
+@Injectable()
+export class ContextLogger {
+ constructor(private cls: ClsService) {}
+
+ log(message: string, data?: object): void {
+ console.log(
+ JSON.stringify({
+ level: 'info',
+ timestamp: new Date().toISOString(),
+ requestId: this.cls.get('requestId'),
+ userId: this.cls.get('userId'),
+ message,
+ ...data,
+ }),
+ );
+ }
+
+ error(message: string, error: Error, data?: object): void {
+ console.error(
+ JSON.stringify({
+ level: 'error',
+ timestamp: new Date().toISOString(),
+ requestId: this.cls.get('requestId'),
+ userId: this.cls.get('userId'),
+ message,
+ error: error.message,
+ stack: error.stack,
+ ...data,
+ }),
+ );
+ }
+}
+
+// Pino integration for high-performance logging
+import { LoggerModule } from 'nestjs-pino';
+
+@Module({
+ imports: [
+ LoggerModule.forRoot({
+ pinoHttp: {
+ level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
+ transport:
+ process.env.NODE_ENV !== 'production'
+ ? { target: 'pino-pretty' }
+ : undefined,
+ redact: ['req.headers.authorization', 'req.body.password'],
+ serializers: {
+ req: (req) => ({
+ method: req.method,
+ url: req.url,
+ query: req.query,
+ }),
+ res: (res) => ({
+ statusCode: res.statusCode,
+ }),
+ },
+ },
+ }),
+ ],
+})
+export class AppModule {}
+
+// Usage with Pino
+@Injectable()
+export class UsersService {
+ constructor(private logger: PinoLogger) {
+ this.logger.setContext(UsersService.name);
+ }
+
+ async findOne(id: string): Promise<User> {
+ this.logger.info({ userId: id }, 'Finding user');
+ // Pino uses first arg for data, second for message
+ }
+}
+```
+
+Reference: [NestJS Logger](https://docs.nestjs.com/techniques/logger)
diff --git a/.agents/skills/nestjs-best-practices/rules/di-avoid-service-locator.md b/.agents/skills/nestjs-best-practices/rules/di-avoid-service-locator.md
new file mode 100644
index 00000000..d4c04b47
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/di-avoid-service-locator.md
@@ -0,0 +1,104 @@
+---
+title: Avoid Service Locator Anti-Pattern
+impact: HIGH
+impactDescription: Hides dependencies and breaks testability
+tags: dependency-injection, anti-patterns, testing
+---
+
+## Avoid Service Locator Anti-Pattern
+
+Avoid using `ModuleRef.get()` or global containers to resolve dependencies at runtime. This hides dependencies, makes code harder to test, and breaks the benefits of dependency injection. Use constructor injection instead.
+
+**Incorrect (service locator anti-pattern):**
+
+```typescript
+// Use ModuleRef to get dependencies dynamically
+@Injectable()
+export class OrdersService {
+ constructor(private moduleRef: ModuleRef) {}
+
+ async createOrder(dto: CreateOrderDto): Promise<Order> {
+ // Dependencies are hidden - not visible in constructor
+ const usersService = this.moduleRef.get(UsersService);
+ const inventoryService = this.moduleRef.get(InventoryService);
+ const paymentService = this.moduleRef.get(PaymentService);
+
+ const user = await usersService.findOne(dto.userId);
+ // ... rest of logic
+ }
+}
+
+// Global singleton container
+class ServiceContainer {
+ private static instance: ServiceContainer;
+ private services = new Map<string, any>();
+
+ static getInstance(): ServiceContainer {
+ if (!this.instance) {
+ this.instance = new ServiceContainer();
+ }
+ return this.instance;
+ }
+
+ get<T>(key: string): T {
+ return this.services.get(key);
+ }
+}
+```
+
+**Correct (constructor injection with explicit dependencies):**
+
+```typescript
+// Use constructor injection - dependencies are explicit
+@Injectable()
+export class OrdersService {
+ constructor(
+ private usersService: UsersService,
+ private inventoryService: InventoryService,
+ private paymentService: PaymentService,
+ ) {}
+
+ async createOrder(dto: CreateOrderDto): Promise<Order> {
+ const user = await this.usersService.findOne(dto.userId);
+ const inventory = await this.inventoryService.check(dto.items);
+ // Dependencies are clear and testable
+ }
+}
+
+// Easy to test with mocks
+describe('OrdersService', () => {
+ let service: OrdersService;
+
+ beforeEach(async () => {
+ const module = await Test.createTestingModule({
+ providers: [
+ OrdersService,
+ { provide: UsersService, useValue: mockUsersService },
+ { provide: InventoryService, useValue: mockInventoryService },
+ { provide: PaymentService, useValue: mockPaymentService },
+ ],
+ }).compile();
+
+ service = module.get(OrdersService);
+ });
+});
+
+// VALID: Factory pattern for dynamic instantiation
+@Injectable()
+export class HandlerFactory {
+ constructor(private moduleRef: ModuleRef) {}
+
+ getHandler(type: string): Handler {
+ switch (type) {
+ case 'email':
+ return this.moduleRef.get(EmailHandler);
+ case 'sms':
+ return this.moduleRef.get(SmsHandler);
+ default:
+ return this.moduleRef.get(DefaultHandler);
+ }
+ }
+}
+```
+
+Reference: [NestJS Module Reference](https://docs.nestjs.com/fundamentals/module-ref)
diff --git a/.agents/skills/nestjs-best-practices/rules/di-interface-segregation.md b/.agents/skills/nestjs-best-practices/rules/di-interface-segregation.md
new file mode 100644
index 00000000..8c96cd81
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/di-interface-segregation.md
@@ -0,0 +1,165 @@
+---
+title: Apply Interface Segregation Principle
+impact: HIGH
+impactDescription: Reduces coupling and improves testability by 30-50%
+tags: dependency-injection, interfaces, solid, isp
+---
+
+## Apply Interface Segregation Principle
+
+Clients should not be forced to depend on interfaces they don't use. In NestJS, this means keeping interfaces small and focused on specific capabilities rather than creating "fat" interfaces that bundle unrelated methods. When a service only needs to send emails, it shouldn't depend on an interface that also includes SMS, push notifications, and logging. Split large interfaces into role-based ones.
+
+**Incorrect (fat interface forcing unused dependencies):**
+
+```typescript
+// Fat interface - forces all consumers to depend on everything
+interface NotificationService {
+ sendEmail(to: string, subject: string, body: string): Promise<void>;
+ sendSms(phone: string, message: string): Promise<void>;
+ sendPush(userId: string, notification: PushPayload): Promise<void>;
+ sendSlack(channel: string, message: string): Promise<void>;
+ logNotification(type: string, payload: any): Promise<void>;
+ getDeliveryStatus(id: string): Promise<DeliveryStatus>;
+ retryFailed(id: string): Promise<void>;
+ scheduleNotification(dto: ScheduleDto): Promise<string>;
+}
+
+// Consumer only needs email, but must mock everything for tests
+@Injectable()
+export class OrdersService {
+ constructor(
+ private notifications: NotificationService, // Depends on 8 methods, uses 1
+ ) {}
+
+ async confirmOrder(order: Order): Promise<void> {
+ await this.notifications.sendEmail(
+ order.customer.email,
+ 'Order Confirmed',
+ `Your order ${order.id} has been confirmed.`,
+ );
+ }
+}
+
+// Testing is painful - must mock unused methods
+const mockNotificationService = {
+ sendEmail: jest.fn(),
+ sendSms: jest.fn(), // Never used, but required
+ sendPush: jest.fn(), // Never used, but required
+ sendSlack: jest.fn(), // Never used, but required
+ logNotification: jest.fn(), // Never used, but required
+ getDeliveryStatus: jest.fn(), // Never used, but required
+ retryFailed: jest.fn(), // Never used, but required
+ scheduleNotification: jest.fn(), // Never used, but required
+};
+```
+
+**Correct (segregated interfaces by capability):**
+
+```typescript
+// Segregated interfaces - each focused on one capability
+interface EmailSender {
+ sendEmail(to: string, subject: string, body: string): Promise<void>;
+}
+
+interface SmsSender {
+ sendSms(phone: string, message: string): Promise<void>;
+}
+
+interface PushSender {
+ sendPush(userId: string, notification: PushPayload): Promise<void>;
+}
+
+interface NotificationLogger {
+ logNotification(type: string, payload: any): Promise<void>;
+}
+
+interface NotificationScheduler {
+ scheduleNotification(dto: ScheduleDto): Promise<string>;
+}
+
+// Implementation can implement multiple interfaces
+@Injectable()
+export class NotificationService implements EmailSender, SmsSender, PushSender {
+ async sendEmail(to: string, subject: string, body: string): Promise<void> {
+ // Email implementation
+ }
+
+ async sendSms(phone: string, message: string): Promise<void> {
+ // SMS implementation
+ }
+
+ async sendPush(userId: string, notification: PushPayload): Promise<void> {
+ // Push implementation
+ }
+}
+
+// Or separate implementations
+@Injectable()
+export class SendGridEmailService implements EmailSender {
+ async sendEmail(to: string, subject: string, body: string): Promise<void> {
+ // SendGrid-specific implementation
+ }
+}
+
+// Consumer depends only on what it needs
+@Injectable()
+export class OrdersService {
+ constructor(
+ @Inject(EMAIL_SENDER) private emailSender: EmailSender, // Minimal dependency
+ ) {}
+
+ async confirmOrder(order: Order): Promise<void> {
+ await this.emailSender.sendEmail(
+ order.customer.email,
+ 'Order Confirmed',
+ `Your order ${order.id} has been confirmed.`,
+ );
+ }
+}
+
+// Testing is simple - only mock what's used
+const mockEmailSender: EmailSender = {
+ sendEmail: jest.fn(),
+};
+
+// Module registration with tokens
+export const EMAIL_SENDER = Symbol('EMAIL_SENDER');
+export const SMS_SENDER = Symbol('SMS_SENDER');
+
+@Module({
+ providers: [
+ { provide: EMAIL_SENDER, useClass: SendGridEmailService },
+ { provide: SMS_SENDER, useClass: TwilioSmsService },
+ ],
+ exports: [EMAIL_SENDER, SMS_SENDER],
+})
+export class NotificationModule {}
+```
+
+**Combining interfaces when needed:**
+
+```typescript
+// Sometimes a consumer legitimately needs multiple capabilities
+interface EmailAndSmsSender extends EmailSender, SmsSender {}
+
+// Or use intersection types
+type MultiChannelSender = EmailSender & SmsSender & PushSender;
+
+// Consumer that genuinely needs multiple channels
+@Injectable()
+export class AlertService {
+ constructor(
+ @Inject(MULTI_CHANNEL_SENDER)
+ private sender: EmailSender & SmsSender,
+ ) {}
+
+ async sendCriticalAlert(user: User, message: string): Promise<void> {
+ await Promise.all([
+ this.sender.sendEmail(user.email, 'Critical Alert', message),
+ this.sender.sendSms(user.phone, message),
+ ]);
+ }
+}
+```
+
+Reference: [Interface Segregation Principle](https://en.wikipedia.org/wiki/Interface_segregation_principle)
diff --git a/.agents/skills/nestjs-best-practices/rules/di-liskov-substitution.md b/.agents/skills/nestjs-best-practices/rules/di-liskov-substitution.md
new file mode 100644
index 00000000..d6701178
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/di-liskov-substitution.md
@@ -0,0 +1,221 @@
+---
+title: Honor Liskov Substitution Principle
+impact: HIGH
+impactDescription: Ensures implementations are truly interchangeable without breaking callers
+tags: dependency-injection, inheritance, solid, lsp
+---
+
+## Honor Liskov Substitution Principle
+
+Subtypes must be substitutable for their base types without altering program correctness. In NestJS with dependency injection, this means any implementation of an interface or abstract class must honor the contract completely. A mock payment service used in tests must behave like a real payment service (return similar shapes, handle errors the same way). Violating LSP causes subtle bugs when swapping implementations.
+
+**Incorrect (implementation violates the contract):**
+
+```typescript
+// Base interface with clear contract
+interface PaymentGateway {
+ /**
+ * Charges the specified amount.
+ * @returns PaymentResult on success
+ * @throws PaymentFailedException on payment failure
+ */
+ charge(amount: number, currency: string): Promise<PaymentResult>;
+}
+
+// Production implementation - follows the contract
+@Injectable()
+export class StripeService implements PaymentGateway {
+ async charge(amount: number, currency: string): Promise<PaymentResult> {
+ const response = await this.stripe.charges.create({ amount, currency });
+ return { success: true, transactionId: response.id, amount };
+ }
+}
+
+// Mock that violates LSP - different behavior!
+@Injectable()
+export class MockPaymentService implements PaymentGateway {
+ async charge(amount: number, currency: string): Promise<PaymentResult> {
+ // VIOLATION 1: Throws for valid input (contract says return PaymentResult)
+ if (amount > 1000) {
+ throw new Error('Mock does not support large amounts');
+ }
+
+ // VIOLATION 2: Returns null instead of PaymentResult
+ if (currency !== 'USD') {
+ return null as any; // Real service would convert or reject properly
+ }
+
+ // VIOLATION 3: Missing required field
+ return { success: true } as PaymentResult; // Missing transactionId!
+ }
+}
+
+// Consumer trusts the contract
+@Injectable()
+export class OrdersService {
+ constructor(@Inject(PAYMENT_GATEWAY) private payment: PaymentGateway) {}
+
+ async checkout(order: Order): Promise<void> {
+ const result = await this.payment.charge(order.total, order.currency);
+ // These fail with MockPaymentService:
+ await this.saveTransaction(result.transactionId); // undefined!
+ await this.sendReceipt(result); // might be null!
+ }
+}
+```
+
+**Correct (implementations honor the contract):**
+
+```typescript
+// Well-defined interface with documented behavior
+interface PaymentGateway {
+ /**
+ * Charges the specified amount.
+ * @param amount - Amount in smallest currency unit (cents)
+ * @param currency - ISO 4217 currency code
+ * @returns PaymentResult with transactionId, success status, and amount
+ * @throws PaymentFailedException if charge is declined
+ * @throws InvalidCurrencyException if currency is not supported
+ */
+ charge(amount: number, currency: string): Promise<PaymentResult>;
+
+ /**
+ * Refunds a previous charge.
+ * @throws TransactionNotFoundException if transactionId is invalid
+ */
+ refund(transactionId: string, amount?: number): Promise<RefundResult>;
+}
+
+// Production implementation
+@Injectable()
+export class StripeService implements PaymentGateway {
+ async charge(amount: number, currency: string): Promise<PaymentResult> {
+ try {
+ const response = await this.stripe.charges.create({ amount, currency });
+ return {
+ success: true,
+ transactionId: response.id,
+ amount: response.amount,
+ };
+ } catch (error) {
+ if (error.type === 'card_error') {
+ throw new PaymentFailedException(error.message);
+ }
+ throw error;
+ }
+ }
+
+ async refund(transactionId: string, amount?: number): Promise<RefundResult> {
+ // Implementation...
+ }
+}
+
+// Mock that honors LSP - same contract, same behavior shape
+@Injectable()
+export class MockPaymentService implements PaymentGateway {
+ private transactions = new Map<string, PaymentResult>();
+
+ async charge(amount: number, currency: string): Promise<PaymentResult> {
+ // Honor the contract: validate currency like real service would
+ if (!['USD', 'EUR', 'GBP'].includes(currency)) {
+ throw new InvalidCurrencyException(`Unsupported currency: ${currency}`);
+ }
+
+ // Simulate decline for specific test scenarios
+ if (amount === 99999) {
+ throw new PaymentFailedException('Card declined (test scenario)');
+ }
+
+ // Return same shape as production
+ const result: PaymentResult = {
+ success: true,
+ transactionId: `mock_${Date.now()}_${Math.random().toString(36)}`,
+ amount,
+ };
+
+ this.transactions.set(result.transactionId, result);
+ return result;
+ }
+
+ async refund(transactionId: string, amount?: number): Promise<RefundResult> {
+ // Honor the contract: throw if transaction not found
+ if (!this.transactions.has(transactionId)) {
+ throw new TransactionNotFoundException(transactionId);
+ }
+
+ return {
+ success: true,
+ refundId: `refund_${transactionId}`,
+ amount: amount ?? this.transactions.get(transactionId)!.amount,
+ };
+ }
+}
+
+// Consumer can swap implementations safely
+@Injectable()
+export class OrdersService {
+ constructor(@Inject(PAYMENT_GATEWAY) private payment: PaymentGateway) {}
+
+ async checkout(order: Order): Promise<Order> {
+ try {
+ const result = await this.payment.charge(order.total, order.currency);
+ // Works with both StripeService and MockPaymentService
+ order.transactionId = result.transactionId;
+ order.status = 'paid';
+ return order;
+ } catch (error) {
+ if (error instanceof PaymentFailedException) {
+ order.status = 'payment_failed';
+ return order;
+ }
+ throw error;
+ }
+ }
+}
+```
+
+**Testing LSP compliance:**
+
+```typescript
+// Shared test suite that any implementation must pass
+function testPaymentGatewayContract(
+ createGateway: () => PaymentGateway,
+) {
+ describe('PaymentGateway contract', () => {
+ let gateway: PaymentGateway;
+
+ beforeEach(() => {
+ gateway = createGateway();
+ });
+
+ it('returns PaymentResult with all required fields', async () => {
+ const result = await gateway.charge(1000, 'USD');
+ expect(result).toHaveProperty('success');
+ expect(result).toHaveProperty('transactionId');
+ expect(result).toHaveProperty('amount');
+ expect(typeof result.transactionId).toBe('string');
+ });
+
+ it('throws InvalidCurrencyException for unsupported currency', async () => {
+ await expect(gateway.charge(1000, 'INVALID'))
+ .rejects.toThrow(InvalidCurrencyException);
+ });
+
+ it('throws TransactionNotFoundException for invalid refund', async () => {
+ await expect(gateway.refund('nonexistent'))
+ .rejects.toThrow(TransactionNotFoundException);
+ });
+ });
+}
+
+// Run against all implementations
+describe('StripeService', () => {
+ testPaymentGatewayContract(() => new StripeService(mockStripeClient));
+});
+
+describe('MockPaymentService', () => {
+ testPaymentGatewayContract(() => new MockPaymentService());
+});
+```
+
+Reference: [Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)
diff --git a/.agents/skills/nestjs-best-practices/rules/di-prefer-constructor-injection.md b/.agents/skills/nestjs-best-practices/rules/di-prefer-constructor-injection.md
new file mode 100644
index 00000000..c4a3274c
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/di-prefer-constructor-injection.md
@@ -0,0 +1,86 @@
+---
+title: Prefer Constructor Injection
+impact: CRITICAL
+impactDescription: Required for proper DI and testing
+tags: dependency-injection, constructor, testing
+---
+
+## Prefer Constructor Injection
+
+Always use constructor injection over property injection. Constructor injection makes dependencies explicit, enables TypeScript type checking, ensures dependencies are available when the class is instantiated, and improves testability. This is required for proper DI, testing, and TypeScript support.
+
+**Incorrect (property injection with hidden dependencies):**
+
+```typescript
+// Property injection - avoid unless necessary
+@Injectable()
+export class UsersService {
+ @Inject()
+ private userRepo: UserRepository; // Hidden dependency
+
+ @Inject('CONFIG')
+ private config: ConfigType; // Also hidden
+
+ async findAll() {
+ return this.userRepo.find();
+ }
+}
+
+// Problems:
+// 1. Dependencies not visible in constructor
+// 2. Service can be instantiated without dependencies in tests
+// 3. TypeScript can't enforce dependency types at instantiation
+```
+
+**Correct (constructor injection with explicit dependencies):**
+
+```typescript
+// Constructor injection - explicit and testable
+@Injectable()
+export class UsersService {
+ constructor(
+ private readonly userRepo: UserRepository,
+ @Inject('CONFIG') private readonly config: ConfigType,
+ ) {}
+
+ async findAll(): Promise<User[]> {
+ return this.userRepo.find();
+ }
+}
+
+// Testing is straightforward
+describe('UsersService', () => {
+ let service: UsersService;
+ let mockRepo: jest.Mocked<UserRepository>;
+
+ beforeEach(() => {
+ mockRepo = {
+ find: jest.fn(),
+ save: jest.fn(),
+ } as any;
+
+ service = new UsersService(mockRepo, { dbUrl: 'test' });
+ });
+
+ it('should find all users', async () => {
+ mockRepo.find.mockResolvedValue([{ id: '1', name: 'Test' }]);
+ const result = await service.findAll();
+ expect(result).toHaveLength(1);
+ });
+});
+
+// Only use property injection for optional dependencies
+@Injectable()
+export class LoggingService {
+ @Optional()
+ @Inject('ANALYTICS')
+ private analytics?: AnalyticsService;
+
+ log(message: string) {
+ console.log(message);
+ this.analytics?.track('log', message); // Optional enhancement
+ }
+}
+```
+
+Reference: [NestJS Providers](https://docs.nestjs.com/providers)
diff --git a/.agents/skills/nestjs-best-practices/rules/di-scope-awareness.md b/.agents/skills/nestjs-best-practices/rules/di-scope-awareness.md
new file mode 100644
index 00000000..a6c77efb
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/di-scope-awareness.md
@@ -0,0 +1,94 @@
+---
+title: Understand Provider Scopes
+impact: CRITICAL
+impactDescription: Prevents data leaks and performance issues
+tags: dependency-injection, scopes, request-context
+---
+
+## Understand Provider Scopes
+
+NestJS has three provider scopes: DEFAULT (singleton), REQUEST (per-request instance), and TRANSIENT (new instance for each injection). Most providers should be singletons. Request-scoped providers have performance implications as they bubble up through the dependency tree. Understanding scopes prevents memory leaks and incorrect data sharing.
+
+**Incorrect (wrong scope usage):**
+
+```typescript
+// Request-scoped when not needed (performance hit)
+@Injectable({ scope: Scope.REQUEST })
+export class UsersService {
+ // This creates a new instance for EVERY request
+ // All dependencies also become request-scoped
+ async findAll() {
+ return this.userRepo.find();
+ }
+}
+
+// Singleton with mutable request state
+@Injectable() // Default: singleton
+export class RequestContextService {
+ private userId: string; // DANGER: Shared across all requests!
+
+ setUser(userId: string) {
+ this.userId = userId; // Overwrites for all concurrent requests
+ }
+
+ getUser() {
+ return this.userId; // Returns wrong user!
+ }
+}
+```
+
+**Correct (appropriate scope for each use case):**
+
+```typescript
+// Singleton for stateless services (default, most common)
+@Injectable()
+export class UsersService {
+ constructor(private readonly userRepo: UserRepository) {}
+
+ async findById(id: string): Promise<User> {
+ return this.userRepo.findOne({ where: { id } });
+ }
+}
+
+// Request-scoped ONLY when you need request context
+@Injectable({ scope: Scope.REQUEST })
+export class RequestContextService {
+ private userId: string;
+
+ setUser(userId: string) {
+ this.userId = userId;
+ }
+
+ getUser(): string {
+ return this.userId;
+ }
+}
+
+// Better: Use NestJS built-in request context
+import { REQUEST } from '@nestjs/core';
+import { Request } from 'express';
+
+@Injectable({ scope: Scope.REQUEST })
+export class AuditService {
+ constructor(@Inject(REQUEST) private request: Request) {}
+
+ log(action: string) {
+ console.log(`User ${this.request.user?.id} performed ${action}`);
+ }
+}
+
+// Best: Use ClsModule for async context (no scope bubble-up)
+import { ClsService } from 'nestjs-cls';
+
+@Injectable() // Stays singleton!
+export class AuditService {
+ constructor(private cls: ClsService) {}
+
+ log(action: string) {
+ const userId = this.cls.get('userId');
+ console.log(`User ${userId} performed ${action}`);
+ }
+}
+```
+
+Reference: [NestJS Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
diff --git a/.agents/skills/nestjs-best-practices/rules/di-use-interfaces-tokens.md b/.agents/skills/nestjs-best-practices/rules/di-use-interfaces-tokens.md
new file mode 100644
index 00000000..f5376a17
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/di-use-interfaces-tokens.md
@@ -0,0 +1,101 @@
+---
+title: Use Injection Tokens for Interfaces
+impact: HIGH
+impactDescription: Enables interface-based DI at runtime
+tags: dependency-injection, tokens, interfaces
+---
+
+## Use Injection Tokens for Interfaces
+
+TypeScript interfaces are erased at compile time and can't be used as injection tokens. Use string tokens, symbols, or abstract classes when you want to inject implementations of interfaces. This enables swapping implementations for testing or different environments.
+
+**Incorrect (interface can't be used as token):**
+
+```typescript
+// Interface can't be used as injection token
+interface PaymentGateway {
+ charge(amount: number): Promise<PaymentResult>;
+}
+
+@Injectable()
+export class StripeService implements PaymentGateway {
+ charge(amount: number) { /* ... */ }
+}
+
+@Injectable()
+export class OrdersService {
+ // This WON'T work - PaymentGateway doesn't exist at runtime
+ constructor(private payment: PaymentGateway) {}
+}
+```
+
+**Correct (symbol tokens or abstract classes):**
+
+```typescript
+// Option 1: String/Symbol tokens (most flexible)
+export const PAYMENT_GATEWAY = Symbol('PAYMENT_GATEWAY');
+
+export interface PaymentGateway {
+ charge(amount: number): Promise<PaymentResult>;
+}
+
+@Injectable()
+export class StripeService implements PaymentGateway {
+ async charge(amount: number): Promise<PaymentResult> {
+ // Stripe implementation
+ }
+}
+
+@Injectable()
+export class MockPaymentService implements PaymentGateway {
+ async charge(amount: number): Promise<PaymentResult> {
+ return { success: true, id: 'mock-id' };
+ }
+}
+
+// Module registration
+@Module({
+ providers: [
+ {
+ provide: PAYMENT_GATEWAY,
+ useClass: process.env.NODE_ENV === 'test'
+ ? MockPaymentService
+ : StripeService,
+ },
+ ],
+ exports: [PAYMENT_GATEWAY],
+})
+export class PaymentModule {}
+
+// Injection
+@Injectable()
+export class OrdersService {
+ constructor(
+ @Inject(PAYMENT_GATEWAY) private payment: PaymentGateway,
+ ) {}
+
+ async createOrder(dto: CreateOrderDto) {
+ await this.payment.charge(dto.amount);
+ }
+}
+
+// Option 2: Abstract class (carries runtime type info)
+export abstract class PaymentGateway {
+ abstract charge(amount: number): Promise<PaymentResult>;
+}
+
+@Injectable()
+export class StripeService extends PaymentGateway {
+ async charge(amount: number): Promise<PaymentResult> {
+ // Implementation
+ }
+}
+
+// No @Inject needed with abstract class
+@Injectable()
+export class OrdersService {
+ constructor(private payment: PaymentGateway) {}
+}
+```
+
+Reference: [NestJS Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers)
diff --git a/.agents/skills/nestjs-best-practices/rules/error-handle-async-errors.md b/.agents/skills/nestjs-best-practices/rules/error-handle-async-errors.md
new file mode 100644
index 00000000..36c3f6af
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/error-handle-async-errors.md
@@ -0,0 +1,125 @@
+---
+title: Handle Async Errors Properly
+impact: HIGH
+impactDescription: Prevents process crashes from unhandled rejections
+tags: error-handling, async, promises
+---
+
+## Handle Async Errors Properly
+
+NestJS automatically catches errors from async route handlers, but errors from background tasks, event handlers, and manually created promises can crash your application. Always handle async errors explicitly and use global handlers as a safety net.
+
+**Incorrect (fire-and-forget without error handling):**
+
+```typescript
+// Fire-and-forget without error handling
+@Injectable()
+export class UsersService {
+ async createUser(dto: CreateUserDto): Promise<User> {
+ const user = await this.repo.save(dto);
+
+ // Fire and forget - if this fails, error is unhandled!
+ this.emailService.sendWelcome(user.email);
+
+ return user;
+ }
+}
+
+// Unhandled promise in event handler
+@Injectable()
+export class OrdersService {
+ @OnEvent('order.created')
+ handleOrderCreated(event: OrderCreatedEvent) {
+ // This returns a promise but it's not awaited!
+ this.processOrder(event);
+ // Errors will crash the process
+ }
+
+ private async processOrder(event: OrderCreatedEvent): Promise<void> {
+ await this.inventoryService.reserve(event.items);
+ await this.notificationService.send(event.userId);
+ }
+}
+
+// Missing try-catch in scheduled tasks
+@Cron('0 0 * * *')
+async dailyCleanup(): Promise<void> {
+ await this.cleanupService.run();
+ // If this throws, no error handling
+}
+```
+
+**Correct (explicit async error handling):**
+
+```typescript
+// Handle fire-and-forget with explicit catch
+@Injectable()
+export class UsersService {
+ private readonly logger = new Logger(UsersService.name);
+
+ async createUser(dto: CreateUserDto): Promise<User> {
+ const user = await this.repo.save(dto);
+
+ // Explicitly catch and log errors
+ this.emailService.sendWelcome(user.email).catch((error) => {
+ this.logger.error('Failed to send welcome email', error.stack);
+ // Optionally queue for retry
+ });
+
+ return user;
+ }
+}
+
+// Properly handle async event handlers
+@Injectable()
+export class OrdersService {
+ private readonly logger = new Logger(OrdersService.name);
+
+ @OnEvent('order.created')
+ async handleOrderCreated(event: OrderCreatedEvent): Promise<void> {
+ try {
+ await this.processOrder(event);
+ } catch (error) {
+ this.logger.error('Failed to process order', { event, error });
+ // Don't rethrow - would crash the process
+ await this.deadLetterQueue.add('order.created', event);
+ }
+ }
+}
+
+// Safe scheduled tasks
+@Injectable()
+export class CleanupService {
+ private readonly logger = new Logger(CleanupService.name);
+
+ @Cron('0 0 * * *')
+ async dailyCleanup(): Promise<void> {
+ try {
+ await this.cleanupService.run();
+ this.logger.log('Daily cleanup completed');
+ } catch (error) {
+ this.logger.error('Daily cleanup failed', error.stack);
+ // Alert or retry logic
+ }
+ }
+}
+
+// Global unhandled rejection handler in main.ts
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule);
+ const logger = new Logger('Bootstrap');
+
+ process.on('unhandledRejection', (reason, promise) => {
+ logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
+ });
+
+ process.on('uncaughtException', (error) => {
+ logger.error('Uncaught Exception:', error);
+ process.exit(1);
+ });
+
+ await app.listen(3000);
+}
+```
+
+Reference: [Node.js Unhandled Rejections](https://nodejs.org/api/process.html#event-unhandledrejection)
diff --git a/.agents/skills/nestjs-best-practices/rules/error-throw-http-exceptions.md b/.agents/skills/nestjs-best-practices/rules/error-throw-http-exceptions.md
new file mode 100644
index 00000000..6aad9fa3
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/error-throw-http-exceptions.md
@@ -0,0 +1,114 @@
+---
+title: Throw HTTP Exceptions from Services
+impact: HIGH
+impactDescription: Keeps controllers thin and simplifies error handling
+tags: error-handling, exceptions, services
+---
+
+## Throw HTTP Exceptions from Services
+
+It's acceptable (and often preferable) to throw `HttpException` subclasses from services in HTTP applications. This keeps controllers thin and allows services to communicate appropriate error states. For truly layer-agnostic services, use domain exceptions that map to HTTP status codes.
+
+**Incorrect (return error objects instead of throwing):**
+
+```typescript
+// Return error objects instead of throwing
+@Injectable()
+export class UsersService {
+ async findById(id: string): Promise<{ user?: User; error?: string }> {
+ const user = await this.repo.findOne({ where: { id } });
+ if (!user) {
+ return { error: 'User not found' }; // Controller must check this
+ }
+ return { user };
+ }
+}
+
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(@Param('id') id: string) {
+ const result = await this.usersService.findById(id);
+ if (result.error) {
+ throw new NotFoundException(result.error);
+ }
+ return result.user;
+ }
+}
+```
+
+**Correct (throw exceptions directly from service):**
+
+```typescript
+// Throw exceptions directly from service
+@Injectable()
+export class UsersService {
+ constructor(private readonly repo: UserRepository) {}
+
+ async findById(id: string): Promise<User> {
+ const user = await this.repo.findOne({ where: { id } });
+ if (!user) {
+ throw new NotFoundException(`User #${id} not found`);
+ }
+ return user;
+ }
+
+ async create(dto: CreateUserDto): Promise<User> {
+ const existing = await this.repo.findOne({
+ where: { email: dto.email },
+ });
+ if (existing) {
+ throw new ConflictException('Email already registered');
+ }
+ return this.repo.save(dto);
+ }
+
+ async update(id: string, dto: UpdateUserDto): Promise<User> {
+ const user = await this.findById(id); // Throws if not found
+ Object.assign(user, dto);
+ return this.repo.save(user);
+ }
+}
+
+// Controller stays thin
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ findOne(@Param('id') id: string): Promise<User> {
+ return this.usersService.findById(id);
+ }
+
+ @Post()
+ create(@Body() dto: CreateUserDto): Promise<User> {
+ return this.usersService.create(dto);
+ }
+}
+
+// For layer-agnostic services, use domain exceptions
+export class EntityNotFoundException extends Error {
+ constructor(
+ public readonly entity: string,
+ public readonly id: string,
+ ) {
+ super(`${entity} with ID "${id}" not found`);
+ }
+}
+
+// Map to HTTP in exception filter
+@Catch(EntityNotFoundException)
+export class EntityNotFoundFilter implements ExceptionFilter {
+ catch(exception: EntityNotFoundException, host: ArgumentsHost) {
+ const ctx = host.switchToHttp();
+ const response = ctx.getResponse<Response>();
+
+ response.status(404).json({
+ statusCode: 404,
+ message: exception.message,
+ entity: exception.entity,
+ id: exception.id,
+ });
+ }
+}
+```
+
+Reference: [NestJS Exception Filters](https://docs.nestjs.com/exception-filters)
diff --git a/.agents/skills/nestjs-best-practices/rules/error-use-exception-filters.md b/.agents/skills/nestjs-best-practices/rules/error-use-exception-filters.md
new file mode 100644
index 00000000..635823a8
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/error-use-exception-filters.md
@@ -0,0 +1,140 @@
+---
+title: Use Exception Filters for Error Handling
+impact: HIGH
+impactDescription: Consistent, centralized error handling
+tags: error-handling, exception-filters, consistency
+---
+
+## Use Exception Filters for Error Handling
+
+Never catch exceptions and manually format error responses in controllers. Use NestJS exception filters to handle errors consistently across your application. Create custom exception filters for specific error types and a global filter for unhandled exceptions.
+
+**Incorrect (manual error handling in controllers):**
+
+```typescript
+// Manual error handling in controllers
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(@Param('id') id: string, @Res() res: Response) {
+ try {
+ const user = await this.usersService.findById(id);
+ if (!user) {
+ return res.status(404).json({
+ statusCode: 404,
+ message: 'User not found',
+ });
+ }
+ return res.json(user);
+ } catch (error) {
+ console.error(error);
+ return res.status(500).json({
+ statusCode: 500,
+ message: 'Internal server error',
+ });
+ }
+ }
+}
+```
+
+**Correct (exception filters with consistent handling):**
+
+```typescript
+// Use built-in and custom exceptions
+@Controller('users')
+export class UsersController {
+ @Get(':id')
+ async findOne(@Param('id') id: string): Promise<User> {
+ const user = await this.usersService.findById(id);
+ if (!user) {
+ throw new NotFoundException(`User #${id} not found`);
+ }
+ return user;
+ }
+}
+
+// Custom domain exception
+export class UserNotFoundException extends NotFoundException {
+ constructor(userId: string) {
+ super({
+ statusCode: 404,
+ error: 'Not Found',
+ message: `User with ID "${userId}" not found`,
+ code: 'USER_NOT_FOUND',
+ });
+ }
+}
+
+// Custom exception filter for domain errors
+@Catch(DomainException)
+export class DomainExceptionFilter implements ExceptionFilter {
+ catch(exception: DomainException, host: ArgumentsHost) {
+ const ctx = host.switchToHttp();
+ const response = ctx.getResponse<Response>();
+ const request = ctx.getRequest<Request>();
+
+ const status = exception.getStatus?.() || 400;
+
+ response.status(status).json({
+ statusCode: status,
+ code: exception.code,
+ message: exception.message,
+ timestamp: new Date().toISOString(),
+ path: request.url,
+ });
+ }
+}
+
+// Global exception filter for unhandled errors
+@Catch()
+export class AllExceptionsFilter implements ExceptionFilter {
+ constructor(private readonly logger: Logger) {}
+
+ catch(exception: unknown, host: ArgumentsHost) {
+ const ctx = host.switchToHttp();
+ const response = ctx.getResponse<Response>();
+ const request = ctx.getRequest<Request>();
+
+ const status =
+ exception instanceof HttpException
+ ? exception.getStatus()
+ : HttpStatus.INTERNAL_SERVER_ERROR;
+
+ const message =
+ exception instanceof HttpException
+ ? exception.message
+ : 'Internal server error';
+
+ this.logger.error(
+ `${request.method} ${request.url}`,
+ exception instanceof Error ? exception.stack : exception,
+ );
+
+ response.status(status).json({
+ statusCode: status,
+ message,
+ timestamp: new Date().toISOString(),
+ path: request.url,
+ });
+ }
+}
+
+// Register globally in main.ts
+app.useGlobalFilters(
+ new AllExceptionsFilter(app.get(Logger)),
+ new DomainExceptionFilter(),
+);
+
+// Or via module
+@Module({
+ providers: [
+ {
+ provide: APP_FILTER,
+ useClass: AllExceptionsFilter,
+ },
+ ],
+})
+export class AppModule {}
+```
+
+Reference: [NestJS Exception Filters](https://docs.nestjs.com/exception-filters)
diff --git a/.agents/skills/nestjs-best-practices/rules/micro-use-health-checks.md b/.agents/skills/nestjs-best-practices/rules/micro-use-health-checks.md
new file mode 100644
index 00000000..0b10d926
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/micro-use-health-checks.md
@@ -0,0 +1,226 @@
+---
+title: Implement Health Checks for Microservices
+impact: MEDIUM-HIGH
+impactDescription: Health checks enable orchestrators to manage service lifecycle
+tags: microservices, health-checks, terminus, kubernetes
+---
+
+## Implement Health Checks for Microservices
+
+Implement liveness and readiness probes using `@nestjs/terminus`. Liveness checks determine if the service should be restarted. Readiness checks determine if the service can accept traffic. Proper health checks enable Kubernetes and load balancers to route traffic correctly.
+
+**Incorrect (simple ping that doesn't check dependencies):**
+
+```typescript
+// Simple ping that doesn't check dependencies
+@Controller('health')
+export class HealthController {
+ @Get()
+ check(): string {
+ return 'OK'; // Service might be unhealthy but returns OK
+ }
+}
+
+// Health check that blocks on slow dependencies
+@Controller('health')
+export class HealthController {
+ @Get()
+ async check(): Promise<string> {
+ // If database is slow, health check times out
+ await this.userRepo.findOne({ where: { id: '1' } });
+ await this.redis.ping();
+ await this.externalApi.healthCheck();
+ return 'OK';
+ }
+}
+```
+
+**Correct (use @nestjs/terminus for comprehensive health checks):**
+
+```typescript
+// Use @nestjs/terminus for comprehensive health checks
+import {
+ HealthCheckService,
+ HttpHealthIndicator,
+ TypeOrmHealthIndicator,
+ HealthCheck,
+ DiskHealthIndicator,
+ MemoryHealthIndicator,
+} from '@nestjs/terminus';
+
+@Controller('health')
+export class HealthController {
+ constructor(
+ private health: HealthCheckService,
+ private http: HttpHealthIndicator,
+ private db: TypeOrmHealthIndicator,
+ private disk: DiskHealthIndicator,
+ private memory: MemoryHealthIndicator,
+ ) {}
+
+ // Liveness probe - is the service alive?
+ @Get('live')
+ @HealthCheck()
+ liveness() {
+ return this.health.check([
+ // Basic checks only
+ () => this.memory.checkHeap('memory_heap', 200 * 1024 * 1024), // 200MB
+ ]);
+ }
+
+ // Readiness probe - can the service handle traffic?
+ @Get('ready')
+ @HealthCheck()
+ readiness() {
+ return this.health.check([
+ () => this.db.pingCheck('database'),
+ () =>
+ this.http.pingCheck('redis', 'http://redis:6379', { timeout: 1000 }),
+ () =>
+ this.disk.checkStorage('disk', { path: '/', thresholdPercent: 0.9 }),
+ ]);
+ }
+
+ // Deep health check for debugging
+ @Get('deep')
+ @HealthCheck()
+ deepCheck() {
+ return this.health.check([
+ () => this.db.pingCheck('database'),
+ () => this.memory.checkHeap('memory_heap', 200 * 1024 * 1024),
+ () => this.memory.checkRSS('memory_rss', 300 * 1024 * 1024),
+ () =>
+ this.disk.checkStorage('disk', { path: '/', thresholdPercent: 0.9 }),
+ () =>
+ this.http.pingCheck('external-api', 'https://api.example.com/health'),
+ ]);
+ }
+}
+
+// Custom indicator for business-specific health
+@Injectable()
+export class QueueHealthIndicator extends HealthIndicator {
+ constructor(private queueService: QueueService) {
+ super();
+ }
+
+ async isHealthy(key: string): Promise<HealthIndicatorResult> {
+ const queueStats = await this.queueService.getStats();
+
+ const isHealthy = queueStats.failedCount < 100;
+ const result = this.getStatus(key, isHealthy, {
+ waiting: queueStats.waitingCount,
+ active: queueStats.activeCount,
+ failed: queueStats.failedCount,
+ });
+
+ if (!isHealthy) {
+ throw new HealthCheckError('Queue unhealthy', result);
+ }
+
+ return result;
+ }
+}
+
+// Redis health indicator
+@Injectable()
+export class RedisHealthIndicator extends HealthIndicator {
+ constructor(@InjectRedis() private redis: Redis) {
+ super();
+ }
+
+ async isHealthy(key: string): Promise<HealthIndicatorResult> {
+ try {
+ const pong = await this.redis.ping();
+ return this.getStatus(key, pong === 'PONG');
+ } catch (error) {
+ throw new HealthCheckError('Redis check failed', this.getStatus(key, false));
+ }
+ }
+}
+
+// Use custom indicators
+@Get('ready')
+@HealthCheck()
+readiness() {
+ return this.health.check([
+ () => this.db.pingCheck('database'),
+ () => this.redis.isHealthy('redis'),
+ () => this.queue.isHealthy('job-queue'),
+ ]);
+}
+
+// Graceful shutdown handling
+@Injectable()
+export class GracefulShutdownService implements OnApplicationShutdown {
+ private isShuttingDown = false;
+
+ isShutdown(): boolean {
+ return this.isShuttingDown;
+ }
+
+ async onApplicationShutdown(signal: string): Promise<void> {
+ this.isShuttingDown = true;
+ console.log(`Shutting down on ${signal}`);
+
+ // Wait for in-flight requests
+ await new Promise((resolve) => setTimeout(resolve, 5000));
+ }
+}
+
+// Health check respects shutdown state
+@Get('ready')
+@HealthCheck()
+readiness() {
+ if (this.shutdownService.isShutdown()) {
+ throw new ServiceUnavailableException('Shutting down');
+ }
+
+ return this.health.check([
+ () => this.db.pingCheck('database'),
+ ]);
+}
+```
+
+### Kubernetes Configuration
+
+```yaml
+# Kubernetes deployment with probes
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: api-service
+spec:
+ template:
+ spec:
+ containers:
+ - name: api
+ image: api-service:latest
+ ports:
+ - containerPort: 3000
+ livenessProbe:
+ httpGet:
+ path: /health/live
+ port: 3000
+ initialDelaySeconds: 30
+ periodSeconds: 10
+ timeoutSeconds: 5
+ failureThreshold: 3
+ readinessProbe:
+ httpGet:
+ path: /health/ready
+ port: 3000
+ initialDelaySeconds: 5
+ periodSeconds: 5
+ timeoutSeconds: 3
+ failureThreshold: 3
+ startupProbe:
+ httpGet:
+ path: /health/live
+ port: 3000
+ initialDelaySeconds: 0
+ periodSeconds: 5
+ failureThreshold: 30
+```
+
+Reference: [NestJS Terminus](https://docs.nestjs.com/recipes/terminus)
diff --git a/.agents/skills/nestjs-best-practices/rules/micro-use-patterns.md b/.agents/skills/nestjs-best-practices/rules/micro-use-patterns.md
new file mode 100644
index 00000000..82d7c722
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/micro-use-patterns.md
@@ -0,0 +1,167 @@
+---
+title: Use Message and Event Patterns Correctly
+impact: MEDIUM
+impactDescription: Proper patterns ensure reliable microservice communication
+tags: microservices, message-pattern, event-pattern, communication
+---
+
+## Use Message and Event Patterns Correctly
+
+NestJS microservices support two communication patterns: request-response (MessagePattern) and event-based (EventPattern). Use MessagePattern when you need a response, and EventPattern for fire-and-forget notifications. Understanding the difference prevents communication bugs.
+
+**Incorrect (using wrong pattern for use case):**
+
+```typescript
+// Use @MessagePattern for fire-and-forget
+@Controller()
+export class NotificationsController {
+ @MessagePattern('user.created')
+ async handleUserCreated(data: UserCreatedEvent) {
+ // This WAITS for response, blocking the sender
+ await this.emailService.sendWelcome(data.email);
+ // If email fails, sender gets an error (coupling!)
+ }
+}
+
+// Use @EventPattern expecting a response
+@Controller()
+export class OrdersController {
+ @EventPattern('inventory.check')
+ async checkInventory(data: CheckInventoryDto) {
+ const available = await this.inventory.check(data);
+ return available; // This return value is IGNORED with @EventPattern!
+ }
+}
+
+// Tight coupling in client
+@Injectable()
+export class UsersService {
+ async createUser(dto: CreateUserDto): Promise<User> {
+ const user = await this.repo.save(dto);
+
+ // Blocks until notification service responds
+ await this.client.send('user.created', user).toPromise();
+ // If notification service is down, user creation fails!
+
+ return user;
+ }
+}
+```
+
+**Correct (use MessagePattern for request-response, EventPattern for fire-and-forget):**
+
+```typescript
+// MessagePattern: Request-Response (when you NEED a response)
+@Controller()
+export class InventoryController {
+ @MessagePattern({ cmd: 'check_inventory' })
+ async checkInventory(data: CheckInventoryDto): Promise<InventoryResult> {
+ const result = await this.inventoryService.check(data.productId, data.quantity);
+ return result; // Response sent back to caller
+ }
+}
+
+// Client expects response
+@Injectable()
+export class OrdersService {
+ async createOrder(dto: CreateOrderDto): Promise<Order> {
+ // Check inventory - we NEED this response to proceed
+ const inventory = await firstValueFrom(
+ this.inventoryClient.send<InventoryResult>(
+ { cmd: 'check_inventory' },
+ { productId: dto.productId, quantity: dto.quantity },
+ ),
+ );
+
+ if (!inventory.available) {
+ throw new BadRequestException('Insufficient inventory');
+ }
+
+ return this.repo.save(dto);
+ }
+}
+
+// EventPattern: Fire-and-Forget (for notifications, side effects)
+@Controller()
+export class NotificationsController {
+ @EventPattern('user.created')
+ async handleUserCreated(data: UserCreatedEvent): Promise<void> {
+ // No return value needed - just process the event
+ await this.emailService.sendWelcome(data.email);
+ await this.analyticsService.track('user_signup', data);
+ // If this fails, it doesn't affect the sender
+ }
+}
+
+// Client emits event without waiting
+@Injectable()
+export class UsersService {
+ async createUser(dto: CreateUserDto): Promise<User> {
+ const user = await this.repo.save(dto);
+
+ // Fire and forget - doesn't block, doesn't wait
+ this.eventClient.emit('user.created', {
+ userId: user.id,
+ email: user.email,
+ timestamp: new Date(),
+ });
+
+ return user; // User creation succeeds regardless of event handling
+ }
+}
+
+// Hybrid pattern for critical events
+@Injectable()
+export class OrdersService {
+ async createOrder(dto: CreateOrderDto): Promise<Order> {
+ const order = await this.repo.save(dto);
+
+ // Critical: inventory reservation (use MessagePattern)
+ const reserved = await firstValueFrom(
+ this.inventoryClient.send({ cmd: 'reserve_inventory' }, {
+ orderId: order.id,
+ items: dto.items,
+ }),
+ );
+
+ if (!reserved.success) {
+ await this.repo.delete(order.id);
+ throw new BadRequestException('Could not reserve inventory');
+ }
+
+ // Non-critical: notifications (use EventPattern)
+ this.eventClient.emit('order.created', {
+ orderId: order.id,
+ userId: dto.userId,
+ total: dto.total,
+ });
+
+ return order;
+ }
+}
+
+// Error handling patterns
+// MessagePattern errors propagate to caller
+@MessagePattern({ cmd: 'get_user' })
+async getUser(userId: string): Promise<User> {
+ const user = await this.repo.findOne({ where: { id: userId } });
+ if (!user) {
+ throw new RpcException('User not found'); // Received by caller
+ }
+ return user;
+}
+
+// EventPattern errors should be handled locally
+@EventPattern('order.created')
+async handleOrderCreated(data: OrderCreatedEvent): Promise<void> {
+ try {
+ await this.processOrder(data);
+ } catch (error) {
+ // Log and potentially retry - don't throw
+ this.logger.error('Failed to process order event', error);
+ await this.deadLetterQueue.add(data);
+ }
+}
+```
+
+Reference: [NestJS Microservices](https://docs.nestjs.com/microservices/basics)
diff --git a/.agents/skills/nestjs-best-practices/rules/micro-use-queues.md b/.agents/skills/nestjs-best-practices/rules/micro-use-queues.md
new file mode 100644
index 00000000..f9bc6725
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/micro-use-queues.md
@@ -0,0 +1,252 @@
+---
+title: Use Message Queues for Background Jobs
+impact: MEDIUM-HIGH
+impactDescription: Queues enable reliable background processing
+tags: microservices, queues, bullmq, background-jobs
+---
+
+## Use Message Queues for Background Jobs
+
+Use `@nestjs/bullmq` for background job processing. Queues decouple long-running tasks from HTTP requests, enable retry logic, and distribute workload across workers. Use them for emails, file processing, notifications, and any task that shouldn't block user requests.
+
+**Incorrect (long-running tasks in HTTP handlers):**
+
+```typescript
+// Long-running tasks in HTTP handlers
+@Controller('reports')
+export class ReportsController {
+ @Post()
+ async generate(@Body() dto: GenerateReportDto): Promise<Report> {
+ // This blocks the request for potentially minutes
+ const data = await this.fetchLargeDataset(dto);
+ const report = await this.processData(data); // Slow!
+ await this.sendEmail(dto.email, report); // Can fail!
+ return report; // Client times out
+ }
+}
+
+// Fire-and-forget without retry
+@Injectable()
+export class EmailService {
+ async sendWelcome(email: string): Promise<void> {
+ // If this fails, email is never sent
+ await this.mailer.send({ to: email, template: 'welcome' });
+ // No retry, no tracking, no visibility
+ }
+}
+
+// Use setInterval for scheduled tasks
+setInterval(async () => {
+ await cleanupOldRecords();
+}, 60000); // No error handling, memory leaks
+```
+
+**Correct (use BullMQ for background processing):**
+
+```typescript
+// Configure BullMQ
+import { BullModule } from '@nestjs/bullmq';
+
+@Module({
+ imports: [
+ BullModule.forRoot({
+ connection: {
+ host: 'localhost',
+ port: 6379,
+ },
+ defaultJobOptions: {
+ removeOnComplete: 1000,
+ removeOnFail: 5000,
+ attempts: 3,
+ backoff: {
+ type: 'exponential',
+ delay: 1000,
+ },
+ },
+ }),
+ BullModule.registerQueue(
+ { name: 'email' },
+ { name: 'reports' },
+ { name: 'notifications' },
+ ),
+ ],
+})
+export class QueueModule {}
+
+// Producer: Add jobs to queue
+@Injectable()
+export class ReportsService {
+ constructor(
+ @InjectQueue('reports') private reportsQueue: Queue,
+ ) {}
+
+ async requestReport(dto: GenerateReportDto): Promise<{ jobId: string }> {
+ // Return immediately, process in background
+ const job = await this.reportsQueue.add('generate', dto, {
+ priority: dto.urgent ? 1 : 10,
+ delay: dto.scheduledFor ? Date.parse(dto.scheduledFor) - Date.now() : 0,
+ });
+
+ return { jobId: job.id };
+ }
+
+ async getJobStatus(jobId: string): Promise<JobStatus> {
+ const job = await this.reportsQueue.getJob(jobId);
+ return {
+ status: await job.getState(),
+ progress: job.progress,
+ result: job.returnvalue,
+ };
+ }
+}
+
+// Consumer: Process jobs
+@Processor('reports')
+export class ReportsProcessor {
+ private readonly logger = new Logger(ReportsProcessor.name);
+
+ @Process('generate')
+ async generateReport(job: Job<GenerateReportDto>): Promise<Report> {
+ this.logger.log(`Processing report job ${job.id}`);
+
+ // Update progress
+ await job.updateProgress(10);
+
+ const data = await this.fetchData(job.data);
+ await job.updateProgress(50);
+
+ const report = await this.processData(data);
+ await job.updateProgress(90);
+
+ await this.saveReport(report);
+ await job.updateProgress(100);
+
+ return report;
+ }
+
+ @OnQueueActive()
+ onActive(job: Job) {
+ this.logger.log(`Processing job ${job.id}`);
+ }
+
+ @OnQueueCompleted()
+ onCompleted(job: Job, result: any) {
+ this.logger.log(`Job ${job.id} completed`);
+ }
+
+ @OnQueueFailed()
+ onFailed(job: Job, error: Error) {
+ this.logger.error(`Job ${job.id} failed: ${error.message}`);
+ }
+}
+
+// Email queue with retry
+@Processor('email')
+export class EmailProcessor {
+ @Process('send')
+ async sendEmail(job: Job<SendEmailDto>): Promise<void> {
+ const { to, template, data } = job.data;
+
+ try {
+ await this.mailer.send({
+ to,
+ template,
+ context: data,
+ });
+ } catch (error) {
+ // BullMQ will retry based on job options
+ throw error;
+ }
+ }
+}
+
+// Usage
+@Injectable()
+export class NotificationService {
+ constructor(@InjectQueue('email') private emailQueue: Queue) {}
+
+ async sendWelcome(user: User): Promise<void> {
+ await this.emailQueue.add(
+ 'send',
+ {
+ to: user.email,
+ template: 'welcome',
+ data: { name: user.name },
+ },
+ {
+ attempts: 5,
+ backoff: { type: 'exponential', delay: 5000 },
+ },
+ );
+ }
+}
+
+// Scheduled jobs
+@Injectable()
+export class ScheduledJobsService implements OnModuleInit {
+ constructor(@InjectQueue('maintenance') private queue: Queue) {}
+
+ async onModuleInit(): Promise<void> {
+ // Clean up old reports daily at midnight
+ await this.queue.add(
+ 'cleanup',
+ {},
+ {
+ repeat: { cron: '0 0 * * *' },
+ jobId: 'daily-cleanup', // Prevent duplicates
+ },
+ );
+
+ // Send digest every hour
+ await this.queue.add(
+ 'digest',
+ {},
+ {
+ repeat: { every: 60 * 60 * 1000 },
+ jobId: 'hourly-digest',
+ },
+ );
+ }
+}
+
+@Processor('maintenance')
+export class MaintenanceProcessor {
+ @Process('cleanup')
+ async cleanup(): Promise<void> {
+ await this.cleanupOldReports();
+ await this.cleanupExpiredSessions();
+ }
+
+ @Process('digest')
+ async sendDigest(): Promise<void> {
+ const users = await this.getUsersForDigest();
+ for (const user of users) {
+ await this.emailQueue.add('send', { to: user.email, template: 'digest' });
+ }
+ }
+}
+
+// Queue monitoring with Bull Board
+import { BullBoardModule } from '@bull-board/nestjs';
+import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';
+
+@Module({
+ imports: [
+ BullBoardModule.forRoot({
+ route: '/admin/queues',
+ adapter: ExpressAdapter,
+ }),
+ BullBoardModule.forFeature({
+ name: 'email',
+ adapter: BullMQAdapter,
+ }),
+ BullBoardModule.forFeature({
+ name: 'reports',
+ adapter: BullMQAdapter,
+ }),
+ ],
+})
+export class AdminModule {}
+```
+
+Reference: [NestJS Queues](https://docs.nestjs.com/techniques/queues)
diff --git a/.agents/skills/nestjs-best-practices/rules/perf-async-hooks.md b/.agents/skills/nestjs-best-practices/rules/perf-async-hooks.md
new file mode 100644
index 00000000..7ca00771
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/perf-async-hooks.md
@@ -0,0 +1,109 @@
+---
+title: Use Async Lifecycle Hooks Correctly
+impact: HIGH
+impactDescription: Improper async handling blocks application startup
+tags: performance, lifecycle, async, hooks
+---
+
+## Use Async Lifecycle Hooks Correctly
+
+NestJS lifecycle hooks (`onModuleInit`, `onApplicationBootstrap`, etc.) support async operations. However, misusing them can block application startup or cause race conditions. Understand the lifecycle order and use hooks appropriately.
+
+**Incorrect (fire-and-forget async without await):**
+
+```typescript
+// Fire-and-forget async without await
+@Injectable()
+export class DatabaseService implements OnModuleInit {
+ onModuleInit() {
+ // This runs but doesn't block - app starts before DB is ready!
+ this.connect();
+ }
+
+ private async connect() {
+ await this.pool.connect();
+ console.log('Database connected');
+ }
+}
+
+// Heavy blocking operations in constructor
+@Injectable()
+export class ConfigService {
+ private config: Config;
+
+ constructor() {
+ // BLOCKS entire module instantiation synchronously
+ this.config = fs.readFileSync('config.json');
+ }
+}
+```
+
+**Correct (return promises from async hooks):**
+
+```typescript
+// Return promise from async hooks
+@Injectable()
+export class DatabaseService implements OnModuleInit {
+ private pool: Pool;
+
+ async onModuleInit(): Promise<void> {
+ // NestJS waits for this to complete before continuing
+ await this.pool.connect();
+ console.log('Database connected');
+ }
+
+ async onModuleDestroy(): Promise<void> {
+ // Clean up resources on shutdown
+ await this.pool.end();
+ console.log('Database disconnected');
+ }
+}
+
+// Use onApplicationBootstrap for cross-module dependencies
+@Injectable()
+export class CacheWarmerService implements OnApplicationBootstrap {
+ constructor(
+ private cache: CacheService,
+ private products: ProductsService,
+ ) {}
+
+ async onApplicationBootstrap(): Promise<void> {
+ // All modules are initialized, safe to warm cache
+ const products = await this.products.findPopular();
+ await this.cache.warmup(products);
+ }
+}
+
+// Heavy init in async hooks, not constructor
+@Injectable()
+export class ConfigService implements OnModuleInit {
+ private config: Config;
+
+ constructor() {
+ // Keep constructor synchronous and fast
+ }
+
+ async onModuleInit(): Promise<void> {
+ // Async loading in lifecycle hook
+ this.config = await this.loadConfig();
+ }
+
+ private async loadConfig(): Promise<Config> {
+ const file = await fs.promises.readFile('config.json');
+ return JSON.parse(file.toString());
+ }
+
+ get<T>(key: string): T {
+ return this.config[key];
+ }
+}
+
+// Enable shutdown hooks in main.ts
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule);
+ app.enableShutdownHooks(); // Enable SIGTERM/SIGINT handling
+ await app.listen(3000);
+}
+```
+
+Reference: [NestJS Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events)
diff --git a/.agents/skills/nestjs-best-practices/rules/perf-lazy-loading.md b/.agents/skills/nestjs-best-practices/rules/perf-lazy-loading.md
new file mode 100644
index 00000000..8bcc5828
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/perf-lazy-loading.md
@@ -0,0 +1,121 @@
+---
+title: Use Lazy Loading for Large Modules
+impact: MEDIUM
+impactDescription: Improves startup time for large applications
+tags: performance, lazy-loading, modules, optimization
+---
+
+## Use Lazy Loading for Large Modules
+
+NestJS supports lazy-loading modules, which defers initialization until first use. This is valuable for large applications where some features are rarely used, serverless deployments where cold start time matters, or when certain modules have heavy initialization costs.
+
+**Incorrect (loading everything eagerly):**
+
+```typescript
+// Load everything eagerly in a large app
+@Module({
+ imports: [
+ UsersModule,
+ OrdersModule,
+ PaymentsModule,
+ ReportsModule, // Heavy, rarely used
+ AnalyticsModule, // Heavy, rarely used
+ AdminModule, // Only admins use this
+ LegacyModule, // Migration module, rarely used
+ BulkImportModule, // Used once a month
+ ],
+})
+export class AppModule {}
+
+// All modules initialize at startup, even if never used
+// Slow cold starts in serverless
+// Memory wasted on unused modules
+```
+
+**Correct (lazy load rarely-used modules):**
+
+```typescript
+// Use LazyModuleLoader for optional modules
+import { LazyModuleLoader } from '@nestjs/core';
+
+@Injectable()
+export class ReportsService {
+ constructor(private lazyModuleLoader: LazyModuleLoader) {}
+
+ async generateReport(type: string): Promise<Report> {
+ // Load module only when needed
+ const { ReportsModule } = await import('./reports/reports.module');
+ const moduleRef = await this.lazyModuleLoader.load(() => ReportsModule);
+
+ const reportsService = moduleRef.get(ReportsGeneratorService);
+ return reportsService.generate(type);
+ }
+}
+
+// Lazy load admin features with caching
+@Injectable()
+export class AdminService {
+ private adminModule: ModuleRef | null = null;
+
+ constructor(private lazyModuleLoader: LazyModuleLoader) {}
+
+ private async getAdminModule(): Promise<ModuleRef> {
+ if (!this.adminModule) {
+ const { AdminModule } = await import('./admin/admin.module');
+ this.adminModule = await this.lazyModuleLoader.load(() => AdminModule);
+ }
+ return this.adminModule;
+ }
+
+ async runAdminTask(task: string): Promise<void> {
+ const moduleRef = await this.getAdminModule();
+ const taskRunner = moduleRef.get(AdminTaskRunner);
+ await taskRunner.run(task);
+ }
+}
+
+// Reusable lazy loader service
+@Injectable()
+export class ModuleLoaderService {
+ private loadedModules = new Map<string, ModuleRef>();
+
+ constructor(private lazyModuleLoader: LazyModuleLoader) {}
+
+ async load<T>(
+ key: string,
+ importFn: () => Promise<{ default: Type<T> } | Type<T>>,
+ ): Promise<ModuleRef> {
+ if (!this.loadedModules.has(key)) {
+ const module = await importFn();
+ const moduleType = 'default' in module ? module.default : module;
+ const moduleRef = await this.lazyModuleLoader.load(() => moduleType);
+ this.loadedModules.set(key, moduleRef);
+ }
+ return this.loadedModules.get(key)!;
+ }
+}
+
+// Preload modules in background after startup
+@Injectable()
+export class ModulePreloader implements OnApplicationBootstrap {
+ constructor(private lazyModuleLoader: LazyModuleLoader) {}
+
+ async onApplicationBootstrap(): Promise<void> {
+ setTimeout(async () => {
+ await this.preloadModule(() => import('./reports/reports.module'));
+ }, 5000); // 5 seconds after startup
+ }
+
+ private async preloadModule(importFn: () => Promise<any>): Promise<void> {
+ try {
+ const module = await importFn();
+ const moduleType = module.default || Object.values(module)[0];
+ await this.lazyModuleLoader.load(() => moduleType);
+ } catch (error) {
+ console.warn('Failed to preload module', error);
+ }
+ }
+}
+```
+
+Reference: [NestJS Lazy Loading Modules](https://docs.nestjs.com/fundamentals/lazy-loading-modules)
diff --git a/.agents/skills/nestjs-best-practices/rules/perf-optimize-database.md b/.agents/skills/nestjs-best-practices/rules/perf-optimize-database.md
new file mode 100644
index 00000000..964189f7
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/perf-optimize-database.md
@@ -0,0 +1,131 @@
+---
+title: Optimize Database Queries
+impact: HIGH
+impactDescription: Database queries are typically the largest source of latency
+tags: performance, database, queries, optimization
+---
+
+## Optimize Database Queries
+
+Select only needed columns, use proper indexes, avoid over-fetching relations, and consider query performance when designing your data access. Most API slowness traces back to inefficient database queries.
+
+**Incorrect (over-fetching data and missing indexes):**
+
+```typescript
+// Select everything when you need few fields
+@Injectable()
+export class UsersService {
+ async findAllEmails(): Promise<string[]> {
+ const users = await this.repo.find();
+ // Fetches ALL columns for ALL users
+ return users.map((u) => u.email);
+ }
+
+ async getUserSummary(id: string): Promise<UserSummary> {
+ const user = await this.repo.findOne({
+ where: { id },
+ relations: ['posts', 'posts.comments', 'posts.comments.author', 'followers'],
+ });
+ // Over-fetches massive relation tree
+ return { name: user.name, postCount: user.posts.length };
+ }
+}
+
+// No indexes on frequently queried columns
+@Entity()
+export class Order {
+ @Column()
+ userId: string; // No index - full table scan on every lookup
+
+ @Column()
+ status: string; // No index - slow status filtering
+}
+```
+
+**Correct (select only needed data with proper indexes):**
+
+```typescript
+// Select only needed columns
+@Injectable()
+export class UsersService {
+ async findAllEmails(): Promise<string[]> {
+ const users = await this.repo.find({
+ select: ['email'], // Only fetch email column
+ });
+ return users.map((u) => u.email);
+ }
+
+ // Use QueryBuilder for complex selections
+ async getUserSummary(id: string): Promise<UserSummary> {
+ return this.repo
+ .createQueryBuilder('user')
+ .select('user.name', 'name')
+ .addSelect('COUNT(post.id)', 'postCount')
+ .leftJoin('user.posts', 'post')
+ .where('user.id = :id', { id })
+ .groupBy('user.id')
+ .getRawOne();
+ }
+
+ // Fetch relations only when needed
+ async getFullProfile(id: string): Promise<User> {
+ return this.repo.findOne({
+ where: { id },
+ relations: ['posts'], // Only immediate relation
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ posts: {
+ id: true,
+ title: true,
+ },
+ },
+ });
+ }
+}
+
+// Add indexes on frequently queried columns
+@Entity()
+@Index(['userId'])
+@Index(['status'])
+@Index(['createdAt'])
+@Index(['userId', 'status']) // Composite index for common query pattern
+export class Order {
+ @PrimaryGeneratedColumn('uuid')
+ id: string;
+
+ @Column()
+ userId: string;
+
+ @Column()
+ status: string;
+
+ @CreateDateColumn()
+ createdAt: Date;
+}
+
+// Always paginate large datasets
+@Injectable()
+export class OrdersService {
+ async findAll(page = 1, limit = 20): Promise<PaginatedResult<Order>> {
+ const [items, total] = await this.repo.findAndCount({
+ skip: (page - 1) * limit,
+ take: limit,
+ order: { createdAt: 'DESC' },
+ });
+
+ return {
+ items,
+ meta: {
+ page,
+ limit,
+ total,
+ totalPages: Math.ceil(total / limit),
+ },
+ };
+ }
+}
+```
+
+Reference: [TypeORM Query Builder](https://typeorm.io/select-query-builder)
diff --git a/.agents/skills/nestjs-best-practices/rules/perf-use-caching.md b/.agents/skills/nestjs-best-practices/rules/perf-use-caching.md
new file mode 100644
index 00000000..71706907
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/perf-use-caching.md
@@ -0,0 +1,128 @@
+---
+title: Use Caching Strategically
+impact: HIGH
+impactDescription: Dramatically reduces database load and response times
+tags: performance, caching, redis, optimization
+---
+
+## Use Caching Strategically
+
+Implement caching for expensive operations, frequently accessed data, and external API calls. Use NestJS CacheModule with appropriate TTLs and cache invalidation strategies. Don't cache everything - focus on high-impact areas.
+
+**Incorrect (no caching or caching everything):**
+
+```typescript
+// No caching for expensive, repeated queries
+@Injectable()
+export class ProductsService {
+ async getPopular(): Promise<Product[]> {
+ // Runs complex aggregation query EVERY request
+ return this.productsRepo
+ .createQueryBuilder('p')
+ .leftJoin('p.orders', 'o')
+ .select('p.*, COUNT(o.id) as orderCount')
+ .groupBy('p.id')
+ .orderBy('orderCount', 'DESC')
+ .limit(20)
+ .getMany();
+ }
+}
+
+// Cache everything without thought
+@Injectable()
+export class UsersService {
+ @CacheKey('users')
+ @CacheTTL(3600)
+ @UseInterceptors(CacheInterceptor)
+ async findAll(): Promise<User[]> {
+ // Caching user list for 1 hour is wrong if data changes frequently
+ return this.usersRepo.find();
+ }
+}
+```
+
+**Correct (strategic caching with proper invalidation):**
+
+```typescript
+// Setup caching module
+@Module({
+ imports: [
+ CacheModule.registerAsync({
+ imports: [ConfigModule],
+ inject: [ConfigService],
+ useFactory: (config: ConfigService) => ({
+ stores: [
+ new KeyvRedis(config.get('REDIS_URL')),
+ ],
+ ttl: 60 * 1000, // Default 60s
+ }),
+ }),
+ ],
+})
+export class AppModule {}
+
+// Manual caching for granular control
+@Injectable()
+export class ProductsService {
+ constructor(
+ @Inject(CACHE_MANAGER) private cache: Cache,
+ private productsRepo: ProductRepository,
+ ) {}
+
+ async getPopular(): Promise<Product[]> {
+ const cacheKey = 'products:popular';
+
+ // Try cache first
+ const cached = await this.cache.get<Product[]>(cacheKey);
+ if (cached) return cached;
+
+ // Cache miss - fetch and cache
+ const products = await this.fetchPopularProducts();
+ await this.cache.set(cacheKey, products, 5 * 60 * 1000); // 5 min TTL
+ return products;
+ }
+
+ // Invalidate cache on changes
+ async updateProduct(id: string, dto: UpdateProductDto): Promise<Product> {
+ const product = await this.productsRepo.save({ id, ...dto });
+ await this.cache.del('products:popular'); // Invalidate
+ return product;
+ }
+}
+
+// Decorator-based caching with auto-interceptor
+@Controller('categories')
+@UseInterceptors(CacheInterceptor)
+export class CategoriesController {
+ @Get()
+ @CacheTTL(30 * 60 * 1000) // 30 minutes - categories rarely change
+ findAll(): Promise<Category[]> {
+ return this.categoriesService.findAll();
+ }
+
+ @Get(':id')
+ @CacheTTL(60 * 1000) // 1 minute
+ @CacheKey('category')
+ findOne(@Param('id') id: string): Promise<Category> {
+ return this.categoriesService.findOne(id);
+ }
+}
+
+// Event-based cache invalidation
+@Injectable()
+export class CacheInvalidationService {
+ constructor(@Inject(CACHE_MANAGER) private cache: Cache) {}
+
+ @OnEvent('product.created')
+ @OnEvent('product.updated')
+ @OnEvent('product.deleted')
+ async invalidateProductCaches(event: ProductEvent) {
+ await Promise.all([
+ this.cache.del('products:popular'),
+ this.cache.del(`product:${event.productId}`),
+ ]);
+ }
+}
+```
+
+Reference: [NestJS Caching](https://docs.nestjs.com/techniques/caching)
diff --git a/.agents/skills/nestjs-best-practices/rules/security-auth-jwt.md b/.agents/skills/nestjs-best-practices/rules/security-auth-jwt.md
new file mode 100644
index 00000000..a0d1ff03
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/security-auth-jwt.md
@@ -0,0 +1,146 @@
+---
+title: Implement Secure JWT Authentication
+impact: CRITICAL
+impactDescription: Essential for secure APIs
+tags: security, jwt, authentication, tokens
+---
+
+## Implement Secure JWT Authentication
+
+Use `@nestjs/jwt` with `@nestjs/passport` for authentication. Store secrets securely, use appropriate token lifetimes, implement refresh tokens, and validate tokens properly. Never expose sensitive data in JWT payloads.
+
+**Incorrect (insecure JWT implementation):**
+
+```typescript
+// Hardcode secrets
+@Module({
+ imports: [
+ JwtModule.register({
+ secret: 'my-secret-key', // Exposed in code
+ signOptions: { expiresIn: '7d' }, // Too long
+ }),
+ ],
+})
+export class AuthModule {}
+
+// Store sensitive data in JWT
+async login(user: User): Promise<{ accessToken: string }> {
+ const payload = {
+ sub: user.id,
+ email: user.email,
+ password: user.password, // NEVER include password!
+ ssn: user.ssn, // NEVER include sensitive data!
+ isAdmin: user.isAdmin, // Can be tampered if not verified
+ };
+ return { accessToken: this.jwtService.sign(payload) };
+}
+
+// Skip token validation
+@Injectable()
+export class JwtStrategy extends PassportStrategy(Strategy) {
+ constructor() {
+ super({
+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
+ secretOrKey: 'my-secret',
+ });
+ }
+
+ async validate(payload: any): Promise<any> {
+ return payload; // No validation of user existence
+ }
+}
+```
+
+**Correct (secure JWT with refresh tokens):**
+
+```typescript
+// Secure JWT configuration
+@Module({
+ imports: [
+ JwtModule.registerAsync({
+ imports: [ConfigModule],
+ inject: [ConfigService],
+ useFactory: (config: ConfigService) => ({
+ secret: config.get<string>('JWT_SECRET'),
+ signOptions: {
+ expiresIn: '15m', // Short-lived access tokens
+ issuer: config.get<string>('JWT_ISSUER'),
+ audience: config.get<string>('JWT_AUDIENCE'),
+ },
+ }),
+ }),
+ PassportModule.register({ defaultStrategy: 'jwt' }),
+ ],
+})
+export class AuthModule {}
+
+// Minimal JWT payload
+@Injectable()
+export class AuthService {
+ async login(user: User): Promise<TokenResponse> {
+ // Only include necessary, non-sensitive data
+ const payload: JwtPayload = {
+ sub: user.id,
+ email: user.email,
+ roles: user.roles,
+ iat: Math.floor(Date.now() / 1000),
+ };
+
+ const accessToken = this.jwtService.sign(payload);
+ const refreshToken = await this.createRefreshToken(user.id);
+
+ return { accessToken, refreshToken, expiresIn: 900 };
+ }
+
+ private async createRefreshToken(userId: string): Promise<string> {
+ const token = randomBytes(32).toString('hex');
+ const hashedToken = await bcrypt.hash(token, 10);
+
+ await this.refreshTokenRepo.save({
+ userId,
+ token: hashedToken,
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
+ });
+
+ return token;
+ }
+}
+
+// Proper JWT strategy with validation
+@Injectable()
+export class JwtStrategy extends PassportStrategy(Strategy) {
+ constructor(
+ private config: ConfigService,
+ private usersService: UsersService,
+ ) {
+ super({
+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
+ secretOrKey: config.get<string>('JWT_SECRET'),
+ ignoreExpiration: false,
+ issuer: config.get<string>('JWT_ISSUER'),
+ audience: config.get<string>('JWT_AUDIENCE'),
+ });
+ }
+
+ async validate(payload: JwtPayload): Promise<User> {
+ // Verify user still exists and is active
+ const user = await this.usersService.findById(payload.sub);
+
+ if (!user || !user.isActive) {
+ throw new UnauthorizedException('User not found or inactive');
+ }
+
+ // Verify token wasn't issued before password change
+ if (user.passwordChangedAt) {
+ const tokenIssuedAt = new Date(payload.iat * 1000);
+ if (tokenIssuedAt < user.passwordChangedAt) {
+ throw new UnauthorizedException('Token invalidated by password change');
+ }
+ }
+
+ return user;
+ }
+}
+```
+
+Reference: [NestJS Authentication](https://docs.nestjs.com/security/authentication)
diff --git a/.agents/skills/nestjs-best-practices/rules/security-rate-limiting.md b/.agents/skills/nestjs-best-practices/rules/security-rate-limiting.md
new file mode 100644
index 00000000..7d39e9c8
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/security-rate-limiting.md
@@ -0,0 +1,125 @@
+---
+title: Implement Rate Limiting
+impact: HIGH
+impactDescription: Protects against abuse and ensures fair resource usage
+tags: security, rate-limiting, throttler, protection
+---
+
+## Implement Rate Limiting
+
+Use `@nestjs/throttler` to limit request rates per client. Apply different limits for different endpoints - stricter for auth endpoints, more relaxed for read operations. Consider using Redis for distributed rate limiting in clustered deployments.
+
+**Incorrect (no rate limiting on sensitive endpoints):**
+
+```typescript
+// No rate limiting on sensitive endpoints
+@Controller('auth')
+export class AuthController {
+ @Post('login')
+ async login(@Body() dto: LoginDto): Promise<TokenResponse> {
+ // Attackers can brute-force credentials
+ return this.authService.login(dto);
+ }
+
+ @Post('forgot-password')
+ async forgotPassword(@Body() dto: ForgotPasswordDto): Promise<void> {
+ // Can be abused to spam users with emails
+ return this.authService.sendResetEmail(dto.email);
+ }
+}
+
+// Same limits for all endpoints
+@UseGuards(ThrottlerGuard)
+@Controller('api')
+export class ApiController {
+ @Get('public-data')
+ async getPublic() {} // Should allow more requests
+
+ @Post('process-payment')
+ async payment() {} // Should be more restrictive
+}
+```
+
+**Correct (configured throttler with endpoint-specific limits):**
+
+```typescript
+// Configure throttler globally with multiple limits
+import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
+
+@Module({
+ imports: [
+ ThrottlerModule.forRoot([
+ {
+ name: 'short',
+ ttl: 1000, // 1 second
+ limit: 3, // 3 requests per second
+ },
+ {
+ name: 'medium',
+ ttl: 10000, // 10 seconds
+ limit: 20, // 20 requests per 10 seconds
+ },
+ {
+ name: 'long',
+ ttl: 60000, // 1 minute
+ limit: 100, // 100 requests per minute
+ },
+ ]),
+ ],
+ providers: [
+ {
+ provide: APP_GUARD,
+ useClass: ThrottlerGuard,
+ },
+ ],
+})
+export class AppModule {}
+
+// Override limits per endpoint
+@Controller('auth')
+export class AuthController {
+ @Post('login')
+ @Throttle({ short: { limit: 5, ttl: 60000 } }) // 5 attempts per minute
+ async login(@Body() dto: LoginDto): Promise<TokenResponse> {
+ return this.authService.login(dto);
+ }
+
+ @Post('forgot-password')
+ @Throttle({ short: { limit: 3, ttl: 3600000 } }) // 3 per hour
+ async forgotPassword(@Body() dto: ForgotPasswordDto): Promise<void> {
+ return this.authService.sendResetEmail(dto.email);
+ }
+}
+
+// Skip throttling for certain routes
+@Controller('health')
+export class HealthController {
+ @Get()
+ @SkipThrottle()
+ check(): string {
+ return 'OK';
+ }
+}
+
+// Custom throttle per user type
+@Injectable()
+export class CustomThrottlerGuard extends ThrottlerGuard {
+ protected async getTracker(req: Request): Promise<string> {
+ // Use user ID if authenticated, IP otherwise
+ return req.user?.id || req.ip;
+ }
+
+ protected async getLimit(context: ExecutionContext): Promise<number> {
+ const request = context.switchToHttp().getRequest();
+
+ // Higher limits for authenticated users
+ if (request.user) {
+ return request.user.isPremium ? 1000 : 200;
+ }
+
+ return 50; // Anonymous users
+ }
+}
+```
+
+Reference: [NestJS Throttler](https://docs.nestjs.com/security/rate-limiting)
diff --git a/.agents/skills/nestjs-best-practices/rules/security-sanitize-output.md b/.agents/skills/nestjs-best-practices/rules/security-sanitize-output.md
new file mode 100644
index 00000000..78e3d396
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/security-sanitize-output.md
@@ -0,0 +1,139 @@
+---
+title: Sanitize Output to Prevent XSS
+impact: HIGH
+impactDescription: XSS vulnerabilities can compromise user sessions and data
+tags: security, xss, sanitization, html
+---
+
+## Sanitize Output to Prevent XSS
+
+While NestJS APIs typically return JSON (which browsers don't execute), XSS risks exist when rendering HTML, storing user content, or when frontend frameworks improperly handle API responses. Sanitize user-generated content before storage and use proper Content-Type headers.
+
+**Incorrect (storing raw HTML without sanitization):**
+
+```typescript
+// Store raw HTML from users
+@Injectable()
+export class CommentsService {
+ async create(dto: CreateCommentDto): Promise<Comment> {
+ // User can inject: <script>steal(document.cookie)</script>
+ return this.repo.save({
+ content: dto.content, // Raw, unsanitized
+ authorId: dto.authorId,
+ });
+ }
+}
+
+// Return HTML without sanitization
+@Controller('pages')
+export class PagesController {
+ @Get(':slug')
+ @Header('Content-Type', 'text/html')
+ async getPage(@Param('slug') slug: string): Promise<string> {
+ const page = await this.pagesService.findBySlug(slug);
+ // If page.content contains user input, XSS is possible
+ return `<html><body>${page.content}</body></html>`;
+ }
+}
+
+// Reflect user input in errors
+@Get(':id')
+async findOne(@Param('id') id: string): Promise<User> {
+ const user = await this.repo.findOne({ where: { id } });
+ if (!user) {
+ // XSS if id contains malicious content and error is rendered
+ throw new NotFoundException(`User ${id} not found`);
+ }
+ return user;
+}
+```
+
+**Correct (sanitize content and use proper headers):**
+
+```typescript
+// Sanitize HTML content before storage
+import * as sanitizeHtml from 'sanitize-html';
+
+@Injectable()
+export class CommentsService {
+ private readonly sanitizeOptions: sanitizeHtml.IOptions = {
+ allowedTags: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'],
+ allowedAttributes: {
+ a: ['href', 'title'],
+ },
+ allowedSchemes: ['http', 'https', 'mailto'],
+ };
+
+ async create(dto: CreateCommentDto): Promise<Comment> {
+ return this.repo.save({
+ content: sanitizeHtml(dto.content, this.sanitizeOptions),
+ authorId: dto.authorId,
+ });
+ }
+}
+
+// Use validation pipe to strip HTML
+import { Transform } from 'class-transformer';
+
+export class CreatePostDto {
+ @IsString()
+ @MaxLength(1000)
+ @Transform(({ value }) => sanitizeHtml(value, { allowedTags: [] }))
+ title: string;
+
+ @IsString()
+ @Transform(({ value }) =>
+ sanitizeHtml(value, {
+ allowedTags: ['p', 'br', 'b', 'i', 'a'],
+ allowedAttributes: { a: ['href'] },
+ }),
+ )
+ content: string;
+}
+
+// Set proper Content-Type headers
+@Controller('api')
+export class ApiController {
+ @Get('data')
+ @Header('Content-Type', 'application/json')
+ async getData(): Promise<DataResponse> {
+ // JSON response - browser won't execute scripts
+ return this.service.getData();
+ }
+}
+
+// Sanitize error messages
+@Get(':id')
+async findOne(@Param('id', ParseUUIDPipe) id: string): Promise<User> {
+ const user = await this.repo.findOne({ where: { id } });
+ if (!user) {
+ // UUID validation ensures safe format
+ throw new NotFoundException('User not found');
+ }
+ return user;
+}
+
+// Use Helmet for CSP headers
+import helmet from 'helmet';
+
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule);
+
+ app.use(
+ helmet({
+ contentSecurityPolicy: {
+ directives: {
+ defaultSrc: ["'self'"],
+ scriptSrc: ["'self'"],
+ styleSrc: ["'self'", "'unsafe-inline'"],
+ imgSrc: ["'self'", 'data:', 'https:'],
+ },
+ },
+ }),
+ );
+
+ await app.listen(3000);
+}
+```
+
+Reference: [OWASP XSS Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)
diff --git a/.agents/skills/nestjs-best-practices/rules/security-use-guards.md b/.agents/skills/nestjs-best-practices/rules/security-use-guards.md
new file mode 100644
index 00000000..fb1359c4
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/security-use-guards.md
@@ -0,0 +1,135 @@
+---
+title: Use Guards for Authentication and Authorization
+impact: HIGH
+impactDescription: Enforces access control before handlers execute
+tags: security, guards, authentication, authorization
+---
+
+## Use Guards for Authentication and Authorization
+
+Guards determine whether a request should be handled based on authentication state, roles, permissions, or other conditions. They run after middleware but before pipes and interceptors, making them ideal for access control. Use guards instead of manual checks in controllers.
+
+**Incorrect (manual auth checks in every handler):**
+
+```typescript
+// Manual auth checks in every handler
+@Controller('admin')
+export class AdminController {
+ @Get('users')
+ async getUsers(@Request() req) {
+ if (!req.user) {
+ throw new UnauthorizedException();
+ }
+ if (!req.user.roles.includes('admin')) {
+ throw new ForbiddenException();
+ }
+ return this.adminService.getUsers();
+ }
+
+ @Delete('users/:id')
+ async deleteUser(@Request() req, @Param('id') id: string) {
+ if (!req.user) {
+ throw new UnauthorizedException();
+ }
+ if (!req.user.roles.includes('admin')) {
+ throw new ForbiddenException();
+ }
+ return this.adminService.deleteUser(id);
+ }
+}
+```
+
+**Correct (guards with declarative decorators):**
+
+```typescript
+// JWT Auth Guard
+@Injectable()
+export class JwtAuthGuard implements CanActivate {
+ constructor(
+ private jwtService: JwtService,
+ private reflector: Reflector,
+ ) {}
+
+ async canActivate(context: ExecutionContext): Promise<boolean> {
+ // Check for @Public() decorator
+ const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
+ context.getHandler(),
+ context.getClass(),
+ ]);
+ if (isPublic) return true;
+
+ const request = context.switchToHttp().getRequest();
+ const token = this.extractToken(request);
+
+ if (!token) {
+ throw new UnauthorizedException('No token provided');
+ }
+
+ try {
+ request.user = await this.jwtService.verifyAsync(token);
+ return true;
+ } catch {
+ throw new UnauthorizedException('Invalid token');
+ }
+ }
+
+ private extractToken(request: Request): string | undefined {
+ const [type, token] = request.headers.authorization?.split(' ') ?? [];
+ return type === 'Bearer' ? token : undefined;
+ }
+}
+
+// Roles Guard
+@Injectable()
+export class RolesGuard implements CanActivate {
+ constructor(private reflector: Reflector) {}
+
+ canActivate(context: ExecutionContext): boolean {
+ const requiredRoles = this.reflector.getAllAndOverride<Role[]>('roles', [
+ context.getHandler(),
+ context.getClass(),
+ ]);
+
+ if (!requiredRoles) return true;
+
+ const { user } = context.switchToHttp().getRequest();
+ return requiredRoles.some((role) => user.roles?.includes(role));
+ }
+}
+
+// Decorators
+export const Public = () => SetMetadata('isPublic', true);
+export const Roles = (...roles: Role[]) => SetMetadata('roles', roles);
+
+// Register guards globally
+@Module({
+ providers: [
+ { provide: APP_GUARD, useClass: JwtAuthGuard },
+ { provide: APP_GUARD, useClass: RolesGuard },
+ ],
+})
+export class AppModule {}
+
+// Clean controller
+@Controller('admin')
+@Roles(Role.Admin) // Applied to all routes
+export class AdminController {
+ @Get('users')
+ getUsers(): Promise<User[]> {
+ return this.adminService.getUsers();
+ }
+
+ @Delete('users/:id')
+ deleteUser(@Param('id') id: string): Promise<void> {
+ return this.adminService.deleteUser(id);
+ }
+
+ @Public() // Override: no auth required
+ @Get('health')
+ health() {
+ return { status: 'ok' };
+ }
+}
+```
+
+Reference: [NestJS Guards](https://docs.nestjs.com/guards)
diff --git a/.agents/skills/nestjs-best-practices/rules/security-validate-all-input.md b/.agents/skills/nestjs-best-practices/rules/security-validate-all-input.md
new file mode 100644
index 00000000..f489d064
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/security-validate-all-input.md
@@ -0,0 +1,150 @@
+---
+title: Validate All Input with DTOs and Pipes
+impact: HIGH
+impactDescription: First line of defense against attacks
+tags: security, validation, dto, pipes
+---
+
+## Validate All Input with DTOs and Pipes
+
+Always validate incoming data using class-validator decorators on DTOs and the global ValidationPipe. Never trust user input. Validate all request bodies, query parameters, and route parameters before processing.
+
+**Incorrect (trust raw input without validation):**
+
+```typescript
+// Trust raw input without validation
+@Controller('users')
+export class UsersController {
+ @Post()
+ create(@Body() body: any) {
+ // body could contain anything - SQL injection, XSS, etc.
+ return this.usersService.create(body);
+ }
+
+ @Get()
+ findAll(@Query() query: any) {
+ // query.limit could be "'; DROP TABLE users; --"
+ return this.usersService.findAll(query.limit);
+ }
+}
+
+// DTOs without validation decorators
+export class CreateUserDto {
+ name: string; // No validation
+ email: string; // Could be "not-an-email"
+ age: number; // Could be "abc" or -999
+}
+```
+
+**Correct (validated DTOs with global ValidationPipe):**
+
+```typescript
+// Enable ValidationPipe globally in main.ts
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule);
+
+ app.useGlobalPipes(
+ new ValidationPipe({
+ whitelist: true, // Strip unknown properties
+ forbidNonWhitelisted: true, // Throw on unknown properties
+ transform: true, // Auto-transform to DTO types
+ transformOptions: {
+ enableImplicitConversion: true,
+ },
+ }),
+ );
+
+ await app.listen(3000);
+}
+
+// Create well-validated DTOs
+import {
+ IsString,
+ IsEmail,
+ IsInt,
+ Min,
+ Max,
+ IsOptional,
+ MinLength,
+ MaxLength,
+ Matches,
+ IsNotEmpty,
+} from 'class-validator';
+import { Transform, Type } from 'class-transformer';
+
+export class CreateUserDto {
+ @IsString()
+ @IsNotEmpty()
+ @MinLength(2)
+ @MaxLength(100)
+ @Transform(({ value }) => value?.trim())
+ name: string;
+
+ @IsEmail()
+ @Transform(({ value }) => value?.toLowerCase().trim())
+ email: string;
+
+ @IsInt()
+ @Min(0)
+ @Max(150)
+ age: number;
+
+ @IsString()
+ @MinLength(8)
+ @MaxLength(100)
+ @Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, {
+ message: 'Password must contain uppercase, lowercase, and number',
+ })
+ password: string;
+}
+
+// Query DTO with defaults and transformation
+export class FindUsersQueryDto {
+ @IsOptional()
+ @IsString()
+ @MaxLength(100)
+ search?: string;
+
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(1)
+ @Max(100)
+ limit: number = 20;
+
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ offset: number = 0;
+}
+
+// Param validation
+export class UserIdParamDto {
+ @IsUUID('4')
+ id: string;
+}
+
+@Controller('users')
+export class UsersController {
+ @Post()
+ create(@Body() dto: CreateUserDto): Promise<User> {
+ // dto is guaranteed to be valid
+ return this.usersService.create(dto);
+ }
+
+ @Get()
+ findAll(@Query() query: FindUsersQueryDto): Promise<User[]> {
+ // query.limit is a number, query.search is sanitized
+ return this.usersService.findAll(query);
+ }
+
+ @Get(':id')
+ findOne(@Param() params: UserIdParamDto): Promise<User> {
+ // params.id is a valid UUID
+ return this.usersService.findById(params.id);
+ }
+}
+```
+
+Reference: [NestJS Validation](https://docs.nestjs.com/techniques/validation)
diff --git a/.agents/skills/nestjs-best-practices/rules/test-e2e-supertest.md b/.agents/skills/nestjs-best-practices/rules/test-e2e-supertest.md
new file mode 100644
index 00000000..42655138
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/test-e2e-supertest.md
@@ -0,0 +1,178 @@
+---
+title: Use Supertest for E2E Testing
+impact: HIGH
+impactDescription: Validates the full request/response cycle
+tags: testing, e2e, supertest, integration
+---
+
+## Use Supertest for E2E Testing
+
+End-to-end tests use Supertest to make real HTTP requests against your NestJS application. They test the full stack including middleware, guards, pipes, and interceptors. E2E tests catch integration issues that unit tests miss.
+
+**Incorrect (no proper E2E setup or teardown):**
+
+```typescript
+// Only unit test controllers
+describe('UsersController', () => {
+ it('should return users', async () => {
+ const service = { findAll: jest.fn().mockResolvedValue([]) };
+ const controller = new UsersController(service as any);
+
+ const result = await controller.findAll();
+
+ expect(result).toEqual([]);
+ // Doesn't test: routes, guards, pipes, serialization
+ });
+});
+
+// E2E tests without proper setup/teardown
+describe('Users API', () => {
+ it('should create user', async () => {
+ const app = await NestFactory.create(AppModule);
+ // No proper initialization
+ // No cleanup after test
+ // Hits real database
+ });
+});
+```
+
+**Correct (proper E2E setup with Supertest):**
+
+```typescript
+// Proper E2E test setup
+import { Test, TestingModule } from '@nestjs/testing';
+import { INestApplication, ValidationPipe } from '@nestjs/common';
+import * as request from 'supertest';
+import { AppModule } from '../src/app.module';
+
+describe('UsersController (e2e)', () => {
+ let app: INestApplication;
+
+ beforeAll(async () => {
+ const moduleFixture: TestingModule = await Test.createTestingModule({
+ imports: [AppModule],
+ }).compile();
+
+ app = moduleFixture.createNestApplication();
+
+ // Apply same config as production
+ app.useGlobalPipes(
+ new ValidationPipe({
+ whitelist: true,
+ transform: true,
+ forbidNonWhitelisted: true,
+ }),
+ );
+
+ await app.init();
+ });
+
+ afterAll(async () => {
+ await app.close();
+ });
+
+ describe('/users (POST)', () => {
+ it('should create a user', () => {
+ return request(app.getHttpServer())
+ .post('/users')
+ .send({ name: 'John', email: '[email protected]' })
+ .expect(201)
+ .expect((res) => {
+ expect(res.body).toHaveProperty('id');
+ expect(res.body.name).toBe('John');
+ expect(res.body.email).toBe('[email protected]');
+ });
+ });
+
+ it('should return 400 for invalid email', () => {
+ return request(app.getHttpServer())
+ .post('/users')
+ .send({ name: 'John', email: 'invalid-email' })
+ .expect(400)
+ .expect((res) => {
+ expect(res.body.message).toContain('email');
+ });
+ });
+ });
+
+ describe('/users/:id (GET)', () => {
+ it('should return 404 for non-existent user', () => {
+ return request(app.getHttpServer())
+ .get('/users/non-existent-id')
+ .expect(404);
+ });
+ });
+});
+
+// Testing with authentication
+describe('Protected Routes (e2e)', () => {
+ let app: INestApplication;
+ let authToken: string;
+
+ beforeAll(async () => {
+ const moduleFixture = await Test.createTestingModule({
+ imports: [AppModule],
+ }).compile();
+
+ app = moduleFixture.createNestApplication();
+ app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
+ await app.init();
+
+ // Get auth token
+ const loginResponse = await request(app.getHttpServer())
+ .post('/auth/login')
+ .send({ email: '[email protected]', password: 'password' });
+
+ authToken = loginResponse.body.accessToken;
+ });
+
+ it('should return 401 without token', () => {
+ return request(app.getHttpServer())
+ .get('/users/me')
+ .expect(401);
+ });
+
+ it('should return user profile with valid token', () => {
+ return request(app.getHttpServer())
+ .get('/users/me')
+ .set('Authorization', `Bearer ${authToken}`)
+ .expect(200)
+ .expect((res) => {
+ expect(res.body.email).toBe('[email protected]');
+ });
+ });
+});
+
+// Database isolation for E2E tests
+describe('Orders API (e2e)', () => {
+ let app: INestApplication;
+ let dataSource: DataSource;
+
+ beforeAll(async () => {
+ const moduleFixture = await Test.createTestingModule({
+ imports: [
+ ConfigModule.forRoot({
+ envFilePath: '.env.test', // Test database config
+ }),
+ AppModule,
+ ],
+ }).compile();
+
+ app = moduleFixture.createNestApplication();
+ dataSource = moduleFixture.get(DataSource);
+ await app.init();
+ });
+
+ beforeEach(async () => {
+ // Clean database between tests
+ await dataSource.synchronize(true);
+ });
+
+ afterAll(async () => {
+ await dataSource.destroy();
+ await app.close();
+ });
+});
+```
+
+Reference: [NestJS E2E Testing](https://docs.nestjs.com/fundamentals/testing#end-to-end-testing)
diff --git a/.agents/skills/nestjs-best-practices/rules/test-mock-external-services.md b/.agents/skills/nestjs-best-practices/rules/test-mock-external-services.md
new file mode 100644
index 00000000..e29b595a
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/test-mock-external-services.md
@@ -0,0 +1,179 @@
+---
+title: Mock External Services in Tests
+impact: HIGH
+impactDescription: Ensures fast, reliable, deterministic tests
+tags: testing, mocking, external-services, jest
+---
+
+## Mock External Services in Tests
+
+Never call real external services (APIs, databases, message queues) in unit tests. Mock them to ensure tests are fast, deterministic, and don't incur costs. Use realistic mock data and test edge cases like timeouts and errors.
+
+**Incorrect (calling real APIs and databases):**
+
+```typescript
+// Call real APIs in tests
+describe('PaymentService', () => {
+ it('should process payment', async () => {
+ const service = new PaymentService(new StripeClient(realApiKey));
+ // Hits real Stripe API!
+ const result = await service.charge('tok_visa', 1000);
+ // Slow, costs money, flaky
+ });
+});
+
+// Use real database
+describe('UsersService', () => {
+ beforeEach(async () => {
+ await connection.query('DELETE FROM users'); // Modifies real DB
+ });
+
+ it('should create user', async () => {
+ const user = await service.create({ email: '[email protected]' });
+ // Side effects on shared database
+ });
+});
+
+// Incomplete mocks
+const mockHttpService = {
+ get: jest.fn().mockResolvedValue({ data: {} }),
+ // Missing error scenarios, missing other methods
+};
+```
+
+**Correct (mock all external dependencies):**
+
+```typescript
+// Mock HTTP service properly
+describe('WeatherService', () => {
+ let service: WeatherService;
+ let httpService: jest.Mocked<HttpService>;
+
+ beforeEach(async () => {
+ const module = await Test.createTestingModule({
+ providers: [
+ WeatherService,
+ {
+ provide: HttpService,
+ useValue: {
+ get: jest.fn(),
+ post: jest.fn(),
+ },
+ },
+ ],
+ }).compile();
+
+ service = module.get(WeatherService);
+ httpService = module.get(HttpService);
+ });
+
+ it('should return weather data', async () => {
+ const mockResponse = {
+ data: { temperature: 72, humidity: 45 },
+ status: 200,
+ statusText: 'OK',
+ headers: {},
+ config: {},
+ };
+
+ httpService.get.mockReturnValue(of(mockResponse));
+
+ const result = await service.getWeather('NYC');
+
+ expect(result).toEqual({ temperature: 72, humidity: 45 });
+ });
+
+ it('should handle API timeout', async () => {
+ httpService.get.mockReturnValue(
+ throwError(() => new Error('ETIMEDOUT')),
+ );
+
+ await expect(service.getWeather('NYC')).rejects.toThrow('Weather service unavailable');
+ });
+
+ it('should handle rate limiting', async () => {
+ httpService.get.mockReturnValue(
+ throwError(() => ({
+ response: { status: 429, data: { message: 'Rate limited' } },
+ })),
+ );
+
+ await expect(service.getWeather('NYC')).rejects.toThrow(TooManyRequestsException);
+ });
+});
+
+// Mock repository instead of database
+describe('UsersService', () => {
+ let service: UsersService;
+ let repo: jest.Mocked<Repository<User>>;
+
+ beforeEach(async () => {
+ const mockRepo = {
+ find: jest.fn(),
+ findOne: jest.fn(),
+ save: jest.fn(),
+ delete: jest.fn(),
+ createQueryBuilder: jest.fn(),
+ };
+
+ const module = await Test.createTestingModule({
+ providers: [
+ UsersService,
+ { provide: getRepositoryToken(User), useValue: mockRepo },
+ ],
+ }).compile();
+
+ service = module.get(UsersService);
+ repo = module.get(getRepositoryToken(User));
+ });
+
+ it('should find user by id', async () => {
+ const mockUser = { id: '1', name: 'John', email: '[email protected]' };
+ repo.findOne.mockResolvedValue(mockUser);
+
+ const result = await service.findById('1');
+
+ expect(result).toEqual(mockUser);
+ expect(repo.findOne).toHaveBeenCalledWith({ where: { id: '1' } });
+ });
+});
+
+// Create mock factory for complex SDKs
+function createMockStripe(): jest.Mocked<Stripe> {
+ return {
+ paymentIntents: {
+ create: jest.fn(),
+ retrieve: jest.fn(),
+ confirm: jest.fn(),
+ cancel: jest.fn(),
+ },
+ customers: {
+ create: jest.fn(),
+ retrieve: jest.fn(),
+ },
+ } as any;
+}
+
+// Mock time for time-dependent tests
+describe('TokenService', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ jest.setSystemTime(new Date('2024-01-15'));
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('should expire token after 1 hour', async () => {
+ const token = await service.createToken();
+
+ // Fast-forward time
+ jest.advanceTimersByTime(61 * 60 * 1000);
+
+ expect(await service.isValid(token)).toBe(false);
+ });
+});
+```
+
+Reference: [Jest Mocking](https://jestjs.io/docs/mock-functions)
diff --git a/.agents/skills/nestjs-best-practices/rules/test-use-testing-module.md b/.agents/skills/nestjs-best-practices/rules/test-use-testing-module.md
new file mode 100644
index 00000000..de256f57
--- /dev/null
+++ b/.agents/skills/nestjs-best-practices/rules/test-use-testing-module.md
@@ -0,0 +1,153 @@
+---
+title: Use Testing Module for Unit Tests
+impact: HIGH
+impactDescription: Enables proper isolated testing with mocked dependencies
+tags: testing, unit-tests, mocking, jest
+---
+
+## Use Testing Module for Unit Tests
+
+Use `@nestjs/testing` module to create isolated test environments with mocked dependencies. This ensures your tests run fast, don't depend on external services, and properly test your business logic in isolation.
+
+**Incorrect (manual instantiation bypassing DI):**
+
+```typescript
+// Instantiate services manually without DI
+describe('UsersService', () => {
+ it('should create user', async () => {
+ // Manual instantiation bypasses DI
+ const repo = new UserRepository(); // Real repo!
+ const service = new UsersService(repo);
+
+ const user = await service.create({ name: 'Test' });
+ // This hits the real database!
+ });
+});
+
+// Test implementation details
+describe('UsersController', () => {
+ it('should call service', async () => {
+ const service = { create: jest.fn() };
+ const controller = new UsersController(service as any);
+
+ await controller.create({ name: 'Test' });
+
+ expect(service.create).toHaveBeenCalled(); // Tests implementation, not behavior
+ });
+});
+```
+
+**Correct (use Test.createTestingModule with mocked dependencies):**
+
+```typescript
+// Use Test.createTestingModule for proper DI
+import { Test, TestingModule } from '@nestjs/testing';
+
+describe('UsersService', () => {
+ let service: UsersService;
+ let repo: jest.Mocked<UserRepository>;
+
+ beforeEach(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ UsersService,
+ {
+ provide: UserRepository,
+ useValue: {
+ save: jest.fn(),
+ findOne: jest.fn(),
+ find: jest.fn(),
+ },
+ },
+ ],
+ }).compile();
+
+ service = module.get<UsersService>(UsersService);
+ repo = module.get(UserRepository);
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('create', () => {
+ it('should save and return user', async () => {
+ const dto = { name: 'John', email: '[email protected]' };
+ const expectedUser = { id: '1', ...dto };
+
+ repo.save.mockResolvedValue(expectedUser);
+
+ const result = await service.create(dto);
+
+ expect(result).toEqual(expectedUser);
+ expect(repo.save).toHaveBeenCalledWith(dto);
+ });
+
+ it('should throw on duplicate email', async () => {
+ repo.findOne.mockResolvedValue({ id: '1', email: '[email protected]' });
+
+ await expect(
+ service.create({ name: 'Test', email: '[email protected]' }),
+ ).rejects.toThrow(ConflictException);
+ });
+ });
+
+ describe('findById', () => {
+ it('should return user when found', async () => {
+ const user = { id: '1', name: 'John' };
+ repo.findOne.mockResolvedValue(user);
+
+ const result = await service.findById('1');
+
+ expect(result).toEqual(user);
+ });
+
+ it('should throw NotFoundException when not found', async () => {
+ repo.findOne.mockResolvedValue(null);
+
+ await expect(service.findById('999')).rejects.toThrow(NotFoundException);
+ });
+ });
+});
+
+// Testing guards and interceptors
+describe('RolesGuard', () => {
+ let guard: RolesGuard;
+ let reflector: Reflector;
+
+ beforeEach(async () => {
+ const module = await Test.createTestingModule({
+ providers: [RolesGuard, Reflector],
+ }).compile();
+
+ guard = module.get<RolesGuard>(RolesGuard);
+ reflector = module.get<Reflector>(Reflector);
+ });
+
+ it('should allow when no roles required', () => {
+ const context = createMockExecutionContext({ user: { roles: [] } });
+ jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(undefined);
+
+ expect(guard.canActivate(context)).toBe(true);
+ });
+
+ it('should allow admin for admin-only route', () => {
+ const context = createMockExecutionContext({ user: { roles: ['admin'] } });
+ jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['admin']);
+
+ expect(guard.canActivate(context)).toBe(true);
+ });
+});
+
+function createMockExecutionContext(request: Partial<Request>): ExecutionContext {
+ return {
+ switchToHttp: () => ({
+ getRequest: () => request,
+ }),
+ getHandler: () => jest.fn(),
+ getClass: () => jest.fn(),
+ } as ExecutionContext;
+}
+```
+
+Reference: [NestJS Testing](https://docs.nestjs.com/fundamentals/testing)
diff --git a/.agents/skills/no-use-effect/SKILL.md b/.agents/skills/no-use-effect/SKILL.md
new file mode 100644
index 00000000..ffc16d08
--- /dev/null
+++ b/.agents/skills/no-use-effect/SKILL.md
@@ -0,0 +1,233 @@
+---
+name: no-use-effect
+description: >-
+ Enforce the no-useEffect rule when writing or reviewing React code.
+ ACTIVATE when writing React components, refactoring existing useEffect calls,
+ reviewing PRs with useEffect, or when an agent adds useEffect "just in case."
+ Provides the five replacement patterns and the useMountEffect escape hatch.
+---
+
+# No useEffect
+
+Never call `useEffect` directly. Use derived state, event handlers, data-fetching libraries, or `useMountEffect` instead.
+
+## Quick Reference
+
+- Lint rule: `no-restricted-syntax` (configured to ban `useEffect`)
+- React docs: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
+- Origin: [https://x.com/alvinsng/status/2033969062834045089](https://x.com/alvinsng/status/2033969062834045089)
+
+| Instead of useEffect for... | Use |
+| --- | --- |
+| Deriving state from other state/props | Inline computation (Rule 1) |
+| Fetching data | `useQuery` / data-fetching library (Rule 2) |
+| Responding to user actions | Event handlers (Rule 3) |
+| One-time external sync on mount | `useMountEffect` (Rule 4) |
+| Resetting state when a prop changes | `key` prop on parent (Rule 5) |
+
+## When to Use This Skill
+
+- Writing new React components
+- Refactoring existing `useEffect` calls
+- Reviewing PRs that introduce `useEffect`
+- An agent adds `useEffect` "just in case"
+
+## Workflow
+
+### 1. Identify the useEffect
+
+Determine what the effect is doing -- deriving state, fetching data, responding to an event, syncing with an external system, or resetting state.
+
+### 2. Apply the Correct Replacement Pattern
+
+Use the five rules below to pick the right replacement.
+
+### 3. Verify
+
+```
+npm run lint -- --filter=<package>
+npm run typecheck -- --filter=<package>
+npm run test -- --filter=<package>
+```
+
+## The Escape Hatch: useMountEffect
+
+For the rare case where you need to sync with an external system on mount:
+
+The implementation wraps `useEffect` with an empty dependency array to make intent explicit:
+
+```
+export function useMountEffect(effect: () => void | (() => void)) {
+ /* eslint-disable no-restricted-syntax */
+ useEffect(effect, []);
+}
+```
+
+## Replacement Patterns
+
+### Rule 1: Derive state, do not sync it
+
+Most effects that set state from other state are unnecessary and add extra renders.
+
+```
+// BAD: Two render cycles - first stale, then filtered
+function ProductList() {
+ const [products, setProducts] = useState([]);
+ const [filteredProducts, setFilteredProducts] = useState([]);
+
+ useEffect(() => {
+ setFilteredProducts(products.filter((p) => p.inStock));
+ }, [products]);
+}
+
+// GOOD: Compute inline in one render
+function ProductList() {
+ const [products, setProducts] = useState([]);
+ const filteredProducts = products.filter((p) => p.inStock);
+}
+```
+
+**Smell test:** You are about to write `useEffect(() => setX(deriveFromY(y)), [y])`, or you have state that only mirrors other state or props.
+
+### Rule 2: Use data-fetching libraries
+
+Effect-based fetching creates race conditions and duplicated caching logic.
+
+```
+// BAD: Race condition risk
+function ProductPage({ productId }) {
+ const [product, setProduct] = useState(null);
+
+ useEffect(() => {
+ fetchProduct(productId).then(setProduct);
+ }, [productId]);
+}
+
+// GOOD: Query library handles cancellation/caching/staleness
+function ProductPage({ productId }) {
+ const { data: product } = useQuery(['product', productId], () =>
+ fetchProduct(productId)
+ );
+}
+```
+
+**Smell test:** Your effect does `fetch(...)` and then `setState(...)`, or you are re-implementing caching, retries, cancellation, or stale handling.
+
+### Rule 3: Event handlers, not effects
+
+If a user clicks a button, do the work in the handler.
+
+```
+// BAD: Effect as an action relay
+function LikeButton() {
+ const [liked, setLiked] = useState(false);
+
+ useEffect(() => {
+ if (liked) {
+ postLike();
+ setLiked(false);
+ }
+ }, [liked]);
+
+ return <button onClick={() => setLiked(true)}>Like</button>;
+}
+
+// GOOD: Direct event-driven action
+function LikeButton() {
+ return <button onClick={() => postLike()}>Like</button>;
+}
+```
+
+**Smell test:** State is used as a flag so an effect can do the real action, or you are building "set flag -> effect runs -> reset flag" mechanics.
+
+### Rule 4: useMountEffect for one-time external sync
+
+Good uses: DOM integration (focus, scroll), third-party widget lifecycles, browser API subscriptions.
+
+```
+// BAD: Guard inside effect
+function VideoPlayer({ isLoading }) {
+ useEffect(() => {
+ if (!isLoading) playVideo();
+ }, [isLoading]);
+}
+
+// GOOD: Mount only when preconditions are met
+function VideoPlayerWrapper({ isLoading }) {
+ if (isLoading) return <LoadingScreen />;
+ return <VideoPlayer />;
+}
+
+function VideoPlayer() {
+ useMountEffect(() => playVideo());
+}
+```
+
+Use `useMountEffect` for stable dependencies (singletons, refs, context values that never change):
+
+```
+// BAD: useEffect with dependency that never changes
+useEffect(() => {
+ connectionManager.on('connected', handleConnect);
+ return () => connectionManager.off('connected', handleConnect);
+}, [connectionManager]); // connectionManager is a singleton from context
+
+// GOOD: useMountEffect for stable dependencies
+
+useMountEffect(() => {
+ connectionManager.on('connected', handleConnect);
+ return () => connectionManager.off('connected', handleConnect);
+});
+```
+
+**Smell test:** You are synchronizing with an external system, and the behavior is naturally "setup on mount, cleanup on unmount."
+
+### Rule 5: Reset with key, not dependency choreography
+
+```
+// BAD: Effect attempts to emulate remount behavior
+function VideoPlayer({ videoId }) {
+ useEffect(() => {
+ loadVideo(videoId);
+ }, [videoId]);
+}
+
+// GOOD: key forces clean remount
+function VideoPlayer({ videoId }) {
+ useMountEffect(() => {
+ loadVideo(videoId);
+ });
+}
+
+function VideoPlayerWrapper({ videoId }) {
+ return <VideoPlayer key={videoId} videoId={videoId} />;
+}
+```
+
+**Smell test:** You are writing an effect whose only job is to reset local state when an ID/prop changes, or you want the component to behave like a brand-new instance for each entity.
+
+## Component Structure Convention
+
+Computed values come after hooks and local state, never via `useEffect`:
+
+```
+export function FeatureComponent({ featureId }: ComponentProps) {
+ // Hooks first
+ const { data, isLoading } = useQueryFeature(featureId);
+
+ // Local state
+ const [isOpen, setIsOpen] = useState(false);
+
+ // Computed values (NOT useEffect + setState)
+ const displayName = user?.name ?? 'Unknown';
+
+ // Event handlers
+ const handleClick = () => { setIsOpen(true); };
+
+ // Early returns
+ if (isLoading) return <Loading />;
+
+ // Render
+ return <Flex direction="column" gap="lg">...</Flex>;
+}
+```
diff --git a/.agents/skills/nuqs/AGENTS.md b/.agents/skills/nuqs/AGENTS.md
new file mode 100644
index 00000000..47b055e9
--- /dev/null
+++ b/.agents/skills/nuqs/AGENTS.md
@@ -0,0 +1,88 @@
+# nuqs
+
+**Version 1.2.0**
+Community
+July 2026
+
+---
+
+## Abstract
+
+Comprehensive best practices guide for nuqs (type-safe URL query state management) in Next.js and other React frameworks, designed for AI agents and LLMs. Covers nuqs v2.5–v2.9 features including limitUrlUpdates (built-in debounce/throttle), key isolation, Standard Schema integration, defaultOptions on NuqsAdapter (with history added in v2.9), processUrlSearchParams middleware (adapter and createSerializer), the createLoader server utility, the React Router v8 adapter, and Next.js 16 cacheComponents compatibility. Contains 39 rules across 8 categories, prioritized by impact from critical (parser configuration, adapter setup) to incremental (advanced patterns). Each rule names the wrong default it corrects, with realistic examples and, where relevant, honest consequence-based impact notes to guide automated refactoring and code generation.
+
+---
+
+## Table of Contents
+
+1. [Parser Configuration](references/_sections.md#1-parser-configuration) — **CRITICAL**
+ - 1.1 [Choose Correct Array Parser Format](references/parser-array-format.md) — CRITICAL (prevents API integration failures from wrong URL format)
+ - 1.2 [Select Appropriate Date Parser](references/parser-date-format.md) — CRITICAL (prevents timezone bugs and parsing failures)
+ - 1.3 [Use Enum Parsers for Constrained Values](references/parser-enum-validation.md) — CRITICAL (prevents invalid state from URL manipulation)
+ - 1.4 [Use parseAsIndex for 1-Based URL Display](references/parser-index-offset.md) — HIGH (eliminates off-by-one errors between URL and code)
+ - 1.5 [Use Typed Parsers for Non-String Values](references/parser-use-typed-parsers.md) — CRITICAL (prevents runtime type errors and hydration mismatches)
+ - 1.6 [Use withDefault for Non-Nullable State](references/parser-with-default.md) — CRITICAL (eliminates null checks throughout component tree)
+ - 1.7 [Validate JSON Parser Input](references/parser-json-validation.md) — CRITICAL (prevents runtime crashes and unsafe casts from URL-supplied JSON)
+2. [Adapter & Setup](references/_sections.md#2-adapter-&-setup) — **CRITICAL**
+ - 2.1 [Add 'use client' Directive for Hooks](references/setup-use-client.md) — CRITICAL (prevents build-breaking hook errors in RSC)
+ - 2.2 [Configure App-Wide Defaults on NuqsAdapter](references/setup-default-options.md) — MEDIUM (avoids repeating .withOptions on every parser; enforces consistent behaviour)
+ - 2.3 [Define Shared Parsers in Dedicated File](references/setup-shared-parsers.md) — HIGH (prevents parser mismatch bugs between components)
+ - 2.4 [Ensure Compatible Next.js Version](references/setup-nextjs-version.md) — CRITICAL (prevents cryptic runtime errors from version mismatch)
+ - 2.5 [Import Server Utilities from nuqs/server](references/setup-import-server.md) — CRITICAL (prevents RSC-to-client boundary contamination errors)
+ - 2.6 [Wrap App with NuqsAdapter](references/setup-nuqs-adapter.md) — CRITICAL (prevents 100% of hook failures from missing provider)
+3. [State Management](references/_sections.md#3-state-management) — **HIGH**
+ - 3.1 [Avoid Derived State from URL Parameters](references/state-avoid-derived.md) — HIGH (prevents sync bugs and unnecessary re-renders)
+ - 3.2 [Clear URL Parameters with null](references/state-clear-with-null.md) — HIGH (reduces URL clutter by removing unnecessary parameters)
+ - 3.3 [Use Setter Return Value for URL Access](references/state-setter-return.md) — MEDIUM (enables accurate URL tracking for analytics/sharing without re-deriving the URL)
+ - 3.4 [Use Standard Schema for Cross-Library Validation](references/state-standard-schema.md) — MEDIUM (one parser map validates nuqs, tRPC, route validators, and forms — no duplicated schema)
+ - 3.5 [Use useQueryStates for Related Parameters](references/state-use-query-states.md) — HIGH (gives a single typed object and one combined URLSearchParams flush)
+ - 3.6 [Use withOptions for Parser-Level Configuration](references/state-options-inheritance.md) — MEDIUM (reduces boilerplate and ensures consistent behavior)
+4. [Server Integration](references/_sections.md#4-server-integration) — **HIGH**
+ - 4.1 [Call parse() Before get() in Server Components](references/server-parse-before-get.md) — HIGH (prevents undefined values and runtime errors)
+ - 4.2 [Handle Async searchParams in Next.js 15+](references/server-next15-async.md) — HIGH (prevents build errors in Next.js 15 with async props)
+ - 4.3 [Integrate useTransition for Loading States](references/server-use-transition.md) — HIGH (exposes pending state for non-shallow server fetches so the UI can show loading)
+ - 4.4 [Use createSearchParamsCache for Server Components](references/server-search-params-cache.md) — HIGH (eliminates prop drilling across N component levels)
+ - 4.5 [Use shallow:false to Trigger Server Re-renders](references/server-shallow-false.md) — HIGH (enables server-side data refetching on URL change)
+5. [Performance Optimization](references/_sections.md#5-performance-optimization) — **MEDIUM**
+ - 5.1 [Debounce Search Input Before URL Update](references/perf-debounce-search.md) — HIGH (reduces server requests during typing from N per keystroke to 1 per pause)
+ - 5.2 [Memoize Components Using URL State](references/perf-avoid-rerender.md) — MEDIUM (prevents unnecessary re-renders on URL changes (Next.js especially))
+ - 5.3 [Rely on Key Isolation Outside Next.js](references/perf-key-isolation.md) — HIGH (avoids unnecessary memoization on adapters that already scope re-renders per key)
+ - 5.4 [Throttle Rapid URL Updates](references/perf-throttle-updates.md) — MEDIUM (prevents browser history API rate limiting on rapid input)
+ - 5.5 [Use clearOnDefault for Clean URLs](references/perf-clear-on-default.md) — MEDIUM (reduces URL length by 20-50% for default values)
+ - 5.6 [Use createSerializer for Link URLs](references/perf-serialize-utility.md) — MEDIUM (enables SSR-compatible URL generation without hooks)
+6. [History & Navigation](references/_sections.md#6-history-&-navigation) — **MEDIUM**
+ - 6.1 [Choose the Right history Mode (push vs replace)](references/history-push-navigation.md) — MEDIUM (back button behaves as users expect for navigation vs ephemeral state)
+ - 6.2 [Control Scroll Behavior on URL Changes](references/history-scroll-behavior.md) — MEDIUM (prevents jarring scroll jumps on state changes)
+7. [Debugging & Testing](references/_sections.md#7-debugging-&-testing) — **LOW-MEDIUM**
+ - 7.1 [Enable Debug Logging for Troubleshooting](references/debug-enable-logging.md) — LOW-MEDIUM (surfaces the exact parse/serialize/URL-write step instead of guessing from silent state)
+ - 7.2 [Test Components with URL State](references/debug-testing.md) — LOW-MEDIUM (enables reliable CI/CD testing of nuqs components)
+8. [Advanced Patterns](references/_sections.md#8-advanced-patterns) — **LOW**
+ - 8.1 [Create Custom Parsers for Complex Types](references/advanced-custom-parsers.md) — LOW (prevents runtime errors from string coercion)
+ - 8.2 [Implement eq Function for Object Parsers](references/advanced-eq-function.md) — LOW (prevents unnecessary URL updates for equivalent objects)
+ - 8.3 [Use Framework-Specific Adapters](references/advanced-framework-adapters.md) — LOW (prevents URL sync failures in non-Next.js apps)
+ - 8.4 [Use processUrlSearchParams for Canonical URL Shape](references/advanced-process-url-search-params.md) — LOW-MEDIUM (enables stable URL ordering for SEO and cache hit-rate)
+ - 8.5 [Use urlKeys for Shorter URLs](references/advanced-url-keys.md) — LOW (keeps shareable links compact by shortening verbose URL keys)
+
+---
+
+## References
+
+1. [https://nuqs.dev](https://nuqs.dev)
+2. [https://nuqs.dev/blog/nuqs-2.5](https://nuqs.dev/blog/nuqs-2.5)
+3. [https://github.com/47ng/nuqs/releases/tag/v2.9.0](https://github.com/47ng/nuqs/releases/tag/v2.9.0)
+4. [https://github.com/47ng/nuqs](https://github.com/47ng/nuqs)
+5. [https://nextjs.org/docs](https://nextjs.org/docs)
+6. [https://react.dev](https://react.dev)
+7. [https://standardschema.dev](https://standardschema.dev)
+
+---
+
+## Source Files
+
+This document was compiled from individual reference files. For detailed editing or extension:
+
+| File | Description |
+|------|-------------|
+| [references/_sections.md](references/_sections.md) | Category definitions and ordering |
+| [assets/templates/_template.md](assets/templates/_template.md) | Template for creating new rules |
+| [SKILL.md](SKILL.md) | Quick reference entry point |
+| [metadata.json](metadata.json) | Version and reference URLs |
\ No newline at end of file
diff --git a/.agents/skills/nuqs/README.md b/.agents/skills/nuqs/README.md
new file mode 100644
index 00000000..9fc1a088
--- /dev/null
+++ b/.agents/skills/nuqs/README.md
@@ -0,0 +1,104 @@
+# nuqs Best Practices for Next.js
+
+A comprehensive best practices skill for using [nuqs](https://nuqs.dev) - type-safe URL query state management - in Next.js applications.
+
+## Overview
+
+This skill provides 42 rules across 8 categories to help AI agents and developers write correct, performant, and maintainable code when using nuqs for URL state management.
+
+## Getting Started
+
+```bash
+# Install dependencies (if any)
+pnpm install
+
+# Build AGENTS.md from references
+pnpm build
+
+# Validate the skill
+pnpm validate
+```
+
+## Categories
+
+| Priority | Category | Impact | Rules |
+|----------|----------|--------|-------|
+| 1 | Parser Configuration | CRITICAL | 8 |
+| 2 | Adapter & Setup | CRITICAL | 5 |
+| 3 | State Management | HIGH | 7 |
+| 4 | Server Integration | HIGH | 6 |
+| 5 | Performance Optimization | MEDIUM | 5 |
+| 6 | History & Navigation | MEDIUM | 4 |
+| 7 | Debugging & Testing | LOW-MEDIUM | 3 |
+| 8 | Advanced Patterns | LOW | 4 |
+
+## Creating a New Rule
+
+1. Create a new file in `references/` with the pattern `{prefix}-{slug}.md`
+2. Use the template from `assets/templates/_template.md`
+3. Include YAML frontmatter with `title`, `impact`, `impactDescription`, `tags`
+4. Add **Incorrect** and **Correct** code examples
+5. Run `pnpm build` to regenerate AGENTS.md
+6. Run `pnpm validate` to check for errors
+
+## Rule File Structure
+
+```markdown
+---
+title: Rule Title
+impact: CRITICAL|HIGH|MEDIUM|LOW
+impactDescription: Quantified impact (e.g., "2-10× improvement")
+tags: prefix, keyword1, keyword2
+---
+
+## Rule Title
+
+Explanation of WHY this matters.
+
+**Incorrect (annotation):**
+\`\`\`tsx
+// Bad code example
+\`\`\`
+
+**Correct (annotation):**
+\`\`\`tsx
+// Good code example
+\`\`\`
+
+Reference: [Link](url)
+```
+
+## File Naming Convention
+
+- Rule files: `{prefix}-{descriptive-slug}.md` (e.g., `parser-use-typed-parsers.md`)
+- Prefix must match a section defined in `references/_sections.md`
+- Use lowercase with hyphens
+
+## Impact Levels
+
+| Level | Description |
+|-------|-------------|
+| CRITICAL | Causes build failures, runtime errors, or major performance issues |
+| HIGH | Significant bugs, performance degradation, or maintenance problems |
+| MEDIUM | Noticeable issues or suboptimal patterns |
+| LOW-MEDIUM | Minor improvements or edge case handling |
+| LOW | Nice-to-have optimizations or advanced patterns |
+
+## Scripts
+
+- `pnpm build` - Regenerate AGENTS.md from references
+- `pnpm validate` - Check skill against quality guidelines
+
+## Contributing
+
+1. Check existing rules to avoid duplication
+2. Follow the rule template structure
+3. Include production-realistic code examples
+4. Quantify impact where possible
+5. Run validation before submitting
+
+## References
+
+- [nuqs Documentation](https://nuqs.dev)
+- [nuqs GitHub](https://github.com/47ng/nuqs)
+- [Next.js Documentation](https://nextjs.org/docs)
diff --git a/.agents/skills/nuqs/SKILL.md b/.agents/skills/nuqs/SKILL.md
new file mode 100644
index 00000000..40668ccd
--- /dev/null
+++ b/.agents/skills/nuqs/SKILL.md
@@ -0,0 +1,113 @@
+---
+name: nuqs
+description: nuqs (type-safe URL query state) best practices for Next.js and other React frameworks. This skill should be used when writing, reviewing, or refactoring code that uses nuqs for URL state management. Triggers on tasks involving useQueryState, useQueryStates, search params, URL state, query parameters, nuqs parsers, limitUrlUpdates, Standard Schema, NuqsAdapter, or Next.js routing with state.
+---
+
+# Community nuqs Best Practices for Next.js & React
+
+Comprehensive guide for type-safe URL query state management with nuqs across Next.js, React Router, TanStack Router, Remix, and plain React. Covers nuqs v2.5–v2.9 features. Contains 39 rules across 8 categories, prioritized by impact to guide code generation, refactoring, and code review.
+
+## When to Apply
+
+Reference these guidelines when:
+- Implementing URL-based state with nuqs
+- Setting up nuqs in a Next.js or React Router project
+- Configuring parsers for URL parameters
+- Integrating URL state with Server Components
+- Optimizing URL update performance (`limitUrlUpdates`, key isolation)
+- Sharing parser definitions with tRPC / TanStack Router / forms via Standard Schema
+- Debugging nuqs-related issues
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Parser Configuration | CRITICAL | `parser-` |
+| 2 | Adapter & Setup | CRITICAL | `setup-` |
+| 3 | State Management | HIGH | `state-` |
+| 4 | Server Integration | HIGH | `server-` |
+| 5 | Performance Optimization | MEDIUM | `perf-` |
+| 6 | History & Navigation | MEDIUM | `history-` |
+| 7 | Debugging & Testing | LOW-MEDIUM | `debug-` |
+| 8 | Advanced Patterns | LOW | `advanced-` |
+
+## Quick Reference
+
+### 1. Parser Configuration (CRITICAL)
+
+- [`parser-use-typed-parsers`](references/parser-use-typed-parsers.md) — Use typed parsers for non-string values
+- [`parser-with-default`](references/parser-with-default.md) — Use withDefault for non-nullable state
+- [`parser-enum-validation`](references/parser-enum-validation.md) — Use enum parsers for constrained values
+- [`parser-array-format`](references/parser-array-format.md) — Choose correct array parser format
+- [`parser-json-validation`](references/parser-json-validation.md) — Validate JSON parser input
+- [`parser-date-format`](references/parser-date-format.md) — Select appropriate date parser
+- [`parser-index-offset`](references/parser-index-offset.md) — Use parseAsIndex for 1-based URL display
+
+### 2. Adapter & Setup (CRITICAL)
+
+- [`setup-nuqs-adapter`](references/setup-nuqs-adapter.md) — Wrap app with NuqsAdapter
+- [`setup-use-client`](references/setup-use-client.md) — Add 'use client' directive for hooks
+- [`setup-import-server`](references/setup-import-server.md) — Import server utilities from nuqs/server
+- [`setup-nextjs-version`](references/setup-nextjs-version.md) — Ensure compatible Next.js version
+- [`setup-shared-parsers`](references/setup-shared-parsers.md) — Define shared parsers in dedicated file
+- [`setup-default-options`](references/setup-default-options.md) — Configure app-wide defaults on NuqsAdapter (v2.5+)
+
+### 3. State Management (HIGH)
+
+- [`state-use-query-states`](references/state-use-query-states.md) — Use useQueryStates for related parameters
+- [`state-clear-with-null`](references/state-clear-with-null.md) — Clear URL parameters with null
+- [`state-avoid-derived`](references/state-avoid-derived.md) — Avoid derived state from URL parameters
+- [`state-options-inheritance`](references/state-options-inheritance.md) — Use withOptions for parser-level configuration
+- [`state-setter-return`](references/state-setter-return.md) — Use setter return value for URL access
+- [`state-standard-schema`](references/state-standard-schema.md) — Use Standard Schema for cross-library validation (v2.5+)
+
+### 4. Server Integration (HIGH)
+
+- [`server-search-params-cache`](references/server-search-params-cache.md) — Use createSearchParamsCache (or createLoader) for Server Components
+- [`server-shallow-false`](references/server-shallow-false.md) — Use shallow:false to trigger server re-renders
+- [`server-use-transition`](references/server-use-transition.md) — Integrate useTransition for loading states
+- [`server-parse-before-get`](references/server-parse-before-get.md) — Call parse() before get() in Server Components
+- [`server-next15-async`](references/server-next15-async.md) — Handle async searchParams in Next.js 15+
+
+### 5. Performance Optimization (MEDIUM)
+
+- [`perf-throttle-updates`](references/perf-throttle-updates.md) — Throttle rapid URL updates with `limitUrlUpdates`
+- [`perf-debounce-search`](references/perf-debounce-search.md) — Debounce search input with built-in `limitUrlUpdates`
+- [`perf-clear-on-default`](references/perf-clear-on-default.md) — Use clearOnDefault for clean URLs
+- [`perf-avoid-rerender`](references/perf-avoid-rerender.md) — Memoize components using URL state (Next.js)
+- [`perf-key-isolation`](references/perf-key-isolation.md) — Rely on key isolation outside Next.js (v2.5+)
+- [`perf-serialize-utility`](references/perf-serialize-utility.md) — Use createSerializer for link URLs
+
+### 6. History & Navigation (MEDIUM)
+
+- [`history-push-navigation`](references/history-push-navigation.md) — Choose history:push vs history:replace
+- [`history-scroll-behavior`](references/history-scroll-behavior.md) — Control scroll behavior on URL changes
+
+### 7. Debugging & Testing (LOW-MEDIUM)
+
+- [`debug-enable-logging`](references/debug-enable-logging.md) — Enable debug logging for troubleshooting
+- [`debug-testing`](references/debug-testing.md) — Test components with URL state
+
+### 8. Advanced Patterns (LOW)
+
+- [`advanced-custom-parsers`](references/advanced-custom-parsers.md) — Create custom parsers for complex types
+- [`advanced-url-keys`](references/advanced-url-keys.md) — Use urlKeys for shorter URLs
+- [`advanced-eq-function`](references/advanced-eq-function.md) — Implement eq function for object parsers
+- [`advanced-framework-adapters`](references/advanced-framework-adapters.md) — Use framework-specific adapters
+- [`advanced-process-url-search-params`](references/advanced-process-url-search-params.md) — Canonicalize URL shape with `processUrlSearchParams` (v2.6+)
+
+## How to Use
+
+Read individual reference files for detailed explanations and code examples:
+
+- [Section definitions](references/_sections.md) — Category structure and impact levels
+- [Rule template](assets/templates/_template.md) — Template for adding new rules
+
+## Reference Files
+
+| File | Description |
+|------|-------------|
+| [AGENTS.md](AGENTS.md) | Complete compiled guide with all rules |
+| [references/_sections.md](references/_sections.md) | Category definitions and ordering |
+| [assets/templates/_template.md](assets/templates/_template.md) | Template for new rules |
+| [metadata.json](metadata.json) | Version and reference information |
diff --git a/.agents/skills/nuqs/assets/templates/_template.md b/.agents/skills/nuqs/assets/templates/_template.md
new file mode 100644
index 00000000..cb64d9f0
--- /dev/null
+++ b/.agents/skills/nuqs/assets/templates/_template.md
@@ -0,0 +1,42 @@
+---
+title: {Rule Title}
+impact: {CRITICAL|HIGH|MEDIUM-HIGH|MEDIUM|LOW-MEDIUM|LOW}
+impactDescription: {Quantified impact, e.g., "2-10× improvement", "200ms savings"}
+tags: {prefix}, {technique}, {tool-if-mentioned}, {related-concepts}
+---
+
+## {Rule Title}
+
+{1-3 sentences explaining WHY this matters. Focus on performance/correctness implications.}
+
+**Incorrect ({what's wrong}):**
+
+```tsx
+{Bad code example - production-realistic, not strawman}
+{// Comments explaining the cost}
+```
+
+**Correct ({what's right}):**
+
+```tsx
+{Good code example - minimal diff from incorrect}
+{// Comments explaining the benefit}
+```
+
+{Optional sections as needed:}
+
+**Alternative ({context}):**
+
+```tsx
+{Alternative approach when applicable}
+```
+
+**When NOT to use this pattern:**
+- {Exception 1}
+- {Exception 2}
+
+**Benefits:**
+- {Benefit 1}
+- {Benefit 2}
+
+Reference: [{Reference Title}]({Reference URL})
diff --git a/.agents/skills/nuqs/references/_sections.md b/.agents/skills/nuqs/references/_sections.md
new file mode 100644
index 00000000..7813b960
--- /dev/null
+++ b/.agents/skills/nuqs/references/_sections.md
@@ -0,0 +1,46 @@
+# Sections
+
+This file defines all sections, their ordering, impact levels, and descriptions.
+The section ID (in parentheses) is the filename prefix used to group rules.
+
+---
+
+## 1. Parser Configuration (parser)
+
+**Impact:** CRITICAL
+**Description:** Incorrect parsers cause type mismatches, runtime errors, and hydration failures. Parser selection cascades through the entire state lifecycle.
+
+## 2. Adapter & Setup (setup)
+
+**Impact:** CRITICAL
+**Description:** Missing NuqsAdapter or incorrect setup causes hooks to fail silently or throw. Foundation for all nuqs functionality.
+
+## 3. State Management (state)
+
+**Impact:** HIGH
+**Description:** Proper use of useQueryState vs useQueryStates, default values, and null handling prevents unnecessary complexity and bugs.
+
+## 4. Server Integration (server)
+
+**Impact:** HIGH
+**Description:** Server cache and shallow routing configuration determines whether state changes trigger expensive server re-renders.
+
+## 5. Performance Optimization (perf)
+
+**Impact:** MEDIUM
+**Description:** Throttling, batching, and update coalescing prevent browser rate-limiting and reduce unnecessary URL updates.
+
+## 6. History & Navigation (history)
+
+**Impact:** MEDIUM
+**Description:** History mode selection affects UX - push vs replace impacts back button behavior and navigation experience.
+
+## 7. Debugging & Testing (debug)
+
+**Impact:** LOW-MEDIUM
+**Description:** Debug logging, testing strategies, and common error diagnosis enable faster development cycles.
+
+## 8. Advanced Patterns (advanced)
+
+**Impact:** LOW
+**Description:** Custom parsers, serializers, URL key mapping for complex use cases requiring careful implementation.
diff --git a/.agents/skills/nuqs/references/advanced-custom-parsers.md b/.agents/skills/nuqs/references/advanced-custom-parsers.md
new file mode 100644
index 00000000..03460cbc
--- /dev/null
+++ b/.agents/skills/nuqs/references/advanced-custom-parsers.md
@@ -0,0 +1,97 @@
+---
+title: Create Custom Parsers for Complex Types
+impact: LOW
+impactDescription: prevents runtime errors from string coercion
+tags: advanced, createParser, custom, serialize, parse
+---
+
+## Create Custom Parsers for Complex Types
+
+When built-in parsers don't fit your needs, create custom parsers with `createParser`. Define `parse`, `serialize`, and optionally `eq` for equality checking.
+
+**Incorrect (manual parsing in component):**
+
+```tsx
+'use client'
+import { useQueryState } from 'nuqs'
+
+interface SortState {
+ id: string
+ desc: boolean
+}
+
+export default function SortableTable() {
+ const [sortRaw, setSortRaw] = useQueryState('sort')
+ // Manual parsing scattered across component
+ const sort: SortState = sortRaw
+ ? { id: sortRaw.split(':')[0], desc: sortRaw.split(':')[1] === 'desc' }
+ : { id: 'name', desc: false }
+
+ const handleSort = (id: string) => {
+ // Manual serialization
+ setSortRaw(`${id}:${sort.id === id && !sort.desc ? 'desc' : 'asc'}`)
+ }
+}
+```
+
+**Correct (custom parser):**
+
+```tsx
+'use client'
+import { useQueryState, createParser } from 'nuqs'
+
+interface SortState {
+ id: string
+ desc: boolean
+}
+
+const parseAsSort = createParser<SortState>({
+ parse(query) {
+ const [id = '', direction = ''] = query.split(':')
+ return { id, desc: direction === 'desc' }
+ },
+ serialize(value) {
+ return `${value.id}:${value.desc ? 'desc' : 'asc'}`
+ },
+ eq(a, b) {
+ return a.id === b.id && a.desc === b.desc
+ }
+})
+
+export default function SortableTable() {
+ const [sort, setSort] = useQueryState(
+ 'sort',
+ parseAsSort.withDefault({ id: 'name', desc: false })
+ )
+ // Type-safe, reusable, with proper equality checking
+}
+```
+
+**Typing parser-returning helpers (v2.7+):**
+
+If you write a function that returns a custom parser (e.g. for a factory), type the return as `SingleParserBuilder<T>`. The older `ParserBuilder<T>` symbol is deprecated and will be removed in v3.
+
+```tsx
+import { createParser, type SingleParserBuilder } from 'nuqs'
+
+export function parseAsTuple<A, B>(
+ a: SingleParserBuilder<A>,
+ b: SingleParserBuilder<B>
+): SingleParserBuilder<[A, B]> {
+ return createParser<[A, B]>({
+ parse(query) {
+ const [left, right] = query.split('|')
+ const A = a.parse(left ?? '')
+ const B = b.parse(right ?? '')
+ return A === null || B === null ? null : [A, B]
+ },
+ serialize([A, B]) {
+ return `${a.serialize(A)}|${b.serialize(B)}`
+ }
+ })
+}
+```
+
+**For object/JSON-shaped values:** prefer `parseAsJson` with a Standard Schema (Zod, Valibot, ArkType, Effect Schema) over a hand-rolled `createParser` — see `parser-json-validation` and `state-standard-schema`.
+
+Reference: [nuqs Custom Parsers](https://nuqs.dev/docs/parsers/making-your-own)
diff --git a/.agents/skills/nuqs/references/advanced-eq-function.md b/.agents/skills/nuqs/references/advanced-eq-function.md
new file mode 100644
index 00000000..670d0d5f
--- /dev/null
+++ b/.agents/skills/nuqs/references/advanced-eq-function.md
@@ -0,0 +1,94 @@
+---
+title: Implement eq Function for Object Parsers
+impact: LOW
+impactDescription: prevents unnecessary URL updates for equivalent objects
+tags: advanced, eq, equality, objects, optimization
+---
+
+## Implement eq Function for Object Parsers
+
+When creating custom parsers for objects, implement the `eq` function to define equality. Without it, nuqs uses reference equality, causing unnecessary URL updates for equivalent but different object instances.
+
+**Incorrect (reference equality):**
+
+```tsx
+import { createParser } from 'nuqs'
+
+interface Filters {
+ minPrice: number
+ maxPrice: number
+}
+
+const parseAsFilters = createParser<Filters>({
+ parse(query) {
+ const [min, max] = query.split('-').map(Number)
+ return { minPrice: min, maxPrice: max }
+ },
+ serialize({ minPrice, maxPrice }) {
+ return `${minPrice}-${maxPrice}`
+ }
+ // Missing eq - uses reference equality
+})
+
+// Problem: setting same values creates new object references
+setFilters({ minPrice: 0, maxPrice: 100 })
+setFilters({ minPrice: 0, maxPrice: 100 }) // Triggers URL update even though values are same
+```
+
+**Correct (value equality):**
+
+```tsx
+import { createParser } from 'nuqs'
+
+interface Filters {
+ minPrice: number
+ maxPrice: number
+}
+
+const parseAsFilters = createParser<Filters>({
+ parse(query) {
+ const [min, max] = query.split('-').map(Number)
+ return { minPrice: min, maxPrice: max }
+ },
+ serialize({ minPrice, maxPrice }) {
+ return `${minPrice}-${maxPrice}`
+ },
+ eq(a, b) {
+ return a.minPrice === b.minPrice && a.maxPrice === b.maxPrice
+ }
+})
+
+// Now same values don't trigger unnecessary updates
+setFilters({ minPrice: 0, maxPrice: 100 })
+setFilters({ minPrice: 0, maxPrice: 100 }) // No URL update - values are equal
+```
+
+**For arrays:**
+
+```tsx
+const parseAsIdList = createParser<number[]>({
+ parse(query) {
+ return query.split(',').map(Number)
+ },
+ serialize(value) {
+ return value.join(',')
+ },
+ eq(a, b) {
+ return a.length === b.length && a.every((v, i) => v === b[i])
+ }
+})
+```
+
+**For nested objects:**
+
+```tsx
+import isEqual from 'lodash/isEqual' // or deep-equal
+
+const parseAsConfig = createParser<Config>({
+ parse: JSON.parse,
+ serialize: JSON.stringify,
+ eq: isEqual // Deep equality comparison
+})
+```
+
+Reference: [nuqs Custom Parsers](https://nuqs.dev/docs/parsers/making-your-own)
diff --git a/.agents/skills/nuqs/references/advanced-framework-adapters.md b/.agents/skills/nuqs/references/advanced-framework-adapters.md
new file mode 100644
index 00000000..7713f398
--- /dev/null
+++ b/.agents/skills/nuqs/references/advanced-framework-adapters.md
@@ -0,0 +1,67 @@
+---
+title: Use Framework-Specific Adapters
+impact: LOW
+impactDescription: prevents URL sync failures in non-Next.js apps
+tags: advanced, adapters, remix, react-router, tanstack-router, frameworks
+---
+
+## Use Framework-Specific Adapters
+
+nuqs works with multiple React frameworks through adapters. Use the correct adapter for your framework to ensure proper URL synchronisation. Picking the wrong adapter usually fails silently — hooks return stale values or never update the URL.
+
+**Incorrect (Next.js adapter inside a React Router tree):**
+
+```tsx
+// src/main.tsx
+import { NuqsAdapter } from 'nuqs/adapters/next/app' // Wrong runtime
+import { BrowserRouter } from 'react-router-dom'
+
+function App() {
+ return (
+ <BrowserRouter>
+ <NuqsAdapter>
+ <Routes />
+ </NuqsAdapter>
+ </BrowserRouter>
+ )
+}
+```
+
+**Correct (React Router v6 adapter):**
+
+```tsx
+// src/main.tsx
+import { NuqsAdapter } from 'nuqs/adapters/react-router/v6'
+import { BrowserRouter } from 'react-router-dom'
+
+function App() {
+ return (
+ <BrowserRouter>
+ <NuqsAdapter>
+ <Routes />
+ </NuqsAdapter>
+ </BrowserRouter>
+ )
+}
+```
+
+**Available adapters (current as of nuqs v2.9):**
+
+| Framework | Import Path | Notes |
+|-----------|-------------|-------|
+| Next.js App Router | `nuqs/adapters/next/app` | |
+| Next.js Pages Router | `nuqs/adapters/next/pages` | |
+| Next.js (unified) | `nuqs/adapters/next` | Use when an app mixes both routers |
+| React Router v6 | `nuqs/adapters/react-router/v6` | |
+| React Router v7 | `nuqs/adapters/react-router/v7` | |
+| React Router v8 | `nuqs/adapters/react-router/v8` | Added in v2.9 |
+| Remix | `nuqs/adapters/remix` | |
+| TanStack Router | `nuqs/adapters/tanstack-router` | Added in v2.5 |
+| Plain React (no router) | `nuqs/adapters/react` | For Vite / CRA apps with no router |
+| Testing | `nuqs/adapters/testing` | See `debug-testing` |
+
+**Deprecation:** The dedicated `react-router/v5` subpath was removed in v2.9 (v5 apps use the unversioned alias or upgrade). The unversioned `nuqs/adapters/react-router` import (which still aliases v6) is itself deprecated and slated for removal in nuqs v3 — always pin `/v6`, `/v7`, or `/v8` explicitly.
+
+**Key isolation (v2.5+):** All non-Next.js adapters scope re-renders to the specific URL key a hook subscribes to. Next.js continues to re-render the entire subtree on any URL change because its `URLSearchParams` context is global. If fine-grained re-renders matter and you're not on Next.js, you generally don't need to memoize aggressively. See `perf-avoid-rerender`.
+
+Reference: [nuqs Adapters](https://nuqs.dev/docs/adapters)
diff --git a/.agents/skills/nuqs/references/advanced-process-url-search-params.md b/.agents/skills/nuqs/references/advanced-process-url-search-params.md
new file mode 100644
index 00000000..2ce2122e
--- /dev/null
+++ b/.agents/skills/nuqs/references/advanced-process-url-search-params.md
@@ -0,0 +1,87 @@
+---
+title: Use processUrlSearchParams for Canonical URL Shape
+impact: LOW-MEDIUM
+impactDescription: enables stable URL ordering for SEO and cache hit-rate
+tags: advanced, processUrlSearchParams, seo, canonical-url, createSerializer
+---
+
+## Use processUrlSearchParams for Canonical URL Shape
+
+nuqs v2.6 added `processUrlSearchParams`, a middleware that transforms the `URLSearchParams` object **just before** it is written to the URL (when passed as an `NuqsAdapter` prop) or **just before** the URL is serialised (when passed to `createSerializer`). The most common use is to canonicalise key ordering — without it, `?b=2&a=1` and `?a=1&b=2` are two different cache keys for the same logical query, hurting SEO and CDN hit-rate.
+
+**Incorrect (key order leaks from React render order):**
+
+```tsx
+// User toggles filters in different orders → different URLs for the same query
+// /search?tag=react&sort=desc
+// /search?sort=desc&tag=react
+// Both render the same results, but each is a distinct canonical URL for Google.
+```
+
+**Correct (sort keys via adapter middleware):**
+
+```tsx
+// app/layout.tsx
+import { NuqsAdapter } from 'nuqs/adapters/next/app'
+
+export default function RootLayout({ children }: { children: React.ReactNode }) {
+ return (
+ <html>
+ <body>
+ <NuqsAdapter
+ processUrlSearchParams={(params) => {
+ // Sort keys alphabetically before each write
+ params.sort()
+ return params
+ }}
+ >
+ {children}
+ </NuqsAdapter>
+ </body>
+ </html>
+ )
+}
+```
+
+**For SEO canonical URLs in `generateMetadata` — same hook on `createSerializer`:**
+
+```tsx
+// lib/searchParams.ts
+import { createSerializer, parseAsString, parseAsInteger } from 'nuqs/server'
+
+export const searchParamsMap = {
+ q: parseAsString.withDefault(''),
+ page: parseAsInteger.withDefault(1)
+}
+
+export const serializeSearch = createSerializer(searchParamsMap, {
+ processUrlSearchParams(params) {
+ params.sort()
+ return params
+ }
+})
+
+// app/search/page.tsx
+import type { Metadata } from 'next'
+import { serializeSearch } from '@/lib/searchParams'
+
+export async function generateMetadata({ searchParams }): Promise<Metadata> {
+ const params = await searchParams
+ return {
+ alternates: {
+ canonical: serializeSearch('/search', params)
+ }
+ }
+}
+```
+
+**Other uses:**
+- Stripping internal tracking params (`utm_*`) before write.
+- Coercing booleans to a stable string form (`true` vs. `1`).
+- Removing empty values that didn't get caught by `clearOnDefault` for legacy reasons.
+
+**When NOT to use this pattern:**
+- Single-page app with no SEO concerns — the indirection costs more than the wobble.
+- You need to drop keys that affect server-side parsing — strip them on the server (in `createSearchParamsCache`/`createLoader`) instead, where the parser map is the source of truth.
+
+Reference: [nuqs Options](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/advanced-url-keys.md b/.agents/skills/nuqs/references/advanced-url-keys.md
new file mode 100644
index 00000000..49c1128d
--- /dev/null
+++ b/.agents/skills/nuqs/references/advanced-url-keys.md
@@ -0,0 +1,62 @@
+---
+title: Use urlKeys for Shorter URLs
+impact: LOW
+impactDescription: keeps shareable links compact by shortening verbose URL keys
+tags: advanced, urlKeys, serializer, url-length, abbreviation
+---
+
+## Use urlKeys for Shorter URLs
+
+Map verbose parameter names to shorter URL keys for cleaner, more shareable URLs while keeping descriptive names in code.
+
+**Incorrect (verbose URL parameters):**
+
+```tsx
+'use client'
+import { useQueryStates, parseAsFloat, parseAsInteger } from 'nuqs'
+
+export default function MapView() {
+ const [coords, setCoords] = useQueryStates({
+ latitude: parseAsFloat.withDefault(0),
+ longitude: parseAsFloat.withDefault(0),
+ zoomLevel: parseAsInteger.withDefault(10)
+ })
+ // URL: ?latitude=48.8566&longitude=2.3522&zoomLevel=12
+ // Long, harder to share, uses more bandwidth
+
+ return <Map {...coords} />
+}
+```
+
+**Correct (abbreviated URL keys):**
+
+```tsx
+'use client'
+import { useQueryStates, parseAsFloat, parseAsInteger } from 'nuqs'
+
+export default function MapView() {
+ const [coords, setCoords] = useQueryStates(
+ {
+ latitude: parseAsFloat.withDefault(0),
+ longitude: parseAsFloat.withDefault(0),
+ zoomLevel: parseAsInteger.withDefault(10)
+ },
+ {
+ urlKeys: {
+ latitude: 'lat',
+ longitude: 'lng',
+ zoomLevel: 'z'
+ }
+ }
+ )
+ // URL: ?lat=48.8566&lng=2.3522&z=12
+ // Shorter, cleaner URLs
+
+ // Code still uses descriptive names
+ console.log(coords.latitude, coords.longitude, coords.zoomLevel)
+
+ return <Map {...coords} />
+}
+```
+
+Reference: [nuqs urlKeys](https://nuqs.dev/docs/utilities)
diff --git a/.agents/skills/nuqs/references/debug-enable-logging.md b/.agents/skills/nuqs/references/debug-enable-logging.md
new file mode 100644
index 00000000..a9472686
--- /dev/null
+++ b/.agents/skills/nuqs/references/debug-enable-logging.md
@@ -0,0 +1,51 @@
+---
+title: Enable Debug Logging for Troubleshooting
+impact: LOW-MEDIUM
+impactDescription: surfaces the exact parse/serialize/URL-write step instead of guessing from silent state
+tags: debug, logging, localStorage, troubleshooting, devtools
+---
+
+## Enable Debug Logging for Troubleshooting
+
+Enable nuqs debug logs to understand state changes, URL updates, and timing. Useful for diagnosing issues with state synchronization or unexpected behavior.
+
+**Incorrect (no visibility into nuqs operations):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Counter() {
+ const [count, setCount] = useQueryState('count', parseAsInteger.withDefault(0))
+ // Something's not working, but no way to see what nuqs is doing
+ // Have to guess and add console.logs everywhere
+
+ return <button onClick={() => setCount(c => c + 1)}>{count}</button>
+}
+```
+
+**Correct (enable debug logging):**
+
+```javascript
+// Run in browser DevTools console FIRST
+localStorage.debug = 'nuqs'
+// Then reload the page
+// Now you see: [nuqs] useQueryState 'count' initialized with 0
+// And: [nuqs] useQueryState 'count' updated to 1
+```
+
+**Disable when done:**
+
+```javascript
+// Run in browser DevTools console
+delete localStorage.debug
+```
+
+**Performance timing markers:**
+
+Debug mode also records User Timing markers visible in the Performance tab:
+- `nuqs:parse` - Time to parse URL parameters
+- `nuqs:serialize` - Time to serialize state to URL
+- `nuqs:update` - Time for URL update
+
+Reference: [nuqs Debugging](https://nuqs.dev/docs)
diff --git a/.agents/skills/nuqs/references/debug-testing.md b/.agents/skills/nuqs/references/debug-testing.md
new file mode 100644
index 00000000..ee7493ea
--- /dev/null
+++ b/.agents/skills/nuqs/references/debug-testing.md
@@ -0,0 +1,55 @@
+---
+title: Test Components with URL State
+impact: LOW-MEDIUM
+impactDescription: enables reliable CI/CD testing of nuqs components
+tags: debug, testing, jest, vitest, react-testing-library
+---
+
+## Test Components with URL State
+
+Test components that use nuqs by providing the NuqsTestingAdapter and controlling URL state in tests.
+
+**Incorrect (test fails without adapter):**
+
+```tsx
+// components/Pagination.test.tsx
+import { render, screen } from '@testing-library/react'
+import Pagination from './Pagination'
+
+it('displays current page', () => {
+ render(<Pagination />) // Fails: no NuqsAdapter
+ expect(screen.getByText('Page 1')).toBeInTheDocument()
+})
+```
+
+**Correct (use NuqsTestingAdapter):**
+
+```tsx
+// test/utils.tsx
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { render, type RenderOptions } from '@testing-library/react'
+
+export function renderWithNuqs(
+ ui: React.ReactElement,
+ { searchParams = {}, ...options }: RenderOptions & { searchParams?: Record<string, string> } = {}
+) {
+ return render(
+ <NuqsTestingAdapter searchParams={searchParams}>
+ {ui}
+ </NuqsTestingAdapter>,
+ options
+ )
+}
+
+// components/Pagination.test.tsx
+import { screen } from '@testing-library/react'
+import { renderWithNuqs } from '@/test/utils'
+import Pagination from './Pagination'
+
+it('displays current page from URL', () => {
+ renderWithNuqs(<Pagination />, { searchParams: { page: '5' } })
+ expect(screen.getByText('Page 5')).toBeInTheDocument()
+})
+```
+
+Reference: [nuqs Testing Adapter](https://nuqs.dev/docs/testing)
diff --git a/.agents/skills/nuqs/references/history-push-navigation.md b/.agents/skills/nuqs/references/history-push-navigation.md
new file mode 100644
index 00000000..d82ca816
--- /dev/null
+++ b/.agents/skills/nuqs/references/history-push-navigation.md
@@ -0,0 +1,68 @@
+---
+title: Choose the Right history Mode (push vs replace)
+impact: MEDIUM
+impactDescription: back button behaves as users expect for navigation vs ephemeral state
+tags: history, push, replace, navigation, back-button, ux
+---
+
+## Choose the Right history Mode (push vs replace)
+
+`history: 'replace'` is the default: state updates rewrite the current history entry, so the back button never walks through intermediate values. Reach for `history: 'push'` only when a state change *is* navigation the user should be able to undo (pagination, tabs, modal state). Getting this backwards produces two opposite bugs — a back button that leaves the site, or one that is unusable.
+
+**Use `history: 'push'` for navigation-like state:**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState(
+ 'page',
+ parseAsInteger.withDefault(1).withOptions({ history: 'push' })
+ )
+ // Page 1 → 2 → 3, then Back returns to page 2 (not off-site)
+
+ return (
+ <nav>
+ <button onClick={() => setPage(p => p - 1)}>Previous</button>
+ <span>Page {page}</span>
+ <button onClick={() => setPage(p => p + 1)}>Next</button>
+ </nav>
+ )
+}
+```
+
+Typical `push` cases: pagination, tab selection, modal open/close, step-by-step wizards, filter-panel expansion.
+
+**Keep the default `replace` for ephemeral state:**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function SearchBox() {
+ // No withOptions — replace is the default
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
+ // Typing "react" does NOT create entries r, re, rea, reac, react
+
+ return <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search…" />
+}
+```
+
+Using `history: 'push'` here would push one entry per keystroke and make the back button useless. Typical `replace` cases: search input text, slider/range values, real-time filters, sort order — any rapidly-changing state.
+
+**Mix modes on a per-call basis when the same key does both:**
+
+```tsx
+const [page, setPage] = useQueryState(
+ 'page',
+ parseAsInteger.withDefault(1).withOptions({ history: 'push' })
+)
+
+setPage(5) // navigation → pushes
+setPage(1, { history: 'replace' }) // "reset to first page" shouldn't spam Back
+```
+
+The mirror pattern also works: keep the parser on `replace`, mirror the input in local `useState` while typing, and `setQuery(input, { history: 'push' })` only on explicit submit.
+
+Reference: [nuqs History Option](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/history-scroll-behavior.md b/.agents/skills/nuqs/references/history-scroll-behavior.md
new file mode 100644
index 00000000..2c41343e
--- /dev/null
+++ b/.agents/skills/nuqs/references/history-scroll-behavior.md
@@ -0,0 +1,60 @@
+---
+title: Control Scroll Behavior on URL Changes
+impact: MEDIUM
+impactDescription: prevents jarring scroll jumps on state changes
+tags: history, scroll, ux, navigation, viewport
+---
+
+## Control Scroll Behavior on URL Changes
+
+By default, nuqs doesn't scroll on URL changes. Use the `scroll` option to control whether state changes scroll to the top of the page.
+
+**Incorrect (unwanted scroll on filter change):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function FilterPanel() {
+ const [filter, setFilter] = useQueryState('filter', parseAsString.withDefault('').withOptions({
+ scroll: true // Bad for filters - user loses their place!
+ }))
+
+ return (
+ <select value={filter} onChange={e => setFilter(e.target.value)}>
+ <option value="">All</option>
+ <option value="active">Active</option>
+ </select>
+ )
+}
+```
+
+**Correct (no scroll for filters, scroll for pagination):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString, parseAsInteger } from 'nuqs'
+
+export default function SearchPage() {
+ // No scroll for filters - user stays in place
+ const [filter, setFilter] = useQueryState('filter', parseAsString.withDefault(''))
+
+ // Scroll for pagination - user sees new content from top
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1).withOptions({
+ scroll: true,
+ history: 'push'
+ }))
+
+ return (
+ <div>
+ <select value={filter} onChange={e => setFilter(e.target.value)}>
+ <option value="">All</option>
+ <option value="active">Active</option>
+ </select>
+ <button onClick={() => setPage(p => p + 1)}>Next Page</button>
+ </div>
+ )
+}
+```
+
+Reference: [nuqs Scroll Option](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/parser-array-format.md b/.agents/skills/nuqs/references/parser-array-format.md
new file mode 100644
index 00000000..42f66037
--- /dev/null
+++ b/.agents/skills/nuqs/references/parser-array-format.md
@@ -0,0 +1,61 @@
+---
+title: Choose Correct Array Parser Format
+impact: CRITICAL
+impactDescription: prevents API integration failures from wrong URL format
+tags: parser, parseAsArrayOf, parseAsNativeArrayOf, arrays, url-format
+---
+
+## Choose Correct Array Parser Format
+
+nuqs offers two array formats with different URL representations. Choose based on your backend API expectations and URL readability requirements.
+
+**Incorrect (wrong format for backend):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsArrayOf, parseAsString } from 'nuqs'
+
+export default function TagFilter() {
+ const [tags, setTags] = useQueryState(
+ 'tags',
+ parseAsArrayOf(parseAsString).withDefault([])
+ )
+ // URL: ?tags=react,nextjs
+ // But backend expects: ?tag=react&tag=nextjs
+ // API receives single string "react,nextjs" instead of array!
+}
+```
+
+**Correct (match backend expectations):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsNativeArrayOf, parseAsString } from 'nuqs'
+
+export default function TagFilter() {
+ const [tags, setTags] = useQueryState(
+ 'tag', // Note: singular key name
+ parseAsNativeArrayOf(parseAsString).withDefault([])
+ )
+ // URL: ?tag=react&tag=nextjs
+ // Backend correctly receives array ['react', 'nextjs']
+
+ return (
+ <div>
+ Tags: {tags.join(', ')}
+ <button onClick={() => setTags([...tags, 'new-tag'])}>Add</button>
+ </div>
+ )
+}
+```
+
+**When to use each:**
+
+| Format | URL Example | Use When | Min version |
+|--------|-------------|----------|-------------|
+| `parseAsArrayOf` | `?ids=1,2,3` | Compact URLs, numeric IDs, custom backends | All versions |
+| `parseAsNativeArrayOf` | `?tag=a&tag=b` | Standard form encoding, PHP/Rails backends | **v2.7+** (MultiParsers) |
+
+If you're on nuqs < 2.7, use `parseAsArrayOf` with a separator change (e.g., `.withOptions({ ... })`) or upgrade — there is no shim.
+
+Reference: [nuqs Array Parsers](https://nuqs.dev/docs/parsers/built-in)
diff --git a/.agents/skills/nuqs/references/parser-date-format.md b/.agents/skills/nuqs/references/parser-date-format.md
new file mode 100644
index 00000000..7b857e93
--- /dev/null
+++ b/.agents/skills/nuqs/references/parser-date-format.md
@@ -0,0 +1,67 @@
+---
+title: Select Appropriate Date Parser
+impact: CRITICAL
+impactDescription: prevents timezone bugs and parsing failures
+tags: parser, parseAsTimestamp, parseAsIsoDateTime, parseAsIsoDate, dates
+---
+
+## Select Appropriate Date Parser
+
+nuqs provides three date parsers with different URL formats and precision. Choose based on your requirements for time precision and URL readability.
+
+**Incorrect (wrong parser for use case):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsIsoDateTime } from 'nuqs'
+
+export default function DateRangePicker() {
+ const [startDate, setStartDate] = useQueryState('start', parseAsIsoDateTime)
+ // URL: ?start=2024-01-01T00:00:00.000Z
+ // Problem: User selected "Jan 1" but URL shows timezone complexity
+ // Better: Use parseAsIsoDate for date-only pickers
+
+ return (
+ <input
+ type="date"
+ value={startDate?.toISOString().slice(0, 10) ?? ''}
+ onChange={e => setStartDate(new Date(e.target.value))}
+ />
+ )
+}
+```
+
+**Correct (match parser to use case):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsIsoDate, parseAsTimestamp } from 'nuqs'
+
+export default function DateRangePicker() {
+ // For date-only picker: clean URL
+ const [startDate, setStartDate] = useQueryState('start', parseAsIsoDate)
+ // URL: ?start=2024-01-01
+
+ // For precise timestamps: use parseAsTimestamp
+ const [lastModified, setLastModified] = useQueryState('modified', parseAsTimestamp)
+ // URL: ?modified=1704067200000
+
+ return (
+ <input
+ type="date"
+ value={startDate?.toISOString().slice(0, 10) ?? ''}
+ onChange={e => setStartDate(new Date(e.target.value))}
+ />
+ )
+}
+```
+
+**When to use each:**
+
+| Parser | URL Format | Use Case |
+|--------|------------|----------|
+| `parseAsTimestamp` | `1704067200000` | Precise timestamps, API integration |
+| `parseAsIsoDateTime` | `2024-01-01T12:00:00.000Z` | Debugging, shareable URLs with time |
+| `parseAsIsoDate` | `2024-01-01` | Date pickers, calendar views |
+
+Reference: [nuqs Date Parsers](https://nuqs.dev/docs/parsers)
diff --git a/.agents/skills/nuqs/references/parser-enum-validation.md b/.agents/skills/nuqs/references/parser-enum-validation.md
new file mode 100644
index 00000000..5fc29c57
--- /dev/null
+++ b/.agents/skills/nuqs/references/parser-enum-validation.md
@@ -0,0 +1,81 @@
+---
+title: Use Enum Parsers for Constrained Values
+impact: CRITICAL
+impactDescription: prevents invalid state from URL manipulation
+tags: parser, parseAsStringEnum, parseAsStringLiteral, validation, security
+---
+
+## Use Enum Parsers for Constrained Values
+
+When state should only accept specific values (like status, sort direction, or view mode), use enum or literal parsers. This prevents invalid values from URL tampering and provides type safety.
+
+**Incorrect (accepts any string):**
+
+```tsx
+'use client'
+import { useQueryState } from 'nuqs'
+
+type SortOrder = 'asc' | 'desc'
+
+export default function SortableList() {
+ const [sort, setSort] = useQueryState('sort')
+ // sort is string | null - accepts ANY value
+ // URL: ?sort=malicious works silently
+
+ const sortOrder = sort as SortOrder // Unsafe cast!
+
+ return (
+ <select
+ value={sort ?? 'asc'}
+ onChange={e => setSort(e.target.value)}
+ >
+ <option value="asc">Ascending</option>
+ <option value="desc">Descending</option>
+ </select>
+ )
+}
+```
+
+**Correct (validated enum):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsStringLiteral } from 'nuqs'
+
+const sortOrders = ['asc', 'desc'] as const
+
+export default function SortableList() {
+ const [sort, setSort] = useQueryState(
+ 'sort',
+ parseAsStringLiteral(sortOrders).withDefault('asc')
+ )
+ // sort is 'asc' | 'desc' - invalid values return null/default
+ // URL: ?sort=malicious → falls back to 'asc'
+
+ return (
+ <select value={sort} onChange={e => setSort(e.target.value as typeof sort)}>
+ <option value="asc">Ascending</option>
+ <option value="desc">Descending</option>
+ </select>
+ )
+}
+```
+
+**Alternative (TypeScript enum):**
+
+```tsx
+import { parseAsStringEnum } from 'nuqs'
+
+enum Status {
+ Active = 'active',
+ Inactive = 'inactive',
+ Pending = 'pending'
+}
+
+const [status, setStatus] = useQueryState(
+ 'status',
+ parseAsStringEnum<Status>(Object.values(Status)).withDefault(Status.Active)
+)
+```
+
+Reference: [nuqs Enum Parsers](https://nuqs.dev/docs/parsers)
diff --git a/.agents/skills/nuqs/references/parser-index-offset.md b/.agents/skills/nuqs/references/parser-index-offset.md
new file mode 100644
index 00000000..8ad2bcab
--- /dev/null
+++ b/.agents/skills/nuqs/references/parser-index-offset.md
@@ -0,0 +1,72 @@
+---
+title: Use parseAsIndex for 1-Based URL Display
+impact: HIGH
+impactDescription: eliminates off-by-one errors between URL and code
+tags: parser, parseAsIndex, pagination, zero-indexed, one-indexed
+---
+
+## Use parseAsIndex for 1-Based URL Display
+
+Arrays are 0-indexed in JavaScript, but users expect 1-indexed URLs (page 1, item 1). `parseAsIndex` automatically converts between them.
+
+**Incorrect (manual conversion):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1))
+ // URL: ?page=1
+ // Array index: need page - 1 everywhere
+
+ const items = ['a', 'b', 'c', 'd', 'e']
+ const currentItem = items[page - 1] // Manual conversion
+
+ return (
+ <div>
+ <p>Page {page}: {currentItem}</p>
+ <button onClick={() => setPage(p => p + 1)}>Next</button>
+ </div>
+ )
+}
+```
+
+**Correct (automatic conversion):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsIndex } from 'nuqs'
+
+export default function Pagination() {
+ const [pageIndex, setPageIndex] = useQueryState(
+ 'page',
+ parseAsIndex.withDefault(0)
+ )
+ // URL: ?page=1 (user-friendly, 1-indexed)
+ // State: 0 (code-friendly, 0-indexed)
+
+ const items = ['a', 'b', 'c', 'd', 'e']
+ const currentItem = items[pageIndex] // Direct array access
+
+ return (
+ <div>
+ <p>Page {pageIndex + 1}: {currentItem}</p>
+ <button onClick={() => setPageIndex(i => i + 1)}>Next</button>
+ </div>
+ )
+}
+```
+
+**How it works:**
+- URL `?page=1` → State `0`
+- URL `?page=5` → State `4`
+- State `0` → URL `?page=1`
+- State `4` → URL `?page=5`
+
+**Benefits:**
+- No off-by-one bugs
+- Array indices work directly
+- URLs are human-friendly
+
+Reference: [nuqs parseAsIndex](https://nuqs.dev/docs/parsers)
diff --git a/.agents/skills/nuqs/references/parser-json-validation.md b/.agents/skills/nuqs/references/parser-json-validation.md
new file mode 100644
index 00000000..befafe6d
--- /dev/null
+++ b/.agents/skills/nuqs/references/parser-json-validation.md
@@ -0,0 +1,100 @@
+---
+title: Validate JSON Parser Input
+impact: CRITICAL
+impactDescription: prevents runtime crashes and unsafe casts from URL-supplied JSON
+tags: parser, parseAsJson, validation, standard-schema, zod
+---
+
+## Validate JSON Parser Input
+
+`parseAsJson` requires a validator function (this is a hard requirement in nuqs v2 — calling `parseAsJson<T>()` with no argument is a TypeScript error). The validator must return the typed value when valid and either throw or return `null` when invalid. Avoid the "make the type errors go away" shortcut of an unchecked cast — URL params are attacker-controlled input, and an unchecked cast lets any shape into your app.
+
+**Incorrect (unchecked cast as the validator):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsJson } from 'nuqs'
+
+interface Filters {
+ minPrice: number
+ maxPrice: number
+ categories: string[]
+}
+
+export default function FilterPanel() {
+ const [filters, setFilters] = useQueryState(
+ 'filters',
+ parseAsJson((v) => v as Filters) // Cast — no runtime check
+ )
+ // URL: ?filters={"minPrice":"haha"} → filters.minPrice is "haha", not a number
+ // URL: ?filters=notjson → null, but downstream code expecting a string crashes
+
+ return <div>Min: {filters?.minPrice.toFixed(2)}</div>
+}
+```
+
+**Correct (hand-rolled type guard):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsJson } from 'nuqs'
+
+interface Filters {
+ minPrice: number
+ maxPrice: number
+ categories: string[]
+}
+
+function isFilters(value: unknown): value is Filters {
+ if (!value || typeof value !== 'object') return false
+ const obj = value as Record<string, unknown>
+ return (
+ typeof obj.minPrice === 'number' &&
+ typeof obj.maxPrice === 'number' &&
+ Array.isArray(obj.categories) &&
+ obj.categories.every((c) => typeof c === 'string')
+ )
+}
+
+export default function FilterPanel() {
+ const [filters] = useQueryState(
+ 'filters',
+ parseAsJson<Filters>((value) => (isFilters(value) ? value : null)).withDefault({
+ minPrice: 0,
+ maxPrice: 1000,
+ categories: []
+ })
+ )
+ // Invalid JSON → null → falls back to default
+
+ return <div>Price: {filters.minPrice} – {filters.maxPrice}</div>
+}
+```
+
+**Correct (Standard Schema — Zod, Valibot, ArkType, Effect Schema):**
+
+Since nuqs v2.5 the validator slot accepts any Standard Schema parser directly — no `safeParse(...).success ? value : null` wrapper required. Zod's `.parse` throws on invalid input, which nuqs catches and converts to `null`.
+
+```tsx
+import { z } from 'zod'
+
+const FiltersSchema = z.object({
+ minPrice: z.number(),
+ maxPrice: z.number(),
+ categories: z.array(z.string())
+})
+
+const [filters] = useQueryState(
+ 'filters',
+ parseAsJson(FiltersSchema.parse).withDefault({
+ minPrice: 0,
+ maxPrice: 1000,
+ categories: []
+ })
+)
+```
+
+**When NOT to use this pattern:**
+- For non-object types, prefer typed primitive parsers (`parseAsInteger`, `parseAsStringEnum`, `parseAsArrayOf`) — they're cheaper and the validator is implicit.
+
+Reference: [nuqs Built-in Parsers](https://nuqs.dev/docs/parsers/built-in)
diff --git a/.agents/skills/nuqs/references/parser-use-typed-parsers.md b/.agents/skills/nuqs/references/parser-use-typed-parsers.md
new file mode 100644
index 00000000..6c9daa46
--- /dev/null
+++ b/.agents/skills/nuqs/references/parser-use-typed-parsers.md
@@ -0,0 +1,58 @@
+---
+title: Use Typed Parsers for Non-String Values
+impact: CRITICAL
+impactDescription: prevents runtime type errors and hydration mismatches
+tags: parser, type-safety, parseAsInteger, parseAsFloat, parseAsBoolean
+---
+
+## Use Typed Parsers for Non-String Values
+
+URL query parameters are always strings. Without typed parsers, you'll get string values where you expect numbers or booleans, causing type errors and incorrect comparisons.
+
+**Incorrect (string instead of number):**
+
+```tsx
+'use client'
+import { useQueryState } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState('page')
+ // page is string | null, not number
+ // page + 1 = "11" not 2 when page is "1"
+
+ return (
+ <button onClick={() => setPage(String(Number(page) + 1))}>
+ Next Page
+ </button>
+ )
+}
+```
+
+**Correct (typed parser):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState('page', parseAsInteger)
+ // page is number | null
+ // Arithmetic works correctly
+
+ return (
+ <button onClick={() => setPage((p) => (p ?? 0) + 1)}>
+ Next Page
+ </button>
+ )
+}
+```
+
+**Available parsers:**
+- `parseAsInteger` - integers
+- `parseAsFloat` - decimal numbers
+- `parseAsBoolean` - true/false
+- `parseAsTimestamp` - Date from milliseconds
+- `parseAsIsoDateTime` - Date from ISO string
+- `parseAsJson<T>()` - JSON objects
+
+Reference: [nuqs Parsers Documentation](https://nuqs.dev/docs/parsers)
diff --git a/.agents/skills/nuqs/references/parser-with-default.md b/.agents/skills/nuqs/references/parser-with-default.md
new file mode 100644
index 00000000..c94bd97b
--- /dev/null
+++ b/.agents/skills/nuqs/references/parser-with-default.md
@@ -0,0 +1,65 @@
+---
+title: Use withDefault for Non-Nullable State
+impact: CRITICAL
+impactDescription: eliminates null checks throughout component tree
+tags: parser, withDefault, null-safety, type-inference
+---
+
+## Use withDefault for Non-Nullable State
+
+Without `withDefault`, query state is always nullable (`T | null`). This forces null checks everywhere the value is used. Use `withDefault` to provide a fallback value and get non-nullable types.
+
+**Incorrect (nullable state, null checks everywhere):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Counter() {
+ const [count, setCount] = useQueryState('count', parseAsInteger)
+ // count is number | null
+
+ return (
+ <div>
+ {/* Null check required */}
+ <p>Count: {count ?? 0}</p>
+ {/* Null check required */}
+ <button onClick={() => setCount((count ?? 0) + 1)}>
+ Increment
+ </button>
+ </div>
+ )
+}
+```
+
+**Correct (non-nullable with default):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Counter() {
+ const [count, setCount] = useQueryState(
+ 'count',
+ parseAsInteger.withDefault(0)
+ )
+ // count is number (never null)
+
+ return (
+ <div>
+ <p>Count: {count}</p>
+ <button onClick={() => setCount(c => c + 1)}>
+ Increment
+ </button>
+ </div>
+ )
+}
+```
+
+**Benefits:**
+- TypeScript infers non-nullable type
+- No null coalescing needed
+- Functional updates work without null checks
+- Default appears in URL only when `clearOnDefault: false`
+
+Reference: [nuqs withDefault](https://nuqs.dev/docs/parsers)
diff --git a/.agents/skills/nuqs/references/perf-avoid-rerender.md b/.agents/skills/nuqs/references/perf-avoid-rerender.md
new file mode 100644
index 00000000..1dbffa5c
--- /dev/null
+++ b/.agents/skills/nuqs/references/perf-avoid-rerender.md
@@ -0,0 +1,92 @@
+---
+title: Memoize Components Using URL State
+impact: MEDIUM
+impactDescription: prevents unnecessary re-renders on URL changes (Next.js especially)
+tags: perf, memo, re-renders, key-isolation, react
+---
+
+## Memoize Components Using URL State
+
+When URL state changes, components subscribed to that state re-render. On Next.js, every `useQueryState`/`useQueryStates` consumer in the subtree re-renders on **any** URL change because `URLSearchParams` is provided through a single context. Use `React.memo` and confine hook usage to leaf components to avoid cascading re-renders.
+
+On non-Next.js adapters (React SPA, React Router, Remix, TanStack Router), nuqs v2.5 added **key isolation**: a hook only re-renders when its specific key changes. The memoization advice below is still useful but far less critical on those frameworks — see `perf-key-isolation`.
+
+**Incorrect (entire page re-renders on every Next.js URL change):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function SearchPage() {
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
+
+ return (
+ <div>
+ <SearchInput query={query} setQuery={setQuery} />
+ <ExpensiveSidebar /> {/* Re-renders on every query change */}
+ <ResultsList query={query} />
+ </div>
+ )
+}
+
+function ExpensiveSidebar() {
+ // Heavy computation that doesn't need query
+ return <aside>…</aside>
+}
+```
+
+**Correct (memoize unrelated subtrees):**
+
+```tsx
+'use client'
+import { memo } from 'react'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function SearchPage() {
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
+
+ return (
+ <div>
+ <SearchInput query={query} setQuery={setQuery} />
+ <ExpensiveSidebar /> {/* Memoized — bypasses re-render when query changes */}
+ <ResultsList query={query} />
+ </div>
+ )
+}
+
+const ExpensiveSidebar = memo(function ExpensiveSidebar() {
+ return <aside>…</aside>
+})
+```
+
+**Better (hoist the hook into a leaf — works on all adapters):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+function SearchSection() {
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
+
+ return (
+ <>
+ <SearchInput query={query} setQuery={setQuery} />
+ <ResultsList query={query} />
+ </>
+ )
+}
+
+export default function SearchPage() {
+ return (
+ <div>
+ <SearchSection /> {/* Only this subtree re-renders on URL change */}
+ <ExpensiveSidebar /> {/* Not affected */}
+ </div>
+ )
+}
+```
+
+**When NOT to use this pattern:**
+- Non-Next.js adapters where the consumer is already a leaf — key isolation makes memoization unnecessary noise.
+
+Reference: [React memo](https://react.dev/reference/react/memo)
diff --git a/.agents/skills/nuqs/references/perf-clear-on-default.md b/.agents/skills/nuqs/references/perf-clear-on-default.md
new file mode 100644
index 00000000..c55dff28
--- /dev/null
+++ b/.agents/skills/nuqs/references/perf-clear-on-default.md
@@ -0,0 +1,55 @@
+---
+title: Use clearOnDefault for Clean URLs
+impact: MEDIUM
+impactDescription: reduces URL length by 20-50% for default values
+tags: perf, clearOnDefault, url-cleanup, defaults, seo
+---
+
+## Use clearOnDefault for Clean URLs
+
+By default, nuqs removes parameters from the URL when they match the default value. This keeps URLs clean. Set `clearOnDefault: false` only when you need the parameter always visible.
+
+**Incorrect (default always shown in URL):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1).withOptions({
+ clearOnDefault: false // Unnecessary!
+ }))
+ // URL always shows ?page=1 even on first page
+ // Clutters shareable URLs, hurts SEO
+
+ return <button onClick={() => setPage(1)}>First</button>
+}
+```
+
+**Correct (clean URLs by default):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1))
+ // clearOnDefault: true (default)
+ // page=1: URL is /search (clean)
+ // page=2: URL is /search?page=2
+
+ return (
+ <div>
+ <button onClick={() => setPage(1)}>First</button>
+ <button onClick={() => setPage(p => p + 1)}>Next</button>
+ </div>
+ )
+}
+```
+
+**When clearOnDefault: false is appropriate:**
+- Analytics tracking requires all parameters
+- API expects explicit parameter even for default
+- Debugging where you need to see all state
+
+Reference: [nuqs clearOnDefault](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/perf-debounce-search.md b/.agents/skills/nuqs/references/perf-debounce-search.md
new file mode 100644
index 00000000..c604c1f7
--- /dev/null
+++ b/.agents/skills/nuqs/references/perf-debounce-search.md
@@ -0,0 +1,88 @@
+---
+title: Debounce Search Input Before URL Update
+impact: HIGH
+impactDescription: reduces server requests during typing from N per keystroke to 1 per pause
+tags: perf, limitUrlUpdates, debounce, search, server-load
+---
+
+## Debounce Search Input Before URL Update
+
+For search inputs that drive a server fetch (`shallow: false`), debounce the URL write so the server only re-renders once the user stops typing. Since nuqs v2.5, debounce is built in — pass `limitUrlUpdates: debounce(N)` instead of hand-rolling a `setTimeout` dance with a parallel local-state mirror.
+
+**Incorrect (a server request per keystroke):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function SearchBox() {
+ const [query, setQuery] = useQueryState(
+ 'q',
+ parseAsString.withDefault('').withOptions({
+ shallow: false // Every keystroke triggers a server re-render
+ })
+ )
+
+ return <input value={query} onChange={(e) => setQuery(e.target.value)} />
+}
+```
+
+**Correct (built-in debounce — one request per pause):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString, debounce } from 'nuqs'
+import { useTransition } from 'react'
+
+export default function SearchBox() {
+ const [isLoading, startTransition] = useTransition()
+ const [query, setQuery] = useQueryState(
+ 'q',
+ parseAsString.withDefault('').withOptions({
+ shallow: false,
+ startTransition,
+ limitUrlUpdates: debounce(300) // Server request fires 300ms after last keystroke
+ })
+ )
+
+ return (
+ <>
+ <input value={query} onChange={(e) => setQuery(e.target.value)} />
+ {isLoading && <span>Searching…</span>}
+ </>
+ )
+}
+```
+
+**Why this beats the manual `setTimeout` pattern:**
+- One source of truth — `query` is both the displayed value and the in-flight value; no parallel `useState` mirror.
+- The Promise returned by the setter still resolves to the merged `URLSearchParams` after the debounce fires, so analytics/share flows keep working.
+- nuqs v2.6 emits a warning if you combine `shallow: true` with debounce — `shallow: true` already keeps the URL local, so debouncing it is almost always a bug. Honour the warning.
+
+**Alternative (no URL-driven fetch — useDeferredValue is fine):**
+
+When the search is purely client-side (`shallow: true`, the default), React's `useDeferredValue` keeps the input responsive without touching nuqs options:
+
+```tsx
+'use client'
+import { useDeferredValue } from 'react'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function ClientSearch() {
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
+ const deferredQuery = useDeferredValue(query)
+
+ return (
+ <>
+ <input value={query} onChange={(e) => setQuery(e.target.value)} />
+ <Results query={deferredQuery} />
+ </>
+ )
+}
+```
+
+**When NOT to use this pattern:**
+- The setter only fires on submit/blur — there's nothing to debounce.
+- You want to rate-limit continuous input (slider drags, scrub bars) — `throttle()` keeps intermediate values; `debounce()` discards them. See `perf-throttle-updates`.
+
+Reference: [nuqs Options](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/perf-key-isolation.md b/.agents/skills/nuqs/references/perf-key-isolation.md
new file mode 100644
index 00000000..15a8334d
--- /dev/null
+++ b/.agents/skills/nuqs/references/perf-key-isolation.md
@@ -0,0 +1,68 @@
+---
+title: Rely on Key Isolation Outside Next.js
+impact: HIGH
+impactDescription: avoids unnecessary memoization on adapters that already scope re-renders per key
+tags: perf, key-isolation, react-router, tanstack-router, remix, re-renders
+---
+
+## Rely on Key Isolation Outside Next.js
+
+nuqs v2.5 added **key isolation** on every non-Next.js adapter (Plain React, React Router v5/v6/v7, Remix, TanStack Router). A `useQueryState('foo', …)` consumer there only re-renders when **`foo`** changes — unrelated URL key changes are filtered out by the adapter's subscription model. On those frameworks, the manual `memo`/leaf-component gymnastics from `perf-avoid-rerender` are usually unnecessary.
+
+Next.js still re-renders the whole subtree on any URL change because `URLSearchParams` is delivered via a single root context. Treat Next.js as the exception.
+
+**Incorrect (over-memoising on a key-isolated adapter):**
+
+```tsx
+// React Router v7 app
+import { memo } from 'react'
+import { useQueryState, parseAsString } from 'nuqs'
+
+const Tags = memo(function Tags() {
+ const [tags] = useQueryState('tags', parseAsString.withDefault(''))
+ return <TagBadges tags={tags} />
+})
+
+const Sort = memo(function Sort() {
+ const [sort] = useQueryState('sort', parseAsString.withDefault('desc'))
+ return <SortPicker value={sort} />
+})
+// `memo` is redundant — Tags never re-renders when `sort` changes,
+// and vice versa. Adapter already isolates by key.
+```
+
+**Correct (let the adapter do the work):**
+
+```tsx
+// React Router v7 app
+import { useQueryState, parseAsString } from 'nuqs'
+
+function Tags() {
+ const [tags] = useQueryState('tags', parseAsString.withDefault(''))
+ return <TagBadges tags={tags} />
+}
+
+function Sort() {
+ const [sort] = useQueryState('sort', parseAsString.withDefault('desc'))
+ return <SortPicker value={sort} />
+}
+// Tags re-renders only on `tags` changes, Sort only on `sort` — no wrappers needed.
+```
+
+**Practical rule of thumb:**
+
+| Adapter | Re-render scope per `useQueryState` | Manual memoization usually worth it? |
+|---------|-------------------------------------|--------------------------------------|
+| Next.js (App + Pages) | Whole consumer subtree on **any** URL change | Yes (see `perf-avoid-rerender`) |
+| Plain React | Only when subscribed key changes | No |
+| React Router v5/v6/v7 | Only when subscribed key changes | No |
+| Remix | Only when subscribed key changes | No |
+| TanStack Router | Only when subscribed key changes | No |
+
+**Caveat:** `useQueryStates` (the plural form) intentionally subscribes to **every** key in its object, so it re-renders whenever any of those keys change — that is its contract. If you want per-key isolation, prefer multiple `useQueryState` hooks.
+
+**When NOT to use this pattern:**
+- You're on Next.js — apply `perf-avoid-rerender` instead.
+- You're using `useQueryStates` for atomic updates and accept the coarser subscription. See `state-use-query-states` for the tradeoff.
+
+Reference: [nuqs 2.5 release notes](https://nuqs.dev/blog/nuqs-2.5)
diff --git a/.agents/skills/nuqs/references/perf-serialize-utility.md b/.agents/skills/nuqs/references/perf-serialize-utility.md
new file mode 100644
index 00000000..0159cc18
--- /dev/null
+++ b/.agents/skills/nuqs/references/perf-serialize-utility.md
@@ -0,0 +1,81 @@
+---
+title: Use createSerializer for Link URLs
+impact: MEDIUM
+impactDescription: enables SSR-compatible URL generation without hooks
+tags: perf, createSerializer, links, navigation, ssr
+---
+
+## Use createSerializer for Link URLs
+
+When generating URLs for links or navigation without needing state, use `createSerializer`. This avoids unnecessary hook usage and works in Server Components.
+
+**Incorrect (hook for URL generation only):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function PaginationLinks({ totalPages }: { totalPages: number }) {
+ const [page] = useQueryState('page', parseAsInteger.withDefault(1))
+
+ // Using state just to generate URLs
+ return (
+ <nav>
+ {Array.from({ length: totalPages }, (_, i) => (
+ <a key={i} href={`?page=${i + 1}`}>
+ {i + 1}
+ </a>
+ ))}
+ </nav>
+ )
+}
+```
+
+**Correct (serializer utility):**
+
+```tsx
+// lib/searchParams.ts
+import { createSerializer, parseAsInteger, parseAsString } from 'nuqs/server'
+
+export const searchParams = {
+ q: parseAsString,
+ page: parseAsInteger.withDefault(1)
+}
+
+export const serialize = createSerializer(searchParams)
+
+// components/PaginationLinks.tsx (can be Server Component)
+import { serialize } from '@/lib/searchParams'
+
+export default function PaginationLinks({ totalPages }: { totalPages: number }) {
+ return (
+ <nav>
+ {Array.from({ length: totalPages }, (_, i) => (
+ <a key={i} href={`?${serialize({ page: i + 1 })}`}>
+ {i + 1}
+ </a>
+ ))}
+ </nav>
+ )
+}
+```
+
+**Building on existing URL:**
+
+```tsx
+import { serialize } from '@/lib/searchParams'
+
+// Preserve existing params, change page
+const currentParams = { q: 'react', page: 1 }
+const nextPageUrl = `?${serialize({ ...currentParams, page: 2 })}`
+// Result: ?q=react&page=2
+```
+
+**With base URL:**
+
+```tsx
+const url = serialize('/search', { q: 'react', page: 1 })
+// Result: /search?q=react&page=1
+```
+
+Reference: [nuqs createSerializer](https://nuqs.dev/docs/utilities)
diff --git a/.agents/skills/nuqs/references/perf-throttle-updates.md b/.agents/skills/nuqs/references/perf-throttle-updates.md
new file mode 100644
index 00000000..72e08413
--- /dev/null
+++ b/.agents/skills/nuqs/references/perf-throttle-updates.md
@@ -0,0 +1,98 @@
+---
+title: Throttle Rapid URL Updates
+impact: MEDIUM
+impactDescription: prevents browser history API rate limiting on rapid input
+tags: perf, limitUrlUpdates, throttle, rate-limiting, slider
+---
+
+## Throttle Rapid URL Updates
+
+Browsers rate-limit History API calls. Rapid updates (typing, sliders, dragging) can exceed this limit, causing dropped updates and console warnings. Pass `limitUrlUpdates: throttle(N)` to coalesce URL writes — local state continues to update instantly, the URL writes at most every N ms.
+
+The legacy `throttleMs: N` option was deprecated in nuqs v2.5. It still works in v2.9 for backwards compatibility, but its JSDoc marks it deprecated and it will be removed in v3 — write new code with `limitUrlUpdates: throttle(N)` (or `debounce(N)`).
+
+**Incorrect (every keystroke pushes to history):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function SearchBox() {
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
+ // Every keystroke writes to history → browser may throttle after ~100 rapid updates
+
+ return (
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ )
+}
+```
+
+**Correct (throttle URL updates):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString, throttle } from 'nuqs'
+
+export default function SearchBox() {
+ const [query, setQuery] = useQueryState(
+ 'q',
+ parseAsString.withDefault('').withOptions({
+ limitUrlUpdates: throttle(300) // URL flushed at most every 300ms
+ })
+ )
+
+ return (
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ )
+}
+```
+
+**For sliders and drag operations (tighter window):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger, throttle } from 'nuqs'
+
+export default function VolumeSlider() {
+ const [volume, setVolume] = useQueryState(
+ 'volume',
+ parseAsInteger.withDefault(50).withOptions({
+ limitUrlUpdates: throttle(100) // More responsive for continuous input
+ })
+ )
+
+ return (
+ <input
+ type="range" min={0} max={100}
+ value={volume}
+ onChange={(e) => setVolume(Number(e.target.value))}
+ />
+ )
+}
+```
+
+**Force an immediate (non-throttled) flush on a single call:**
+
+```tsx
+import { defaultRateLimit } from 'nuqs'
+
+// Normal updates use the throttle window
+setQuery('intermediate')
+
+// On blur, bypass rate limiting and commit immediately
+setQuery('final value', { limitUrlUpdates: defaultRateLimit })
+```
+
+**When NOT to use this pattern:**
+- Search inputs that drive a server fetch (`shallow: false`) — prefer `debounce()` so the request only fires once the user stops typing. See `perf-debounce-search`.
+- One-off updates (button clicks, form submits) — there's nothing to throttle.
+
+**Note:** UI state from the hook updates synchronously regardless of `limitUrlUpdates`; only the URL write is rate-limited.
+
+Reference: [nuqs Options](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/server-next15-async.md b/.agents/skills/nuqs/references/server-next15-async.md
new file mode 100644
index 00000000..b85ee524
--- /dev/null
+++ b/.agents/skills/nuqs/references/server-next15-async.md
@@ -0,0 +1,80 @@
+---
+title: Handle Async searchParams in Next.js 15+
+impact: HIGH
+impactDescription: prevents build errors in Next.js 15 with async props
+tags: server, nextjs15, async, searchParams, promise
+---
+
+## Handle Async searchParams in Next.js 15+
+
+In Next.js 15+, `searchParams` is a Promise that must be awaited. Using it directly without await causes TypeScript errors and runtime issues.
+
+**Incorrect (Next.js 15+ without await):**
+
+```tsx
+// app/search/page.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+
+type PageProps = {
+ searchParams: { q?: string } // Wrong type for Next.js 15+
+}
+
+export default async function SearchPage({ searchParams }: PageProps) {
+ // searchParams is a Promise, not an object
+ const { q } = searchParamsCache.parse(searchParams) // Type error
+}
+```
+
+**Correct (Next.js 15+):**
+
+```tsx
+// app/search/page.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+import type { SearchParams } from 'nuqs/server'
+
+type PageProps = {
+ searchParams: Promise<SearchParams> // Correct type
+}
+
+export default async function SearchPage({ searchParams }: PageProps) {
+ // Await the Promise
+ const { q, page } = await searchParamsCache.parse(searchParams)
+
+ return <Results query={q} page={page} />
+}
+```
+
+**For Next.js 14 and earlier:**
+
+```tsx
+// app/search/page.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+
+type PageProps = {
+ searchParams: Record<string, string | string[] | undefined>
+}
+
+export default function SearchPage({ searchParams }: PageProps) {
+ // No await needed in Next.js 14
+ const { q, page } = searchParamsCache.parse(searchParams)
+
+ return <Results query={q} page={page} />
+}
+```
+
+**Version-agnostic pattern:**
+
+```tsx
+import type { SearchParams } from 'nuqs/server'
+
+type PageProps = {
+ searchParams: Promise<SearchParams>
+}
+
+export default async function SearchPage({ searchParams }: PageProps) {
+ // Works in both Next.js 14 and 15
+ const { q } = await searchParamsCache.parse(searchParams)
+}
+```
+
+Reference: [Next.js 15 Migration](https://nextjs.org/docs/app/building-your-application/upgrading/version-15)
diff --git a/.agents/skills/nuqs/references/server-parse-before-get.md b/.agents/skills/nuqs/references/server-parse-before-get.md
new file mode 100644
index 00000000..11d135a0
--- /dev/null
+++ b/.agents/skills/nuqs/references/server-parse-before-get.md
@@ -0,0 +1,82 @@
+---
+title: Call parse() Before get() in Server Components
+impact: HIGH
+impactDescription: prevents undefined values and runtime errors
+tags: server, parse, get, searchParamsCache, initialization
+---
+
+## Call parse() Before get() in Server Components
+
+`createSearchParamsCache` requires calling `parse()` at the page level before calling `get()` in nested components. Forgetting `parse()` causes `get()` to return undefined or throw.
+
+**Incorrect (missing parse):**
+
+```tsx
+// app/search/page.tsx
+import { ResultsHeader } from './ResultsHeader'
+
+export default async function SearchPage({ searchParams }) {
+ // Missing: await searchParamsCache.parse(searchParams)
+
+ return (
+ <div>
+ <ResultsHeader /> {/* Will fail or return undefined */}
+ <Results />
+ </div>
+ )
+}
+
+// components/ResultsHeader.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+
+export function ResultsHeader() {
+ const query = searchParamsCache.get('q') // Error: cache not initialized
+ return <h1>Results for {query}</h1>
+}
+```
+
+**Correct (parse at page level):**
+
+```tsx
+// app/search/page.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+import { ResultsHeader } from './ResultsHeader'
+import type { SearchParams } from 'nuqs/server'
+
+type PageProps = {
+ searchParams: Promise<SearchParams>
+}
+
+export default async function SearchPage({ searchParams }: PageProps) {
+ // Parse FIRST, before rendering any children
+ await searchParamsCache.parse(searchParams)
+
+ return (
+ <div>
+ <ResultsHeader /> {/* Now get() works */}
+ <Results />
+ </div>
+ )
+}
+
+// components/ResultsHeader.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+
+export function ResultsHeader() {
+ const query = searchParamsCache.get('q') // Works correctly
+ return <h1>Results for {query}</h1>
+}
+```
+
+**Parse and destructure in one step:**
+
+```tsx
+export default async function SearchPage({ searchParams }: PageProps) {
+ const { q, page } = await searchParamsCache.parse(searchParams)
+ // Use q and page directly, or let children use get()
+
+ return <Results query={q} page={page} />
+}
+```
+
+Reference: [nuqs Server Cache](https://nuqs.dev/docs/server-side)
diff --git a/.agents/skills/nuqs/references/server-search-params-cache.md b/.agents/skills/nuqs/references/server-search-params-cache.md
new file mode 100644
index 00000000..a1141e30
--- /dev/null
+++ b/.agents/skills/nuqs/references/server-search-params-cache.md
@@ -0,0 +1,100 @@
+---
+title: Use createSearchParamsCache for Server Components
+impact: HIGH
+impactDescription: eliminates prop drilling across N component levels
+tags: server, createSearchParamsCache, server-components, type-safety
+---
+
+## Use createSearchParamsCache for Server Components
+
+In Server Components, use `createSearchParamsCache` to access URL parameters with type safety. This avoids prop drilling and provides the same parsers as client-side hooks.
+
+**Incorrect (manual parsing):**
+
+```tsx
+// app/search/page.tsx
+type PageProps = {
+ searchParams: Promise<{ q?: string; page?: string }>
+}
+
+export default async function SearchPage({ searchParams }: PageProps) {
+ const params = await searchParams
+ const query = params.q ?? ''
+ const page = parseInt(params.page ?? '1', 10) // Manual parsing
+ // No type safety, parsing logic duplicated
+
+ return <Results query={query} page={page} />
+}
+```
+
+**Correct (search params cache):**
+
+```tsx
+// lib/searchParams.ts
+import {
+ createSearchParamsCache,
+ parseAsString,
+ parseAsInteger
+} from 'nuqs/server'
+
+export const searchParamsCache = createSearchParamsCache({
+ q: parseAsString.withDefault(''),
+ page: parseAsInteger.withDefault(1)
+})
+
+// app/search/page.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+import type { SearchParams } from 'nuqs/server'
+
+type PageProps = {
+ searchParams: Promise<SearchParams>
+}
+
+export default async function SearchPage({ searchParams }: PageProps) {
+ // Parse once at page level
+ const { q, page } = await searchParamsCache.parse(searchParams)
+
+ return <Results query={q} page={page} />
+}
+```
+
+**Access in nested Server Components:**
+
+```tsx
+// components/ResultsHeader.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+
+export function ResultsHeader() {
+ // No props needed - access from cache
+ const query = searchParamsCache.get('q')
+ const page = searchParamsCache.get('page')
+
+ return <h1>Results for "{query}" (Page {page})</h1>
+}
+```
+
+**Important:** Call `parse()` once at the page level before using `get()` in nested components.
+
+**Alternative: `createLoader` for non-nested cases.** If you only consume the parsed values inside the page itself (no deeply nested Server Components needing `get()`), `createLoader` is the lighter primitive — it returns a single function and skips the React-cache plumbing. Use the cache when you'd otherwise prop-drill; use the loader when you wouldn't.
+
+```tsx
+// lib/searchParams.ts
+import { createLoader, parseAsString, parseAsInteger } from 'nuqs/server'
+
+export const loadSearchParams = createLoader({
+ q: parseAsString.withDefault(''),
+ page: parseAsInteger.withDefault(1)
+})
+
+// app/search/page.tsx
+import { loadSearchParams } from '@/lib/searchParams'
+
+export default async function SearchPage({ searchParams }) {
+ const { q, page } = await loadSearchParams(searchParams)
+ return <Results query={q} page={page} />
+}
+```
+
+The same parser map can power **both** `createSearchParamsCache` and `createLoader` (and a client-side `useQueryStates`), so the choice is purely about ergonomics — see `setup-shared-parsers`.
+
+Reference: [nuqs Server-Side](https://nuqs.dev/docs/server-side)
diff --git a/.agents/skills/nuqs/references/server-shallow-false.md b/.agents/skills/nuqs/references/server-shallow-false.md
new file mode 100644
index 00000000..6ca0ef6e
--- /dev/null
+++ b/.agents/skills/nuqs/references/server-shallow-false.md
@@ -0,0 +1,74 @@
+---
+title: Use shallow:false to Trigger Server Re-renders
+impact: HIGH
+impactDescription: enables server-side data refetching on URL change
+tags: server, shallow, server-components, data-fetching, rsc
+---
+
+## Use shallow:false to Trigger Server Re-renders
+
+By default, nuqs updates are client-side only (`shallow: true`). Set `shallow: false` to trigger Server Component re-renders when URL changes, enabling server-side data fetching.
+
+**Incorrect (server data never refreshes):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1))
+ // shallow: true (default) - server doesn't see URL changes
+ // Server-fetched data stays stale
+
+ return <button onClick={() => setPage(p => p + 1)}>Next</button>
+}
+```
+
+**Correct (server refetches on change):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1).withOptions({
+ shallow: false // Notify server of URL changes
+ }))
+ // Server Components re-render with new page value
+
+ return <button onClick={() => setPage(p => p + 1)}>Next</button>
+}
+```
+
+**With loading state using useTransition:**
+
+```tsx
+'use client'
+import { useTransition } from 'react'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [isLoading, startTransition] = useTransition()
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1).withOptions({
+ shallow: false,
+ startTransition // Shows loading during server fetch
+ }))
+
+ return (
+ <div>
+ {isLoading && <span>Loading...</span>}
+ <button onClick={() => setPage(p => p + 1)} disabled={isLoading}>
+ Next
+ </button>
+ </div>
+ )
+}
+```
+
+**When to use shallow:false:**
+- Pagination with server-fetched data
+- Search that triggers server queries
+- Filters that affect server-rendered content
+- Any state that affects Server Component output
+
+Reference: [nuqs Shallow Option](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/server-use-transition.md b/.agents/skills/nuqs/references/server-use-transition.md
new file mode 100644
index 00000000..b2714b80
--- /dev/null
+++ b/.agents/skills/nuqs/references/server-use-transition.md
@@ -0,0 +1,96 @@
+---
+title: Integrate useTransition for Loading States
+impact: HIGH
+impactDescription: exposes pending state for non-shallow server fetches so the UI can show loading
+tags: server, useTransition, loading, suspense, streaming
+---
+
+## Integrate useTransition for Loading States
+
+When using `shallow: false`, integrate React's `useTransition` to track when the server is fetching new data. This enables loading indicators during URL-triggered server updates.
+
+**Incorrect (no loading feedback):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function SearchBox() {
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault('').withOptions({
+ shallow: false
+ }))
+ // User types, waits with no feedback while server fetches
+
+ return (
+ <input
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ placeholder="Search..."
+ />
+ )
+}
+```
+
+**Correct (loading state):**
+
+```tsx
+'use client'
+import { useTransition } from 'react'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function SearchBox() {
+ const [isLoading, startTransition] = useTransition()
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault('').withOptions({
+ shallow: false,
+ startTransition
+ }))
+
+ return (
+ <div>
+ <input
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ placeholder="Search..."
+ />
+ {isLoading && <span className="spinner" />}
+ </div>
+ )
+}
+```
+
+**With disabled interaction during load:**
+
+```tsx
+'use client'
+import { useTransition } from 'react'
+import { useQueryStates, parseAsString, parseAsInteger } from 'nuqs'
+
+export default function FilterPanel() {
+ const [isLoading, startTransition] = useTransition()
+ const [filters, setFilters] = useQueryStates(
+ {
+ category: parseAsString.withDefault(''),
+ page: parseAsInteger.withDefault(1)
+ },
+ {
+ shallow: false,
+ startTransition
+ }
+ )
+
+ return (
+ <fieldset disabled={isLoading}>
+ <select
+ value={filters.category}
+ onChange={e => setFilters({ category: e.target.value, page: 1 })}
+ >
+ <option value="">All</option>
+ <option value="electronics">Electronics</option>
+ </select>
+ {isLoading && <p>Updating results...</p>}
+ </fieldset>
+ )
+}
+```
+
+Reference: [nuqs useTransition Integration](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/setup-default-options.md b/.agents/skills/nuqs/references/setup-default-options.md
new file mode 100644
index 00000000..eefa1797
--- /dev/null
+++ b/.agents/skills/nuqs/references/setup-default-options.md
@@ -0,0 +1,71 @@
+---
+title: Configure App-Wide Defaults on NuqsAdapter
+impact: MEDIUM
+impactDescription: avoids repeating .withOptions on every parser; enforces consistent behaviour
+tags: setup, NuqsAdapter, defaultOptions, configuration, consistency
+---
+
+## Configure App-Wide Defaults on NuqsAdapter
+
+Since nuqs v2.5, `NuqsAdapter` accepts a `defaultOptions` prop. It takes exactly the serialisable options — `shallow`, `scroll`, `clearOnDefault`, `limitUrlUpdates`, and (since v2.9.0) `history`. Setting them once on the adapter eliminates the temptation to copy-paste the same `.withOptions({ … })` chain onto every parser, and reduces the chance one component silently disagrees with the rest of the app (e.g. one missing `shallow: false` that drops a server fetch). `startTransition` is **not** a `defaultOptions` key — it's a function from `useTransition()` and can only be passed per hook call.
+
+**Incorrect (every parser repeats the same options):**
+
+```tsx
+// Search page
+const [q] = useQueryState('q', parseAsString.withDefault('').withOptions({ shallow: false, scroll: false }))
+const [page] = useQueryState('page', parseAsInteger.withDefault(1).withOptions({ shallow: false, scroll: false }))
+
+// Filters page
+const [tag] = useQueryState('tag', parseAsString.withDefault('').withOptions({ shallow: false /* forgot scroll: false */ }))
+// Inconsistency: filter changes now scroll to top; search changes don't.
+```
+
+**Correct (set defaults once on the adapter):**
+
+```tsx
+// app/layout.tsx
+import { NuqsAdapter } from 'nuqs/adapters/next/app'
+
+export default function RootLayout({ children }: { children: React.ReactNode }) {
+ return (
+ <html>
+ <body>
+ <NuqsAdapter
+ defaultOptions={{
+ shallow: false, // Every URL change re-runs the server
+ scroll: false // Never auto-scroll on URL update
+ }}
+ >
+ {children}
+ </NuqsAdapter>
+ </body>
+ </html>
+ )
+}
+```
+
+```tsx
+// Anywhere in the tree — no per-parser duplication
+const [q] = useQueryState('q', parseAsString.withDefault(''))
+const [page] = useQueryState('page', parseAsInteger.withDefault(1))
+// Both inherit shallow: false, scroll: false from the adapter
+```
+
+**Per-hook overrides still work:**
+
+```tsx
+// A purely-local UI flag — opt out of the server round-trip just here
+const [drawerOpen, setDrawerOpen] = useQueryState(
+ 'drawer',
+ parseAsBoolean.withDefault(false).withOptions({ shallow: true })
+)
+```
+
+**Precedence (low → high):** built-in defaults → adapter `defaultOptions` → parser `.withOptions(…)` → per-call `setX(value, { … })`.
+
+**When NOT to use this pattern:**
+- The app has fewer than a handful of nuqs hooks — duplicating options is fine.
+- Different sections of the app legitimately want different defaults (e.g. an embedded widget vs. a full page) — split the tree into two adapters with their own `defaultOptions`.
+
+Reference: [nuqs 2.5 release notes](https://nuqs.dev/blog/nuqs-2.5)
diff --git a/.agents/skills/nuqs/references/setup-import-server.md b/.agents/skills/nuqs/references/setup-import-server.md
new file mode 100644
index 00000000..0e91af1f
--- /dev/null
+++ b/.agents/skills/nuqs/references/setup-import-server.md
@@ -0,0 +1,72 @@
+---
+title: Import Server Utilities from nuqs/server
+impact: CRITICAL
+impactDescription: prevents RSC-to-client boundary contamination errors
+tags: setup, nuqs/server, imports, createSearchParamsCache, server-components
+---
+
+## Import Server Utilities from nuqs/server
+
+Server-side utilities like `createSearchParamsCache` must be imported from `nuqs/server`, not `nuqs`. The main `nuqs` export includes the `'use client'` directive which contaminates Server Components.
+
+**Incorrect (wrong import):**
+
+```tsx
+// lib/searchParams.ts
+import { createSearchParamsCache, parseAsString } from 'nuqs'
+// Error: This import adds 'use client' to your server code
+
+export const searchParamsCache = createSearchParamsCache({
+ q: parseAsString.withDefault('')
+})
+```
+
+**Correct (server import):**
+
+```tsx
+// lib/searchParams.ts
+import {
+ createSearchParamsCache,
+ parseAsString,
+ parseAsInteger
+} from 'nuqs/server'
+// No 'use client' directive - safe for Server Components
+
+export const searchParamsCache = createSearchParamsCache({
+ q: parseAsString.withDefault(''),
+ page: parseAsInteger.withDefault(1)
+})
+```
+
+**Usage in Server Component:**
+
+```tsx
+// app/search/page.tsx
+import { searchParamsCache } from '@/lib/searchParams'
+import type { SearchParams } from 'nuqs/server'
+
+type PageProps = {
+ searchParams: Promise<SearchParams>
+}
+
+export default async function SearchPage({ searchParams }: PageProps) {
+ const { q, page } = await searchParamsCache.parse(searchParams)
+
+ return (
+ <div>
+ <h1>Results for: {q}</h1>
+ <p>Page: {page}</p>
+ </div>
+ )
+}
+```
+
+**What to import from where:**
+
+| Import | Source | Use In |
+|--------|--------|--------|
+| `useQueryState`, `useQueryStates` | `nuqs` | Client Components |
+| `createSearchParamsCache` | `nuqs/server` | Server Components |
+| Parsers (`parseAsString`, etc.) | `nuqs/server` for server, `nuqs` for client | Either |
+
+Reference: [nuqs Server-Side](https://nuqs.dev/docs/server-side)
diff --git a/.agents/skills/nuqs/references/setup-nextjs-version.md b/.agents/skills/nuqs/references/setup-nextjs-version.md
new file mode 100644
index 00000000..fc25cb3e
--- /dev/null
+++ b/.agents/skills/nuqs/references/setup-nextjs-version.md
@@ -0,0 +1,71 @@
+---
+title: Ensure Compatible Next.js Version
+impact: CRITICAL
+impactDescription: prevents cryptic runtime errors from version mismatch
+tags: setup, nextjs, version, compatibility, app-router
+---
+
+## Ensure Compatible Next.js Version
+
+`nuqs@^2` declares `next` as a peer dependency at `>=14.2.0` — the **same floor for both App and Pages routers**. There is no separate, lower minimum for the Pages Router; older tables that list `12.0.0` or `14.0.0` are wrong for v2. On Next.js below 14.2, install `nuqs@^1` instead. Using an unsupported combination surfaces as cryptic runtime errors, not a clean install failure.
+
+**Version Requirements (nuqs v2):**
+
+| Next.js | Support | Notes |
+|---------|---------|-------|
+| `< 14.2.0` | Not supported by nuqs v2 | Use `nuqs@^1` for these versions. |
+| `>= 14.2.0` | App & Pages routers | Minimum for `nuqs@^2` (both routers). |
+| `15.x` | App & Pages routers | `searchParams` is `Promise<SearchParams>` — must be `await`-ed. See `server-next15-async`. |
+| `16.x` (`cacheComponents`) | App router | Requires **nuqs `>= 2.9.0`** to avoid stale URL reads when Server Components are cached. Older nuqs returns outdated query values on revisit. |
+
+**Check your version:**
+
+```bash
+npm list next
+# or
+yarn why next
+# or
+pnpm why next
+```
+
+**Incorrect (outdated Next.js):**
+
+```json
+{
+ "dependencies": {
+ "next": "13.5.0",
+ "nuqs": "^2.0.0"
+ }
+}
+// May cause: "Cannot read property 'push' of undefined"
+// Or: URL updates not reflected
+```
+
+**Correct (compatible version):**
+
+```json
+{
+ "dependencies": {
+ "next": "14.2.0",
+ "nuqs": "^2.0.0"
+ }
+}
+```
+
+**Upgrade command:**
+
+```bash
+npm install next@latest
+# or
+yarn add next@latest
+# or
+pnpm add next@latest
+```
+
+**Common symptoms of version mismatch:**
+- `useQueryState` returns undefined
+- URL doesn't update on state change
+- Hydration mismatches
+- `TypeError: Cannot read property 'push' of undefined`
+
+Reference: [nuqs Installation](https://nuqs.dev/docs/installation)
diff --git a/.agents/skills/nuqs/references/setup-nuqs-adapter.md b/.agents/skills/nuqs/references/setup-nuqs-adapter.md
new file mode 100644
index 00000000..e778812b
--- /dev/null
+++ b/.agents/skills/nuqs/references/setup-nuqs-adapter.md
@@ -0,0 +1,81 @@
+---
+title: Wrap App with NuqsAdapter
+impact: CRITICAL
+impactDescription: prevents 100% of hook failures from missing provider
+tags: setup, NuqsAdapter, provider, app-router, pages-router
+---
+
+## Wrap App with NuqsAdapter
+
+nuqs requires the `NuqsAdapter` provider to function. Without it, `useQueryState` hooks won't sync with the URL and may throw errors.
+
+**Incorrect (missing adapter):**
+
+```tsx
+// src/app/layout.tsx
+export default function RootLayout({
+ children
+}: {
+ children: React.ReactNode
+}) {
+ return (
+ <html>
+ <body>{children}</body>
+ </html>
+ )
+}
+// useQueryState calls will fail silently or throw
+```
+
+**Correct (App Router):**
+
+```tsx
+// src/app/layout.tsx
+import { NuqsAdapter } from 'nuqs/adapters/next/app'
+
+export default function RootLayout({
+ children
+}: {
+ children: React.ReactNode
+}) {
+ return (
+ <html>
+ <body>
+ <NuqsAdapter>{children}</NuqsAdapter>
+ </body>
+ </html>
+ )
+}
+```
+
+**Correct (Pages Router):**
+
+```tsx
+// src/pages/_app.tsx
+import type { AppProps } from 'next/app'
+import { NuqsAdapter } from 'nuqs/adapters/next/pages'
+
+export default function MyApp({ Component, pageProps }: AppProps) {
+ return (
+ <NuqsAdapter>
+ <Component {...pageProps} />
+ </NuqsAdapter>
+ )
+}
+```
+
+**Available adapters (nuqs v2.9+):**
+- `nuqs/adapters/next/app` — Next.js App Router
+- `nuqs/adapters/next/pages` — Next.js Pages Router
+- `nuqs/adapters/next` — Next.js unified (mixed routers)
+- `nuqs/adapters/react` — Plain React (no router, e.g. Vite/CRA)
+- `nuqs/adapters/remix` — Remix
+- `nuqs/adapters/react-router/v6` — React Router v6
+- `nuqs/adapters/react-router/v7` — React Router v7
+- `nuqs/adapters/react-router/v8` — React Router v8 (added v2.9)
+- `nuqs/adapters/tanstack-router` — TanStack Router (added v2.5)
+- `nuqs/adapters/testing` — Tests (see `debug-testing`)
+
+The dedicated `react-router/v5` adapter subpath was removed in v2.9 — v5 apps import the unversioned `nuqs/adapters/react-router` (which still aliases v6) or upgrade. That bare alias is itself deprecated and slated for removal in v3, so pin `/v6`, `/v7`, or `/v8` explicitly.
+
+Reference: [nuqs Adapters](https://nuqs.dev/docs/adapters)
diff --git a/.agents/skills/nuqs/references/setup-shared-parsers.md b/.agents/skills/nuqs/references/setup-shared-parsers.md
new file mode 100644
index 00000000..03c4fd09
--- /dev/null
+++ b/.agents/skills/nuqs/references/setup-shared-parsers.md
@@ -0,0 +1,86 @@
+---
+title: Define Shared Parsers in Dedicated File
+impact: HIGH
+impactDescription: prevents parser mismatch bugs between components
+tags: setup, parsers, organization, reusability, consistency
+---
+
+## Define Shared Parsers in Dedicated File
+
+When multiple components use the same URL parameters, define parsers in a shared file. This prevents mismatches where one component uses `parseAsInteger` and another uses `parseAsString` for the same parameter.
+
+**Incorrect (duplicate parser definitions):**
+
+```tsx
+// components/Pagination.tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export function Pagination() {
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1))
+ return <button onClick={() => setPage(p => p + 1)}>Next</button>
+}
+
+// components/PageInfo.tsx
+'use client'
+import { useQueryState } from 'nuqs'
+
+export function PageInfo() {
+ const [page] = useQueryState('page') // String parser - mismatch!
+ return <span>Page: {page}</span> // Shows "1" not 1
+}
+```
+
+**Correct (shared parsers):**
+
+```tsx
+// lib/searchParams.ts
+import { parseAsInteger, parseAsString, parseAsStringLiteral } from 'nuqs'
+
+export const searchParams = {
+ page: parseAsInteger.withDefault(1),
+ query: parseAsString.withDefault(''),
+ sort: parseAsStringLiteral(['asc', 'desc'] as const).withDefault('asc')
+}
+
+// components/Pagination.tsx
+'use client'
+import { useQueryState } from 'nuqs'
+import { searchParams } from '@/lib/searchParams'
+
+export function Pagination() {
+ const [page, setPage] = useQueryState('page', searchParams.page)
+ return <button onClick={() => setPage(p => p + 1)}>Next</button>
+}
+
+// components/PageInfo.tsx
+'use client'
+import { useQueryState } from 'nuqs'
+import { searchParams } from '@/lib/searchParams'
+
+export function PageInfo() {
+ const [page] = useQueryState('page', searchParams.page)
+ return <span>Page: {page}</span> // Correctly typed as number
+}
+```
+
+**Share the same map between client and server:**
+
+The same parser map drives a Server Component's `createSearchParamsCache` (or `createLoader`) and a client `useQueryState`. Keep the server cache in its own module so `nuqs/server` never leaks into a client bundle, and import the parsers from a client-safe file:
+
+```tsx
+// lib/searchParams.server.ts — server-only
+import { createSearchParamsCache } from 'nuqs/server'
+import { searchParams } from './searchParams'
+
+export const searchParamsCache = createSearchParamsCache(searchParams)
+```
+
+A default that disagrees across the boundary (server `withDefault(1)`, client `withDefault(0)`) is a classic hydration mismatch — the shared map makes it impossible.
+
+**Benefits:**
+- Single source of truth for parser configuration
+- TypeScript catches mismatches at compile time
+- Easy to update defaults in one place
+
+Reference: [nuqs Documentation](https://nuqs.dev/docs)
diff --git a/.agents/skills/nuqs/references/setup-use-client.md b/.agents/skills/nuqs/references/setup-use-client.md
new file mode 100644
index 00000000..92172bad
--- /dev/null
+++ b/.agents/skills/nuqs/references/setup-use-client.md
@@ -0,0 +1,69 @@
+---
+title: Add 'use client' Directive for Hooks
+impact: CRITICAL
+impactDescription: prevents build-breaking hook errors in RSC
+tags: setup, use-client, server-components, client-components
+---
+
+## Add 'use client' Directive for Hooks
+
+`useQueryState` and `useQueryStates` are React hooks that require client-side rendering. Using them in Server Components causes build errors.
+
+**Incorrect (missing directive):**
+
+```tsx
+// app/search/page.tsx
+import { useQueryState } from 'nuqs'
+
+export default function SearchPage() {
+ const [query, setQuery] = useQueryState('q')
+ // Error: Hooks can only be called inside Client Components
+
+ return <input value={query ?? ''} onChange={e => setQuery(e.target.value)} />
+}
+```
+
+**Correct (client component):**
+
+```tsx
+// app/search/page.tsx
+'use client'
+
+import { useQueryState } from 'nuqs'
+
+export default function SearchPage() {
+ const [query, setQuery] = useQueryState('q')
+
+ return <input value={query ?? ''} onChange={e => setQuery(e.target.value)} />
+}
+```
+
+**Alternative (extract to client component):**
+
+```tsx
+// app/search/page.tsx (Server Component)
+import SearchInput from './SearchInput'
+
+export default function SearchPage() {
+ return (
+ <div>
+ <h1>Search</h1>
+ <SearchInput />
+ </div>
+ )
+}
+
+// app/search/SearchInput.tsx (Client Component)
+'use client'
+
+import { useQueryState } from 'nuqs'
+
+export default function SearchInput() {
+ const [query, setQuery] = useQueryState('q')
+ return <input value={query ?? ''} onChange={e => setQuery(e.target.value)} />
+}
+```
+
+**Note:** For reading search params in Server Components without hooks, use `createSearchParamsCache` from `nuqs/server`.
+
+Reference: [nuqs Server-Side](https://nuqs.dev/docs/server-side)
diff --git a/.agents/skills/nuqs/references/state-avoid-derived.md b/.agents/skills/nuqs/references/state-avoid-derived.md
new file mode 100644
index 00000000..a409cec2
--- /dev/null
+++ b/.agents/skills/nuqs/references/state-avoid-derived.md
@@ -0,0 +1,84 @@
+---
+title: Avoid Derived State from URL Parameters
+impact: HIGH
+impactDescription: prevents sync bugs and unnecessary re-renders
+tags: state, derived-state, anti-pattern, single-source-of-truth
+---
+
+## Avoid Derived State from URL Parameters
+
+Don't copy URL state into local `useState`. This creates two sources of truth that can drift out of sync. Use the URL state directly or compute derived values.
+
+**Incorrect (duplicated state):**
+
+```tsx
+'use client'
+import { useState, useEffect } from 'react'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [urlPage] = useQueryState('page', parseAsInteger.withDefault(1))
+ const [page, setPage] = useState(urlPage) // Duplicated!
+
+ useEffect(() => {
+ setPage(urlPage) // Sync attempt - can cause loops
+ }, [urlPage])
+
+ return <span>Page: {page}</span>
+}
+```
+
+**Correct (single source of truth):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1))
+
+ return <span>Page: {page}</span>
+}
+```
+
+**For derived values, use useMemo:**
+
+```tsx
+'use client'
+import { useMemo } from 'react'
+import { useQueryState, parseAsInteger } from 'nuqs'
+
+export default function Pagination() {
+ const [page] = useQueryState('page', parseAsInteger.withDefault(1))
+
+ // Derived value, not duplicated state
+ const isFirstPage = useMemo(() => page === 1, [page])
+ const pageRange = useMemo(
+ () => ({ start: (page - 1) * 10, end: page * 10 }),
+ [page]
+ )
+
+ return (
+ <div>
+ <span>Page: {page}</span>
+ {isFirstPage && <span>(First page)</span>}
+ </div>
+ )
+}
+```
+
+**Exception: Debounced input**
+
+```tsx
+// OK to have local state for debounced input
+const [query, setQuery] = useQueryState('q')
+const [inputValue, setInputValue] = useState(query ?? '')
+
+// Debounce URL updates
+useEffect(() => {
+ const timeout = setTimeout(() => setQuery(inputValue || null), 300)
+ return () => clearTimeout(timeout)
+}, [inputValue, setQuery])
+```
+
+Reference: [React Derived State](https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state)
diff --git a/.agents/skills/nuqs/references/state-clear-with-null.md b/.agents/skills/nuqs/references/state-clear-with-null.md
new file mode 100644
index 00000000..20085b1d
--- /dev/null
+++ b/.agents/skills/nuqs/references/state-clear-with-null.md
@@ -0,0 +1,81 @@
+---
+title: Clear URL Parameters with null
+impact: HIGH
+impactDescription: reduces URL clutter by removing unnecessary parameters
+tags: state, null, clear, url-cleanup, reset
+---
+
+## Clear URL Parameters with null
+
+To remove a parameter from the URL, set it to `null`. Setting to empty string (`''`) or `0` keeps the parameter in the URL with that value.
+
+**Incorrect (empty string in URL):**
+
+```tsx
+'use client'
+import { useQueryState } from 'nuqs'
+
+export default function SearchBox() {
+ const [query, setQuery] = useQueryState('q')
+
+ const clear = () => setQuery('')
+ // URL: ?q= (empty but parameter remains)
+
+ return (
+ <div>
+ <input value={query ?? ''} onChange={e => setQuery(e.target.value)} />
+ <button onClick={clear}>Clear</button>
+ </div>
+ )
+}
+```
+
+**Correct (null removes parameter):**
+
+```tsx
+'use client'
+import { useQueryState } from 'nuqs'
+
+export default function SearchBox() {
+ const [query, setQuery] = useQueryState('q')
+
+ const clear = () => setQuery(null)
+ // URL: / (parameter removed entirely)
+
+ return (
+ <div>
+ <input
+ value={query ?? ''}
+ onChange={e => setQuery(e.target.value || null)}
+ />
+ <button onClick={clear}>Clear</button>
+ </div>
+ )
+}
+```
+
+**Pattern: Convert empty to null on change:**
+
+```tsx
+<input
+ value={query ?? ''}
+ onChange={e => setQuery(e.target.value || null)}
+/>
+// Empty input → null → clean URL
+// "search term" → "search term" → ?q=search+term
+```
+
+**With typed parsers:**
+
+```tsx
+const [count, setCount] = useQueryState('count', parseAsInteger)
+
+// Clear the parameter
+setCount(null) // URL: /
+
+// With default, null resets to default behavior
+const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1))
+setPage(null) // URL: / (page defaults to 1, not shown)
+```
+
+Reference: [nuqs Documentation](https://nuqs.dev/docs)
diff --git a/.agents/skills/nuqs/references/state-options-inheritance.md b/.agents/skills/nuqs/references/state-options-inheritance.md
new file mode 100644
index 00000000..938ee495
--- /dev/null
+++ b/.agents/skills/nuqs/references/state-options-inheritance.md
@@ -0,0 +1,74 @@
+---
+title: Use withOptions for Parser-Level Configuration
+impact: MEDIUM
+impactDescription: reduces boilerplate and ensures consistent behavior
+tags: state, withOptions, configuration, parsers, reusability
+---
+
+## Use withOptions for Parser-Level Configuration
+
+Instead of passing options to every `useQueryState` call, configure options on the parser itself with `withOptions`. This ensures consistent behavior and reduces repetition.
+
+**Incorrect (options repeated at every call site):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString, throttle } from 'nuqs'
+
+export default function SearchPage() {
+ const [query, setQuery] = useQueryState(
+ 'q',
+ parseAsString.withDefault('').withOptions({ shallow: false, limitUrlUpdates: throttle(500), history: 'push' })
+ )
+
+ const [filter, setFilter] = useQueryState(
+ 'filter',
+ parseAsString.withDefault('').withOptions({ shallow: false, limitUrlUpdates: throttle(500), history: 'push' })
+ )
+
+ // Same option bag copy-pasted — one typo and the two keys drift apart
+}
+```
+
+**Correct (parser-level options):**
+
+```tsx
+// lib/searchParams.ts
+import { parseAsString, parseAsInteger, throttle } from 'nuqs'
+
+const serverSyncOptions = {
+ shallow: false,
+ limitUrlUpdates: throttle(500),
+ history: 'push' as const
+}
+
+export const searchParams = {
+ query: parseAsString.withDefault('').withOptions(serverSyncOptions),
+ filter: parseAsString.withDefault('').withOptions(serverSyncOptions),
+ page: parseAsInteger.withDefault(1).withOptions(serverSyncOptions)
+}
+
+// components/SearchPage.tsx
+'use client'
+import { useQueryState } from 'nuqs'
+import { searchParams } from '@/lib/searchParams'
+
+export default function SearchPage() {
+ const [query, setQuery] = useQueryState('q', searchParams.query)
+ const [filter, setFilter] = useQueryState('filter', searchParams.filter)
+ const [page, setPage] = useQueryState('page', searchParams.page)
+
+ // All use the same options consistently
+}
+```
+
+**Options can be chained:**
+
+```tsx
+parseAsInteger
+ .withDefault(1)
+ .withOptions({ shallow: false })
+ .withOptions({ limitUrlUpdates: throttle(300) }) // Merges with previous options
+```
+
+Reference: [nuqs Options](https://nuqs.dev/docs/options)
diff --git a/.agents/skills/nuqs/references/state-setter-return.md b/.agents/skills/nuqs/references/state-setter-return.md
new file mode 100644
index 00000000..8fafda4a
--- /dev/null
+++ b/.agents/skills/nuqs/references/state-setter-return.md
@@ -0,0 +1,84 @@
+---
+title: Use Setter Return Value for URL Access
+impact: MEDIUM
+impactDescription: enables accurate URL tracking for analytics/sharing without re-deriving the URL
+tags: state, setter, return-value, URLSearchParams, analytics
+---
+
+## Use Setter Return Value for URL Access
+
+The state setter returns a `Promise<URLSearchParams>` that resolves to the merged URL search params after the update is flushed. Use it whenever you need the resulting URL immediately (sharing, copy-to-clipboard, analytics) instead of re-deriving the URL by hand and risking drift from nuqs's own serialisation. Because it resolves to a `URLSearchParams` object, you must call `.toString()` when embedding it in a string.
+
+**Incorrect (manually reconstructing the URL):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function ShareButton() {
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
+
+ const share = () => {
+ setQuery('shared-term')
+ // Manual URL construction — drifts from nuqs's encoding (clearOnDefault, urlKeys, etc.)
+ const url = `${window.location.pathname}?q=shared-term`
+ navigator.clipboard.writeText(url)
+ }
+
+ return <button onClick={share}>Share</button>
+}
+```
+
+**Correct (use the awaited return value):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsString } from 'nuqs'
+
+export default function ShareButton() {
+ const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
+
+ const share = async () => {
+ const search = await setQuery('shared-term')
+ // search is URLSearchParams — call .toString() to embed in a URL.
+ const url = `${window.location.origin}${window.location.pathname}?${search.toString()}`
+ await navigator.clipboard.writeText(url)
+ }
+
+ return <button onClick={share}>Share</button>
+}
+```
+
+**For analytics:**
+
+```tsx
+const trackSearch = async (term: string) => {
+ const search = await setQuery(term)
+ analytics.track('search', {
+ term,
+ url: `?${search.toString()}`,
+ // You can also pull individual keys directly off URLSearchParams:
+ canonicalQuery: search.get('q')
+ })
+}
+```
+
+**With `useQueryStates` — merged params come back in one object:**
+
+```tsx
+const [coords, setCoords] = useQueryStates({
+ lat: parseAsFloat,
+ lng: parseAsFloat
+})
+
+const shareLocation = async () => {
+ const search = await setCoords({ lat: 48.8566, lng: 2.3522 })
+ // search.toString(): "lat=48.8566&lng=2.3522"
+}
+```
+
+**When NOT to use this pattern:**
+- You only need the local in-memory value — read it from the returned state, not the setter Promise.
+- You are inside Server Components — use `createSerializer` instead (see `perf-serialize-utility`).
+
+Reference: [nuqs Batching](https://nuqs.dev/docs/batching)
diff --git a/.agents/skills/nuqs/references/state-standard-schema.md b/.agents/skills/nuqs/references/state-standard-schema.md
new file mode 100644
index 00000000..4f8b3229
--- /dev/null
+++ b/.agents/skills/nuqs/references/state-standard-schema.md
@@ -0,0 +1,99 @@
+---
+title: Use Standard Schema for Cross-Library Validation
+impact: MEDIUM
+impactDescription: one parser map validates nuqs, tRPC, route validators, and forms — no duplicated schema
+tags: state, standard-schema, zod, valibot, trpc, validation
+---
+
+## Use Standard Schema for Cross-Library Validation
+
+Since nuqs v2.5, every `parseAsX` builder implements the [Standard Schema](https://standardschema.dev) interface, and `parseAsJson` accepts any Standard Schema validator (Zod, Valibot, ArkType, Effect Schema, …) directly in the validator slot. That means one parser map can drive **all of**: client-side `useQueryState`, server-side `createSearchParamsCache`/`createLoader`, tRPC procedure inputs, TanStack Router search-param validation, and form-level validation — without redefining the schema in three places.
+
+**Incorrect (shape defined in three places, drift inevitable):**
+
+```ts
+// lib/searchParams.ts
+import { parseAsString, parseAsInteger } from 'nuqs'
+export const searchParams = {
+ q: parseAsString.withDefault(''),
+ page: parseAsInteger.withDefault(1)
+}
+
+// server/trpc/search.ts
+import { z } from 'zod'
+export const searchInput = z.object({
+ q: z.string().default(''),
+ page: z.number().int().default(1) // Default '1' here, '0' somewhere else — bug waiting to happen
+})
+
+// server/route-validator.ts
+export function validateSearch(v: unknown) {
+ // Hand-rolled — drifts from both of the above
+}
+```
+
+**Correct (one nuqs parser map, consumed everywhere via Standard Schema):**
+
+```ts
+// lib/searchParams.ts
+import { parseAsString, parseAsInteger, createStandardSchemaV1 } from 'nuqs'
+
+export const searchParamsMap = {
+ q: parseAsString.withDefault(''),
+ page: parseAsInteger.withDefault(1)
+}
+
+// Expose the same map as a Standard Schema for any v1-compatible consumer
+export const searchParamsSchema = createStandardSchemaV1(searchParamsMap)
+```
+
+```ts
+// server/trpc/search.ts — tRPC v11 accepts Standard Schemas
+import { publicProcedure } from '@/server/trpc'
+import { searchParamsSchema } from '@/lib/searchParams'
+
+export const search = publicProcedure
+ .input(searchParamsSchema)
+ .query(({ input }) => {
+ // input is { q: string; page: number }
+ return runSearch(input.q, input.page)
+ })
+```
+
+```tsx
+// app/search/page.tsx (client) — same map
+'use client'
+import { useQueryStates } from 'nuqs'
+import { searchParamsMap } from '@/lib/searchParams'
+
+export default function Filters() {
+ const [{ q, page }, setSearch] = useQueryStates(searchParamsMap)
+ return <SearchUI q={q} page={page} onChange={setSearch} />
+}
+```
+
+**Using a Standard Schema library inside `parseAsJson`:**
+
+`parseAsJson` accepts any Standard Schema validator directly — Zod 4+, Valibot 0.30+, ArkType, and Effect Schema all qualify.
+
+```tsx
+import { z } from 'zod'
+import { parseAsJson, useQueryState } from 'nuqs'
+
+const FiltersSchema = z.object({
+ minPrice: z.number(),
+ categories: z.array(z.string())
+})
+
+const [filters] = useQueryState(
+ 'filters',
+ parseAsJson(FiltersSchema).withDefault({ minPrice: 0, categories: [] })
+)
+// Invalid JSON → null → falls back to the default
+```
+
+**When NOT to use this pattern:**
+- The shape only lives in one file and one consumer — keep it simple with plain parsers; the Standard Schema indirection adds zero value.
+- You're on nuqs < 2.5 — `createStandardSchemaV1` doesn't exist there. Either upgrade or write the bridge by hand.
+
+Reference: [nuqs 2.5 release notes](https://nuqs.dev/blog/nuqs-2.5)
diff --git a/.agents/skills/nuqs/references/state-use-query-states.md b/.agents/skills/nuqs/references/state-use-query-states.md
new file mode 100644
index 00000000..1833eda6
--- /dev/null
+++ b/.agents/skills/nuqs/references/state-use-query-states.md
@@ -0,0 +1,74 @@
+---
+title: Use useQueryStates for Related Parameters
+impact: HIGH
+impactDescription: gives a single typed object and one combined URLSearchParams flush
+tags: state, useQueryStates, batching, atomic, related-params
+---
+
+## Use useQueryStates for Related Parameters
+
+When multiple URL parameters are logically related (coordinates, date ranges, filter sets), prefer `useQueryStates` over a tower of `useQueryState` calls. nuqs already batches sibling setter calls within the same event-loop tick into a single URL flush, so the win isn't "fewer history entries" — it's a single typed state object, a single combined update payload, and a single returned `URLSearchParams` you can inspect for the merged result.
+
+**Incorrect (one hook per parameter):**
+
+```tsx
+'use client'
+import { useQueryState, parseAsFloat, parseAsInteger } from 'nuqs'
+
+export default function MapView() {
+ const [lat, setLat] = useQueryState('lat', parseAsFloat.withDefault(0))
+ const [lng, setLng] = useQueryState('lng', parseAsFloat.withDefault(0))
+ const [zoom, setZoom] = useQueryState('zoom', parseAsInteger.withDefault(10))
+
+ const goToParis = () => {
+ setLat(48.8566)
+ setLng(2.3522)
+ setZoom(12)
+ // Three setters, three places to keep in sync.
+ // Each setter resolves to its own URLSearchParams Promise — no single object holding the merged result.
+ }
+
+ return <button onClick={goToParis}>Go to Paris</button>
+}
+```
+
+**Correct (one hook, one atomic update):**
+
+```tsx
+'use client'
+import { useQueryStates, parseAsFloat, parseAsInteger } from 'nuqs'
+
+export default function MapView() {
+ const [coords, setCoords] = useQueryStates({
+ lat: parseAsFloat.withDefault(0),
+ lng: parseAsFloat.withDefault(0),
+ zoom: parseAsInteger.withDefault(10)
+ })
+
+ const goToParis = async () => {
+ const search = await setCoords({ lat: 48.8566, lng: 2.3522, zoom: 12 })
+ // search: URLSearchParams with all three keys merged
+ }
+
+ return (
+ <div>
+ <p>Location: {coords.lat}, {coords.lng} (zoom: {coords.zoom})</p>
+ <button onClick={goToParis}>Go to Paris</button>
+ </div>
+ )
+}
+```
+
+**Partial updates and clearing:**
+
+```tsx
+setCoords({ zoom: 15 }) // Update only zoom; lat/lng untouched
+setCoords({ lat: 51.5074, lng: -0.1278 }) // Update lat/lng; keep zoom
+setCoords(null) // Clear every key in the object
+```
+
+**When NOT to use this pattern:**
+- Parameters belong to unrelated UI surfaces (e.g., a sidebar filter vs. an unrelated pagination control) — coupling them in one hook causes unnecessary re-renders of components that only need one key.
+- Non-Next.js adapters (v2.5+) automatically scope re-renders to specific keys when you use `useQueryState`, so splitting into independent hooks can actually be faster for re-render-sensitive trees. See `perf-avoid-rerender`.
+
+Reference: [nuqs Batching](https://nuqs.dev/docs/batching)
diff --git a/.agents/skills/prisma-database-setup/SKILL.md b/.agents/skills/prisma-database-setup/SKILL.md
new file mode 100644
index 00000000..51643e74
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/SKILL.md
@@ -0,0 +1,192 @@
+---
+name: prisma-database-setup
+description: Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.). Use when setting up a new project, changing databases, or troubleshooting connection issues. Triggers on "configure postgres", "connect to mysql", "setup mongodb", "sqlite setup".
+license: MIT
+metadata:
+ author: prisma
+ version: "7.6.0"
+---
+
+# Prisma Database Setup
+
+Comprehensive guides for configuring Prisma ORM with various database providers.
+
+## When to Apply
+
+Reference this skill when:
+- Initializing a new Prisma project
+- Switching database providers
+- Configuring connection strings and environment variables
+- Troubleshooting database connection issues
+- Setting up database-specific features
+- Generating and instantiating Prisma Client
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Provider Guides | CRITICAL | provider names |
+| 2 | Prisma Postgres | HIGH | `prisma-postgres` |
+| 3 | Client Setup | CRITICAL | `prisma-client-setup` |
+
+## System Prerequisites
+
+- **Node.js 20.19.0+**
+- **TypeScript 5.4.0+**
+
+## Bun Runtime
+
+If you're using Bun, run Prisma CLI commands with `bunx --bun prisma ...` so Prisma uses the Bun runtime instead of falling back to Node.js.
+
+## Supported Databases
+
+| Database | Provider String | Notes |
+|----------|-----------------|-------|
+| PostgreSQL | `postgresql` | Default, full feature support |
+| MySQL | `mysql` | Widespread support, some JSON diffs |
+| SQLite | `sqlite` | Local file-based, no enum/scalar lists |
+| MongoDB | `mongodb` | Mongo-specific workflow; do not apply SQL driver-adapter guidance |
+| SQL Server | `sqlserver` | Microsoft ecosystem |
+| CockroachDB | `cockroachdb` | Distributed SQL, Postgres-compatible |
+| Prisma Postgres | `postgresql` | Managed serverless database |
+
+## Configuration Files
+
+Your configuration shape depends on the provider and Prisma major version:
+
+1. **All providers** use **`prisma/schema.prisma`**.
+2. **Prisma 7 SQL setups** typically use **`prisma.config.ts`** for datasource URLs.
+3. **MongoDB projects should stay on Prisma 6.x**, keep `url = env("DATABASE_URL")` in the schema, and continue using the classic MongoDB setup.
+
+## Driver Adapters
+
+The standard SQL workflow uses a driver adapter. Choose the adapter and driver for your database and pass the adapter to `PrismaClient`.
+
+| Database | Adapter | JS Driver |
+|----------|---------|-----------|
+| PostgreSQL | `@prisma/adapter-pg` | `pg` |
+| CockroachDB | `@prisma/adapter-pg` | `pg` |
+| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
+| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
+| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
+| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
+| SQLite (Turso/LibSQL) | `@prisma/adapter-libsql` | `@libsql/client` |
+| SQL Server | `@prisma/adapter-mssql` | `node-mssql` |
+
+MongoDB should not follow the Prisma 7 SQL adapter workflow. Use the latest Prisma 6.x release for MongoDB projects and do not install a SQL `@prisma/adapter-*` package for it.
+
+Example (PostgreSQL):
+
+```ts
+import 'dotenv/config'
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+const prisma = new PrismaClient({ adapter })
+```
+
+## Prisma Client Setup (Required)
+
+Prisma Client must be installed and generated for any database.
+
+1. Install Prisma CLI and Prisma Client:
+ ```bash
+ npm install prisma --save-dev
+ npm install @prisma/client
+ ```
+
+1. Add a generator block (`prisma-client` requires an explicit output path):
+ ```prisma
+ generator client {
+ provider = "prisma-client"
+ output = "../generated"
+ }
+ ```
+
+1. Generate Prisma Client:
+ ```bash
+ npx prisma generate
+ ```
+
+1. For SQL providers, instantiate Prisma Client with the database-specific driver adapter:
+ ```typescript
+ import { PrismaClient } from '../generated/client'
+ import { PrismaPg } from '@prisma/adapter-pg'
+
+ const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+1. Re-run `prisma generate` after every schema change.
+
+## Quick Reference
+
+### PostgreSQL
+```prisma
+datasource db {
+ provider = "postgresql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+### MySQL
+```prisma
+datasource db {
+ provider = "mysql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+### SQLite
+```prisma
+datasource db {
+ provider = "sqlite"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+### MongoDB
+```prisma
+datasource db {
+ provider = "mongodb"
+ url = env("DATABASE_URL")
+}
+
+generator client {
+ provider = "prisma-client-js"
+}
+```
+
+For MongoDB, stay on the latest Prisma 6.x line and keep the connection URL in `schema.prisma`. Do not move a MongoDB project to the Prisma 7 SQL adapter setup. If a MongoDB project asks about upgrading Prisma versions, route to the `prisma-mongodb-upgrade` skill (stay-on-v6 vs Prisma Next is the real decision; Prisma 7 is not an option).
+
+## Rule Files
+
+See individual rule files for detailed setup instructions:
+
+```
+references/postgresql.md
+references/mysql.md
+references/sqlite.md
+references/mongodb.md
+references/sqlserver.md
+references/cockroachdb.md
+references/prisma-postgres.md
+references/prisma-client-setup.md
+```
+
+## How to Use
+
+Choose the provider reference file for your database, then apply `references/prisma-client-setup.md` to complete client generation and adapter setup. For MongoDB, use `references/mongodb.md` instead of copying the SQL adapter examples or Prisma 7 config pattern.
diff --git a/.agents/skills/prisma-database-setup/references/cockroachdb.md b/.agents/skills/prisma-database-setup/references/cockroachdb.md
new file mode 100644
index 00000000..38d38597
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/references/cockroachdb.md
@@ -0,0 +1,89 @@
+# CockroachDB Setup
+
+Configure Prisma with CockroachDB.
+
+## Prerequisites
+
+- CockroachDB cluster
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "cockroachdb"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="postgresql://user:password@host:26257/db?sslmode=verify-full"
+```
+
+Note: CockroachDB uses the PostgreSQL wire protocol, so the URL often looks like postgresql, but the provider **MUST** be `cockroachdb` in the schema to handle specific CRDB features correctly.
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow. CockroachDB is PostgreSQL-compatible, so use the PostgreSQL adapter.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-pg pg
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaPg } from '@prisma/adapter-pg'
+
+ const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## ID Generation
+
+CockroachDB uses `BigInt` or `UUID` for IDs efficiently.
+
+```prisma
+model User {
+ id BigInt @id @default(autoincrement()) // Uses unique_rowid()
+}
+```
+
+Or using string UUIDs:
+
+```prisma
+model User {
+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+}
+```
+
+## Common Issues
+
+### Schema Introspection
+Always use `provider = "cockroachdb"` to ensure correct type mapping during `db pull`.
diff --git a/.agents/skills/prisma-database-setup/references/mongodb.md b/.agents/skills/prisma-database-setup/references/mongodb.md
new file mode 100644
index 00000000..29dc2a0e
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/references/mongodb.md
@@ -0,0 +1,90 @@
+# MongoDB Setup
+
+MongoDB projects should stay on the latest Prisma 6.x release. Do not upgrade a MongoDB app to Prisma 7's SQL client path.
+
+## Prerequisites
+
+- MongoDB 4.2+
+- Replica Set configured (required for transactions)
+- Latest Prisma 6.x release, or your team's pinned Prisma 6 version
+- Node.js 20.19.0+
+- TypeScript 5.4.0+
+
+## 1. Schema Configuration
+
+Use the standard Prisma 6 MongoDB setup with `prisma-client-js`.
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "mongodb"
+ url = env("DATABASE_URL")
+}
+
+generator client {
+ provider = "prisma-client-js"
+}
+```
+
+### Driver Adapters
+
+Do **not** apply the Prisma 7 SQL adapter setup here. MongoDB does not use a SQL `@prisma/adapter-*` package.
+
+### ID Field Requirement
+
+MongoDB models **must** have a mapped `_id` field using `@id` and `@map("_id")`, usually of type `String` with `auto()` and `db.ObjectId`.
+
+```prisma
+model User {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ email String @unique
+ name String?
+}
+```
+
+### Relations
+
+Relations in MongoDB expect IDs to be `db.ObjectId` type.
+
+```prisma
+model Post {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ author User @relation(fields: [authorId], references: [id])
+ authorId String @db.ObjectId
+}
+```
+
+## 2. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="mongodb+srv://user:[email protected]/mydb?retryWrites=true&w=majority"
+```
+
+## Migrations vs Introspection
+
+- **No Migrations**: MongoDB is schema-less. `prisma migrate` commands **do not work**.
+- **db push**: Use `prisma db push` to sync indexes and constraints.
+- **db pull**: Use `prisma db pull` to generate schema from existing data (sampling).
+
+## Current Verification Notes
+
+- `prisma init --datasource-provider mongodb` is still implemented in Prisma's CLI source.
+- Prisma's upstream repo still contains MongoDB fixtures and tests.
+- Local verification shows Prisma 7 can still recognize MongoDB inputs, but the generated client path does not provide a supported MongoDB upgrade path.
+- Local verification shows Prisma 6.x works end to end with `prisma-client-js`, `prisma db push`, and `new PrismaClient()` against a MongoDB replica set.
+
+## Version Guidance
+
+- For MongoDB, stay on the latest available Prisma 6.x release.
+- Treat Prisma 7 MongoDB migration attempts as unsupported until Prisma ships a real MongoDB upgrade path.
+
+## Common Issues
+
+### "Transactions not supported"
+Ensure your MongoDB instance is a **Replica Set**. Standalone instances do not support transactions. Atlas clusters are replica sets by default.
+
+### "Invalid ObjectID"
+Ensure fields referencing IDs are decorated with `@db.ObjectId` if the target is an ObjectID.
diff --git a/.agents/skills/prisma-database-setup/references/mysql.md b/.agents/skills/prisma-database-setup/references/mysql.md
new file mode 100644
index 00000000..eb67b186
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/references/mysql.md
@@ -0,0 +1,126 @@
+# MySQL Setup
+
+Configure Prisma with MySQL (or MariaDB).
+
+## Prerequisites
+
+- MySQL or MariaDB database
+- Connection string
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "mysql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="mysql://user:password@localhost:3306/mydb"
+```
+
+### Connection String Format
+
+```
+mysql://USER:PASSWORD@HOST:PORT/DATABASE
+```
+
+- **USER**: Database user
+- **PASSWORD**: Password
+- **HOST**: Hostname
+- **PORT**: Port (default 3306)
+- **DATABASE**: Database name
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-mariadb mariadb
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaMariaDb } from '@prisma/adapter-mariadb'
+
+ const adapter = new PrismaMariaDb({
+ host: 'localhost',
+ port: 3306,
+ connectionLimit: 5,
+ user: process.env.MYSQL_USER,
+ password: process.env.MYSQL_PASSWORD,
+ database: process.env.MYSQL_DATABASE,
+ })
+
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+### Text protocol option
+
+If you need the MariaDB driver's text protocol instead of the default binary `execute()` path, enable `useTextProtocol` explicitly:
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaMariaDb } from '@prisma/adapter-mariadb'
+
+const adapter = new PrismaMariaDb(process.env.DATABASE_URL!, {
+ useTextProtocol: true,
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+Use this only when you specifically need text-protocol compatibility for your MariaDB setup.
+
+## PlanetScale Setup
+
+PlanetScale uses MySQL but requires specific settings because it doesn't support foreign key constraints.
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "mysql"
+ relationMode = "prisma" // Emulate foreign keys in Prisma
+}
+```
+
+## Common Issues
+
+### "Too many connections"
+MySQL has a connection limit. Adjust connection pool size in URL:
+```env
+DATABASE_URL="mysql://...?connection_limit=5"
+```
+
+### JSON Support
+MySQL 5.7+ supports JSON. MariaDB 10.2+ supports JSON (as an alias for LONGTEXT with check constraints). Prisma handles this, but verify your version.
diff --git a/.agents/skills/prisma-database-setup/references/postgresql.md b/.agents/skills/prisma-database-setup/references/postgresql.md
new file mode 100644
index 00000000..ea575f68
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/references/postgresql.md
@@ -0,0 +1,92 @@
+# PostgreSQL Setup
+
+Configure Prisma with PostgreSQL.
+
+## Prerequisites
+
+- PostgreSQL database (local or cloud)
+- Connection string
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "postgresql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
+```
+
+### Connection String Format
+
+```
+postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA
+```
+
+- **USER**: Database user
+- **PASSWORD**: Password (URL encoded if special chars)
+- **HOST**: Hostname (localhost, IP, or domain)
+- **PORT**: Port (default 5432)
+- **DATABASE**: Database name
+- **SCHEMA**: Schema name (default `public`)
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-pg pg
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaPg } from '@prisma/adapter-pg'
+
+ const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## Common Issues
+
+### "Can't reach database server"
+- Check host and port
+- Check firewall settings
+- Ensure database is running
+
+### "Authentication failed"
+- Check user/password
+- Special characters in password must be URL-encoded
+
+### "Schema does not exist"
+- Ensure `?schema=public` (or your schema) is in the URL
diff --git a/.agents/skills/prisma-database-setup/references/prisma-client-setup.md b/.agents/skills/prisma-database-setup/references/prisma-client-setup.md
new file mode 100644
index 00000000..bb369322
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/references/prisma-client-setup.md
@@ -0,0 +1,47 @@
+# Prisma Client Setup
+
+Generate and instantiate Prisma Client for Prisma's standard SQL provider workflow. For MongoDB, follow the provider-specific notes in `references/mongodb.md` instead of copying the SQL adapter example below.
+
+## 1. Install dependencies
+
+```bash
+npm install prisma --save-dev
+npm install @prisma/client
+```
+
+## 2. Add generator block
+
+In `prisma/schema.prisma`:
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+`prisma-client` requires an explicit `output` path and does not generate into `node_modules` by default.
+
+## 3. Generate Prisma Client
+
+```bash
+npx prisma generate
+```
+
+Re-run `prisma generate` after every schema change to keep the client in sync.
+
+## 4. Instantiate Prisma Client
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+const prisma = new PrismaClient({ adapter })
+```
+
+If you change the generator `output`, update the import path to match. For the SQL provider workflow, replace `PrismaPg` with the adapter for your database.
+
+## 5. Use a single instance
+
+Each `PrismaClient` instance creates a connection pool. Reuse a single instance per app process to avoid exhausting database connections.
diff --git a/.agents/skills/prisma-database-setup/references/prisma-postgres.md b/.agents/skills/prisma-database-setup/references/prisma-postgres.md
new file mode 100644
index 00000000..dc939e5d
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/references/prisma-postgres.md
@@ -0,0 +1,130 @@
+# Prisma Postgres Setup
+
+Configure Prisma with Prisma Postgres (Managed).
+
+## Overview
+
+Prisma Postgres is a serverless, managed PostgreSQL database optimized for Prisma.
+
+## Setup via CLI
+
+You can provision a Prisma Postgres instance directly via the CLI:
+
+```bash
+prisma init --db
+```
+
+This will:
+1. Log you into Prisma Data Platform.
+2. Create a new project and database instance.
+3. Update your `.env` with the connection string.
+
+## Connection String
+
+For Prisma CLI flows and Accelerate-style usage, you may see a `prisma+postgres://` URL.
+
+For Prisma Client with a driver adapter in Node.js, prefer the direct TCP connection string from the Prisma Postgres dashboard:
+
+```env
+DATABASE_URL="postgres://identifier:[email protected]:5432/postgres?sslmode=require"
+```
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "postgresql" // Use postgresql provider
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Driver Adapter
+
+Use a driver adapter for Prisma Postgres in the standard SQL workflow.
+
+### Recommended for standard Node.js apps
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-pg pg
+ ```
+
+2. Use the direct TCP connection string from Prisma Console:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaPg } from '@prisma/adapter-pg'
+
+ const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+`PrismaPg` also accepts the connection string directly:
+
+```typescript
+const adapter = new PrismaPg(process.env.DATABASE_URL!)
+const prisma = new PrismaClient({ adapter })
+```
+
+For PostgreSQL prepared statement naming, pass adapter options as the second argument:
+
+```typescript
+import { createHash } from 'node:crypto'
+
+const adapter = new PrismaPg(process.env.DATABASE_URL!, {
+ statementNameGenerator: ({ sql }) =>
+ `prisma_${createHash('sha1').update(sql).digest('hex').slice(0, 16)}`,
+})
+```
+
+### Edge/serverless option
+
+Use the Prisma Postgres serverless driver only when you need HTTP/WebSocket transport in environments like Workers or Edge Functions:
+
+```bash
+npm install @prisma/adapter-ppg @prisma/ppg
+```
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
+
+const prisma = new PrismaClient({
+ adapter: new PrismaPostgresAdapter({
+ connectionString: process.env.PRISMA_DIRECT_TCP_URL,
+ }),
+})
+```
+
+This serverless driver is the specialized path for HTTP/WebSocket-based edge and serverless runtimes, not the default recommendation for standard Node.js apps.
+
+## Features
+
+- **Serverless**: Scales to zero.
+- **Caching**: Integrated query caching (Accelerate).
+- **Real-time**: Database events (Pulse).
+
+## Using with Prisma Client
+
+Use the Prisma Postgres adapter shown above when instantiating Prisma Client.
diff --git a/.agents/skills/prisma-database-setup/references/sqlite.md b/.agents/skills/prisma-database-setup/references/sqlite.md
new file mode 100644
index 00000000..30e3e004
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/references/sqlite.md
@@ -0,0 +1,106 @@
+# SQLite Setup
+
+Configure Prisma with SQLite.
+
+## Prerequisites
+
+- None (file-based)
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "sqlite"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="file:./dev.db"
+```
+
+### Connection String Format
+
+```
+file:PATH
+```
+
+- **PATH**: Relative path to the database file. Check `prisma.config.ts` if you need to confirm how your app resolves it.
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-better-sqlite3 better-sqlite3
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import { PrismaClient } from '../generated/client'
+ import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
+
+ const adapter = new PrismaBetterSqlite3({
+ url: process.env.DATABASE_URL ?? 'file:./dev.db',
+ })
+
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## Using Driver Adapter (LibSQL / Turso)
+
+For edge compatibility or Turso:
+
+1. Install:
+ ```bash
+ npm install @prisma/adapter-libsql @libsql/client
+ ```
+
+2. Instantiate:
+ ```typescript
+ import { PrismaClient } from '../generated/client'
+ import { PrismaLibSql } from '@prisma/adapter-libsql'
+
+ const adapter = new PrismaLibSql({
+ url: process.env.TURSO_DATABASE_URL,
+ authToken: process.env.TURSO_AUTH_TOKEN,
+ })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## Limitations
+
+- **No Enums**: SQLite doesn't support enums (Prisma polyfills them or treats as String).
+- **No Scalar Lists**: `String[]` is not supported directly.
+- **Concurrency**: Write operations lock the file.
+
+## Common Issues
+
+### "Database file not found"
+Ensure the path in `DATABASE_URL` is correct relative to where Prisma is running or the schema file. `file:./dev.db` creates it next to schema.
diff --git a/.agents/skills/prisma-database-setup/references/sqlserver.md b/.agents/skills/prisma-database-setup/references/sqlserver.md
new file mode 100644
index 00000000..b519d95b
--- /dev/null
+++ b/.agents/skills/prisma-database-setup/references/sqlserver.md
@@ -0,0 +1,94 @@
+# SQL Server Setup
+
+Configure Prisma with Microsoft SQL Server.
+
+## Prerequisites
+
+- SQL Server 2017, 2019, 2022, or Azure SQL
+- TCP/IP enabled
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "sqlserver"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=Password123;encrypt=true;trustServerCertificate=true"
+```
+
+### Connection String Format
+
+```
+sqlserver://HOST:PORT;database=DB;user=USER;password=PASS;encrypt=true;trustServerCertificate=true
+```
+
+- **encrypt**: Required for Azure (true).
+- **trustServerCertificate**: True for self-signed certs (local dev).
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-mssql mssql
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaMssql } from '@prisma/adapter-mssql'
+
+ const adapter = new PrismaMssql({
+ server: 'localhost',
+ port: 1433,
+ database: 'mydb',
+ user: process.env.SQLSERVER_USER,
+ password: process.env.SQLSERVER_PASSWORD,
+ options: {
+ encrypt: true,
+ trustServerCertificate: true,
+ },
+ })
+
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## Common Issues
+
+### "Login failed for user"
+- SQL Server auth vs Windows auth. Prisma typically uses SQL Server authentication (username/password).
+- Ensure TCP/IP is enabled in SQL Server Configuration Manager.
+
+### "Table not found" (dbo schema)
+Prisma assumes `dbo` schema by default. If using another schema, update the model or connection string? SQL Server provider mostly sticks to default schema.
diff --git a/.agents/skills/shadcn/SKILL.md b/.agents/skills/shadcn/SKILL.md
new file mode 100644
index 00000000..1b4c414c
--- /dev/null
+++ b/.agents/skills/shadcn/SKILL.md
@@ -0,0 +1,277 @@
+---
+name: shadcn
+description: Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".
+user-invocable: false
+allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
+---
+
+# shadcn/ui
+
+A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
+
+> **IMPORTANT:** Run all CLI commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest` — based on the project's `packageManager`. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
+
+## Current Project Context
+
+```json
+!`npx shadcn@latest info --json`
+```
+
+The JSON above contains the project config and installed components. Use `npx shadcn@latest docs <component>` to get documentation and example URLs for any component.
+
+## Principles
+
+1. **Use existing components first.** Use `npx shadcn@latest search` to check registries before writing custom UI. Check community registries too.
+2. **Compose, don't reinvent.** Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.
+3. **Use built-in variants before custom styles.** `variant="outline"`, `size="sm"`, etc.
+4. **Use semantic colors.** `bg-primary`, `text-muted-foreground` — never raw values like `bg-blue-500`.
+
+## Critical Rules
+
+These rules are **always enforced**. Each links to a file with Incorrect/Correct code pairs.
+
+### Styling & Tailwind → [styling.md](./rules/styling.md)
+
+- **`className` for layout, not styling.** Never override component colors or typography.
+- **No `space-x-*` or `space-y-*`.** Use `flex` with `gap-*`. For vertical stacks, `flex flex-col gap-*`.
+- **Use `size-*` when width and height are equal.** `size-10` not `w-10 h-10`.
+- **Use `truncate` shorthand.** Not `overflow-hidden text-ellipsis whitespace-nowrap`.
+- **No manual `dark:` color overrides.** Use semantic tokens (`bg-background`, `text-muted-foreground`).
+- **Use `cn()` for conditional classes.** Don't write manual template literal ternaries.
+- **No manual `z-index` on overlay components.** Dialog, Sheet, Popover, etc. handle their own stacking.
+
+### Forms & Inputs → [forms.md](./rules/forms.md)
+
+- **Forms use `FieldGroup` + `Field`.** Never use raw `div` with `space-y-*` or `grid gap-*` for form layout.
+- **`InputGroup` uses `InputGroupInput`/`InputGroupTextarea`.** Never raw `Input`/`Textarea` inside `InputGroup`.
+- **Buttons inside inputs use `InputGroup` + `InputGroupAddon`.**
+- **Option sets (2–7 choices) use `ToggleGroup`.** Don't loop `Button` with manual active state.
+- **`FieldSet` + `FieldLegend` for grouping related checkboxes/radios.** Don't use a `div` with a heading.
+- **Field validation uses `data-invalid` + `aria-invalid`.** `data-invalid` on `Field`, `aria-invalid` on the control. For disabled: `data-disabled` on `Field`, `disabled` on the control.
+
+### Component Structure → [composition.md](./rules/composition.md)
+
+- **Items always inside their Group.** `SelectItem` → `SelectGroup`. `DropdownMenuItem` → `DropdownMenuGroup`. `CommandItem` → `CommandGroup`.
+- **Use `asChild` (radix) or `render` (base) for custom triggers.** Check `base` field from `npx shadcn@latest info`. → [base-vs-radix.md](./rules/base-vs-radix.md)
+- **Dialog, Sheet, and Drawer always need a Title.** `DialogTitle`, `SheetTitle`, `DrawerTitle` required for accessibility. Use `className="sr-only"` if visually hidden.
+- **Use full Card composition.** `CardHeader`/`CardTitle`/`CardDescription`/`CardContent`/`CardFooter`. Don't dump everything in `CardContent`.
+- **Button has no `isPending`/`isLoading`.** Compose with `Spinner` + `data-icon` + `disabled`.
+- **`TabsTrigger` must be inside `TabsList`.** Never render triggers directly in `Tabs`.
+- **`Avatar` always needs `AvatarFallback`.** For when the image fails to load.
+
+### Use Components, Not Custom Markup → [composition.md](./rules/composition.md)
+
+- **Use existing components before custom markup.** Check if a component exists before writing a styled `div`.
+- **Callouts use `Alert`.** Don't build custom styled divs.
+- **Empty states use `Empty`.** Don't build custom empty state markup.
+- **Toast follows the project base.** Use `toast` from the `toast` component for
+ Base UI projects. Use `toast()` from `sonner` for Radix and React Aria
+ projects.
+- **Use `Separator`** instead of `<hr>` or `<div className="border-t">`.
+- **Use `Skeleton`** for loading placeholders. No custom `animate-pulse` divs.
+- **Use `Badge`** instead of custom styled spans.
+
+### Icons → [icons.md](./rules/icons.md)
+
+- **Icons in `Button` use `data-icon`.** `data-icon="inline-start"` or `data-icon="inline-end"` on the icon.
+- **No sizing classes on icons inside components.** Components handle icon sizing via CSS. No `size-4` or `w-4 h-4`.
+- **Pass icons as objects, not string keys.** `icon={CheckIcon}`, not a string lookup.
+
+### Chat & Messaging → [chat.md](./rules/chat.md)
+
+- **Chat UI composes the chat primitives.** Conversations use `MessageScroller`, rows use `Message`, surfaces use `Bubble`. Never hand-rolled bubble `div`s or a raw scroll container.
+- **`MessageScroller` owns scroll behavior.** Streaming follow, anchoring, and jump-to-latest (`MessageScrollerButton`) are built in. Don't write a `useStickToBottom`/`ResizeObserver` hook.
+- **Attachments use `Attachment`; system notes and dividers use `Marker`.** Not `Item` cards or `Separator` + a label.
+
+### CLI
+
+- **Never decode preset codes or build preset URLs manually.** Use `npx shadcn@latest preset decode <code>`, `preset url <code>`, or `preset open <code>`. For project-aware preset detection, use `npx shadcn@latest preset resolve`.
+- **Apply preset codes directly with the CLI.** Use `npx shadcn@latest apply <code>` for existing projects, or `npx shadcn@latest init --preset <code>` when initializing.
+
+## Key Patterns
+
+These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
+
+```tsx
+// Form layout: FieldGroup + Field, not div + Label.
+<FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="email">Email</FieldLabel>
+ <Input id="email" />
+ </Field>
+</FieldGroup>
+
+// Validation: data-invalid on Field, aria-invalid on the control.
+<Field data-invalid>
+ <FieldLabel>Email</FieldLabel>
+ <Input aria-invalid />
+ <FieldDescription>Invalid email.</FieldDescription>
+</Field>
+
+// Icons in buttons: data-icon, no sizing classes.
+<Button>
+ <SearchIcon data-icon="inline-start" />
+ Search
+</Button>
+
+// Spacing: gap-*, not space-y-*.
+<div className="flex flex-col gap-4"> // correct
+<div className="space-y-4"> // wrong
+
+// Equal dimensions: size-*, not w-* h-*.
+<Avatar className="size-10"> // correct
+<Avatar className="w-10 h-10"> // wrong
+
+// Status colors: Badge variants or semantic tokens, not raw colors.
+<Badge variant="secondary">+20.1%</Badge> // correct
+<span className="text-emerald-600">+20.1%</span> // wrong
+```
+
+## Component Selection
+
+| Need | Use |
+| -------------------------- | --------------------------------------------------------------------------------------------------- |
+| Button/action | `Button` with appropriate variant |
+| Form inputs | `Input`, `Select`, `Combobox`, `Switch`, `Checkbox`, `RadioGroup`, `Textarea`, `InputOTP`, `Slider` |
+| Toggle between 2–5 options | `ToggleGroup` + `ToggleGroupItem` |
+| Data display | `Table`, `Card`, `Badge`, `Avatar` |
+| Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Tabs`, `Pagination` |
+| Overlays | `Dialog` (modal), `Sheet` (side panel), `Drawer` (bottom sheet), `AlertDialog` (confirmation) |
+| Feedback | `toast` (Base UI), `sonner` (Radix/Aria), `Alert`, `Progress`, `Skeleton`, `Spinner` |
+| Command palette | `Command` inside `Dialog` |
+| Charts | `Chart` (wraps Recharts) |
+| Layout | `Card`, `Separator`, `Resizable`, `ScrollArea`, `Accordion`, `Collapsible` |
+| Empty states | `Empty` |
+| Menus | `DropdownMenu`, `ContextMenu`, `Menubar` |
+| Tooltips/info | `Tooltip`, `HoverCard`, `Popover` |
+| Chat / conversation UI | `MessageScroller`, `Message`, `Bubble`, `Attachment`, `Marker` |
+
+## Key Fields
+
+The injected project context contains these key fields:
+
+- **`aliases`** → use the actual alias prefix for imports (e.g. `@/`, `~/`), never hardcode.
+- **`isRSC`** → when `true`, components using `useState`, `useEffect`, event handlers, or browser APIs need `"use client"` at the top of the file. Always reference this field when advising on the directive.
+- **`tailwindVersion`** → `"v4"` uses `@theme inline` blocks; `"v3"` uses `tailwind.config.js`.
+- **`tailwindCssFile`** → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
+- **`style`** → component visual treatment (e.g. `nova`, `vega`).
+- **`base`** → primitive library (`radix` or `base`). Affects component APIs and available props.
+- **`iconLibrary`** → determines icon imports. Use `lucide-react` for `lucide`, `@tabler/icons-react` for `tabler`, etc. Never assume `lucide-react`.
+- **`resolvedPaths`** → exact file-system destinations for components, utils, hooks, etc.
+- **`framework`** → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
+- **`packageManager`** → use this for any non-shadcn dependency installs (e.g. `pnpm add date-fns` vs `npm install date-fns`).
+- **`preset`** → resolved preset code and values for the current project. Use `npx shadcn@latest preset resolve --json` when you only need preset information.
+
+See [cli.md — `info` command](./cli.md) for the full field reference.
+
+## Component Docs, Examples, and Usage
+
+Run `npx shadcn@latest docs <component>` to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
+
+```bash
+npx shadcn@latest docs button dialog select
+```
+
+**When creating, fixing, debugging, or using a component, always run `npx shadcn@latest docs` and fetch the URLs first.** This ensures you're working with the correct API and usage patterns rather than guessing.
+
+## Workflow
+
+1. **Get project context** — already injected above. Run `npx shadcn@latest info` again if you need to refresh.
+2. **Check installed components first** — before running `add`, always check the `components` list from project context or list the `resolvedPaths.ui` directory. Don't import components that haven't been added, and don't re-add ones already installed.
+3. **Find components** — `npx shadcn@latest search`.
+4. **Get docs and examples** — run `npx shadcn@latest docs <component>` to get URLs, then fetch them. Use `npx shadcn@latest view` to browse registry items you haven't installed. To preview changes to installed components, use `npx shadcn@latest add --diff`.
+5. **Install or update** — `npx shadcn@latest add`. When updating existing components, use `--dry-run` and `--diff` to preview changes first (see [Updating Components](#updating-components) below).
+6. **Fix imports in third-party components** — After adding components from community registries (e.g. `@bundui`, `@magicui`), check the added non-UI files for hardcoded import paths like `@/components/ui/...`. These won't match the project's actual aliases. Use `npx shadcn@latest info` to get the correct `ui` alias (e.g. `@workspace/ui/components`) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.
+7. **Review added components** — After adding a component or block from any registry, **always read the added files and verify they are correct**. Check for missing sub-components (e.g. `SelectItem` without `SelectGroup`), missing imports, incorrect composition, or violations of the [Critical Rules](#critical-rules). Also replace any icon imports with the project's `iconLibrary` from the project context (e.g. if the registry item uses `lucide-react` but the project uses `hugeicons`, swap the imports and icon names accordingly). Fix all issues before moving on.
+8. **Registry must be explicit** — When the user asks to add a block or component, **do not guess the registry**. If no registry is specified (e.g. user says "add a login block" without specifying `@shadcn`, `@tailark`, `owner/repo`, etc.), ask which registry to use. Never default to a registry on behalf of the user.
+9. **Switching presets** — Ask the user first: **overwrite**, **partial**, **merge**, or **skip**?
+ - **Inspect current preset**: `npx shadcn@latest preset resolve`. Use `--json` when you need structured values.
+ - **Inspect incoming preset**: `npx shadcn@latest preset decode <code>`. Use `preset url <code>` or `preset open <code>` to share or open the preset builder.
+ - **Overwrite**: `npx shadcn@latest apply <code>`. Overwrites detected components, fonts, and CSS variables.
+ - **Partial**: `npx shadcn@latest apply <code> --only theme,font`. Updates only the selected preset parts without reinstalling UI components. Supported values are `theme` and `font`; comma-separated combinations are allowed. `icon` is intentionally not supported, because icon changes may require full component reinstall and transforms.
+ - **Merge**: `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to list installed components, then for each installed component use `--dry-run` and `--diff` to [smart merge](#updating-components) it individually.
+ - **Skip**: `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS, leaves components as-is.
+ - **Important**: Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
+
+## Updating Components
+
+When the user asks to update a component from upstream while keeping their local changes, use `--dry-run` and `--diff` to intelligently merge. **NEVER fetch raw files from GitHub manually — always use the CLI.**
+
+1. Run `npx shadcn@latest add <component> --dry-run` to see all files that would be affected.
+2. For each file, run `npx shadcn@latest add <component> --diff <file>` to see what changed upstream vs local.
+3. Decide per file based on the diff:
+ - No local changes → safe to overwrite.
+ - Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications.
+ - User says "just update everything" → use `--overwrite`, but confirm first.
+4. **Never use `--overwrite` without the user's explicit approval.**
+
+## Quick Reference
+
+```bash
+# Create a new project.
+npx shadcn@latest init --name my-app --preset base-nova
+npx shadcn@latest init --name my-app --preset a2r6bw --template vite
+
+# Create a monorepo project.
+npx shadcn@latest init --name my-app --preset base-nova --monorepo
+npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
+
+# Initialize existing project.
+npx shadcn@latest init --preset base-nova
+npx shadcn@latest init --defaults # shortcut: --template=next --preset=nova (base style implied)
+
+# Apply a preset to an existing project.
+npx shadcn@latest apply a2r6bw
+npx shadcn@latest apply a2r6bw --only theme
+npx shadcn@latest apply a2r6bw --only font
+npx shadcn@latest apply a2r6bw --only theme,font
+
+# Inspect preset codes and project preset state.
+npx shadcn@latest preset decode a2r6bw
+npx shadcn@latest preset url a2r6bw
+npx shadcn@latest preset open a2r6bw
+npx shadcn@latest preset resolve
+npx shadcn@latest preset resolve --json
+
+# Add components.
+npx shadcn@latest add button card dialog
+npx shadcn@latest add @magicui/shimmer-button
+npx shadcn@latest add owner/repo/item
+npx shadcn@latest add --all
+
+# Preview changes before adding/updating.
+npx shadcn@latest add button --dry-run
+npx shadcn@latest add button --diff button.tsx
+npx shadcn@latest add @acme/form --view button.tsx
+npx shadcn@latest add owner/repo/item --dry-run
+
+# Search registries.
+npx shadcn@latest search @shadcn -q "sidebar"
+npx shadcn@latest search @tailark -q "stats"
+npx shadcn@latest search owner/repo -q "login"
+npx shadcn@latest search # all configured registries
+npx shadcn@latest search @shadcn -q "menu" -t ui # filter by item type
+
+# Get component docs and example URLs.
+npx shadcn@latest docs button dialog select
+
+# View registry item details (for items not yet installed).
+npx shadcn@latest view @shadcn/button
+npx shadcn@latest view owner/repo/item
+```
+
+**Named presets:** `nova`, `vega`, `maia`, `lyra`, `mira`, `luma`
+**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)
+**Preset codes:** Version-prefixed base62 strings (e.g. `a2r6bw` or `b0`), from [ui.shadcn.com](https://ui.shadcn.com).
+
+## Detailed References
+
+- [rules/forms.md](./rules/forms.md) — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states
+- [rules/composition.md](./rules/composition.md) — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading
+- [rules/chat.md](./rules/chat.md) — MessageScroller, Message, Bubble, Attachment, Marker; streaming, anchoring, jump-to-latest
+- [rules/icons.md](./rules/icons.md) — data-icon, icon sizing, passing icons as objects
+- [rules/styling.md](./rules/styling.md) — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index
+- [rules/base-vs-radix.md](./rules/base-vs-radix.md) — asChild vs render, Select, ToggleGroup, Slider, Accordion
+- [cli.md](./cli.md) — Commands, flags, presets, templates
+- [registry.md](./registry.md) — Authoring source registries, `include`, item definitions, dependencies, GitHub registry rules
+- [customization.md](./customization.md) — Theming, CSS variables, extending components
diff --git a/.agents/skills/shadcn/agents/openai.yml b/.agents/skills/shadcn/agents/openai.yml
new file mode 100644
index 00000000..ab636da8
--- /dev/null
+++ b/.agents/skills/shadcn/agents/openai.yml
@@ -0,0 +1,5 @@
+interface:
+ display_name: "shadcn/ui"
+ short_description: "Manages shadcn/ui components — adding, searching, fixing, debugging, styling, and composing UI."
+ icon_small: "./assets/shadcn-small.png"
+ icon_large: "./assets/shadcn.png"
diff --git a/.agents/skills/shadcn/assets/shadcn-small.png b/.agents/skills/shadcn/assets/shadcn-small.png
new file mode 100644
index 00000000..547154b9
Binary files /dev/null and b/.agents/skills/shadcn/assets/shadcn-small.png differ
diff --git a/.agents/skills/shadcn/assets/shadcn.png b/.agents/skills/shadcn/assets/shadcn.png
new file mode 100644
index 00000000..b7b6814a
Binary files /dev/null and b/.agents/skills/shadcn/assets/shadcn.png differ
diff --git a/.agents/skills/shadcn/cli.md b/.agents/skills/shadcn/cli.md
new file mode 100644
index 00000000..8a1d1958
--- /dev/null
+++ b/.agents/skills/shadcn/cli.md
@@ -0,0 +1,290 @@
+# shadcn CLI Reference
+
+Configuration is read from `components.json`.
+
+> **IMPORTANT:** Always run commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest`. Check `packageManager` from project context to choose the right one. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
+
+> **IMPORTANT:** Only use the flags documented below. Do not invent or guess flags — if a flag isn't listed here, it doesn't exist. The CLI auto-detects the package manager from the project's lockfile; there is no `--package-manager` flag.
+
+## Contents
+
+- Commands: init, apply, add (dry-run, smart merge), search, view, docs, info, build
+- Templates: next, vite, start, react-router, astro
+- Presets: named, code, URL formats and fields
+- Switching presets
+
+---
+
+## Commands
+
+### `init` — Initialize or create a project
+
+```bash
+npx shadcn@latest init [components...] [options]
+```
+
+Initializes shadcn/ui in an existing project or creates a new project (when `--name` is provided). Optionally installs components in the same step.
+
+| Flag | Short | Description | Default |
+| ----------------------- | ----- | --------------------------------------------------------- | ------- |
+| `--template <template>` | `-t` | Template (next, start, vite, next-monorepo, react-router) | — |
+| `--preset [name]` | `-p` | Preset configuration (named, code, or URL) | — |
+| `--yes` | `-y` | Skip confirmation prompt | `true` |
+| `--defaults` | `-d` | Use defaults (`--template=next --preset=base-nova`) | `false` |
+| `--force` | `-f` | Force overwrite existing configuration | `false` |
+| `--cwd <cwd>` | `-c` | Working directory | current |
+| `--name <name>` | `-n` | Name for new project | — |
+| `--silent` | `-s` | Mute output | `false` |
+| `--rtl` | | Enable RTL support | — |
+| `--reinstall` | | Re-install existing UI components | `false` |
+| `--monorepo` | | Scaffold a monorepo project | — |
+| `--no-monorepo` | | Skip the monorepo prompt | — |
+
+`npx shadcn@latest create` is an alias for `npx shadcn@latest init`.
+
+### `apply` — Apply a preset to an existing project
+
+```bash
+npx shadcn@latest apply [preset] [options]
+```
+
+Applies a preset to an existing project, overwriting preset-driven config, fonts, CSS variables, and detected UI components.
+
+| Flag | Short | Description | Default |
+| ------------------- | ----- | ------------------------------------------ | ------- |
+| `--preset <preset>` | — | Preset configuration (named, code, or URL) | — |
+| `--yes` | `-y` | Skip confirmation prompt | `false` |
+| `--cwd <cwd>` | `-c` | Working directory | current |
+| `--silent` | `-s` | Mute output | `false` |
+
+`[preset]` is a shorthand for `--preset <preset>`. If both are provided, they must match.
+If no preset is provided, the CLI offers to open the custom preset builder on `ui.shadcn.com/create`.
+
+### `add` — Add components
+
+> **IMPORTANT:** To compare local components against upstream or to preview changes, ALWAYS use `npx shadcn@latest add <component> --dry-run`, `--diff`, or `--view`. NEVER fetch raw files from GitHub or other sources manually. The CLI handles registry resolution, file paths, and CSS diffing automatically.
+
+```bash
+npx shadcn@latest add [components...] [options]
+```
+
+Accepts component names, registry-prefixed names (`@magicui/shimmer-button`),
+GitHub item addresses (`owner/repo/item`), URLs, or local paths.
+
+| Flag | Short | Description | Default |
+| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------- | ------- |
+| `--yes` | `-y` | Skip confirmation prompt | `false` |
+| `--overwrite` | `-o` | Overwrite existing files | `false` |
+| `--cwd <cwd>` | `-c` | Working directory | current |
+| `--all` | `-a` | Add all available components | `false` |
+| `--path <path>` | `-p` | Target path for the component | — |
+| `--silent` | `-s` | Mute output | `false` |
+| `--dry-run` | | Preview all changes without writing files | `false` |
+| `--diff [path]` | | Show diffs. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
+| `--view [path]` | | Show file contents. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
+
+#### Dry-Run Mode
+
+Use `--dry-run` to preview what `add` would do without writing any files. `--diff` and `--view` both imply `--dry-run`.
+
+```bash
+# Preview all changes.
+npx shadcn@latest add button --dry-run
+
+# Show diffs for all files (top 5).
+npx shadcn@latest add button --diff
+
+# Show the diff for a specific file.
+npx shadcn@latest add button --diff button.tsx
+
+# Show contents for all files (top 5).
+npx shadcn@latest add button --view
+
+# Show the full content of a specific file.
+npx shadcn@latest add button --view button.tsx
+
+# Works with URLs too.
+npx shadcn@latest add https://api.npoint.io/abc123 --dry-run
+
+# Works with public GitHub registries too.
+npx shadcn@latest add owner/repo/item --dry-run
+
+# CSS diffs.
+npx shadcn@latest add button --diff globals.css
+```
+
+**When to use dry-run:**
+
+- When the user asks "what files will this add?" or "what will this change?" — use `--dry-run`.
+- Before overwriting existing components — use `--diff` to preview the changes first.
+- When the user wants to inspect component source code without installing — use `--view`.
+- When checking what CSS changes would be made to `globals.css` — use `--diff globals.css`.
+- When the user asks to review or audit third-party registry code before installing — use `--view` to inspect the source.
+
+> **`npx shadcn@latest add --dry-run` vs `npx shadcn@latest view`:** Prefer `npx shadcn@latest add --dry-run/--diff/--view` over `npx shadcn@latest view` when the user wants to preview changes to their project. `npx shadcn@latest view` only shows raw registry metadata. `npx shadcn@latest add --dry-run` shows exactly what would happen in the user's project: resolved file paths, diffs against existing files, and CSS updates. Use `npx shadcn@latest view` only when the user wants to browse registry info without a project context.
+
+#### Smart Merge from Upstream
+
+See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full workflow.
+
+### `search` — Search registries
+
+```bash
+npx shadcn@latest search [registries...] [options]
+```
+
+Fuzzy search across registries. Also aliased as `npx shadcn@latest list`.
+Supports namespaces (`@acme`), public GitHub registry sources (`owner/repo`),
+and registry catalog URLs. Without `-q`, lists all items. When no registries are
+passed, searches every registry configured in `components.json`.
+
+| Flag | Short | Description | Default |
+| ------------------- | ----- | ------------------------------------------------- | ------- |
+| `--query <query>` | `-q` | Search query | — |
+| `--type <type>` | `-t` | Filter by item type (e.g. `ui`, `block`, `hook`); comma-separated | — |
+| `--limit <number>` | `-l` | Max items to display | `100` |
+| `--offset <number>` | `-o` | Items to skip | `0` |
+| `--json` | | Output as JSON | `false` |
+| `--cwd <cwd>` | `-c` | Working directory | current |
+
+### `view` — View item details
+
+```bash
+npx shadcn@latest view <items...> [options]
+```
+
+Displays item info including file contents. Examples:
+`npx shadcn@latest view @shadcn/button`,
+`npx shadcn@latest view owner/repo/item`.
+
+### `docs` — Get component documentation URLs
+
+```bash
+npx shadcn@latest docs <components...> [options]
+```
+
+Outputs resolved URLs for component documentation, examples, and API references. Accepts one or more component names. Fetch the URLs to get the actual content.
+
+Example output for `npx shadcn@latest docs input button`:
+
+```
+base radix
+
+input
+ docs https://ui.shadcn.com/docs/components/radix/input
+ examples https://raw.githubusercontent.com/.../examples/input-example.tsx
+
+button
+ docs https://ui.shadcn.com/docs/components/radix/button
+ examples https://raw.githubusercontent.com/.../examples/button-example.tsx
+```
+
+Some components include an `api` link to the underlying library (e.g. `cmdk` for the command component).
+
+### `diff` — Check for updates
+
+Do not use this command. Use `npx shadcn@latest add --diff` instead.
+
+### `info` — Project information
+
+```bash
+npx shadcn@latest info [options]
+```
+
+Displays project info and `components.json` configuration. Run this first to discover the project's framework, aliases, Tailwind version, and resolved paths.
+
+| Flag | Short | Description | Default |
+| ------------- | ----- | ----------------- | ------- |
+| `--cwd <cwd>` | `-c` | Working directory | current |
+
+**Project Info fields:**
+
+| Field | Type | Meaning |
+| -------------------- | --------- | ------------------------------------------------------------------ |
+| `framework` | `string` | Detected framework (`next`, `vite`, `react-router`, `start`, etc.) |
+| `frameworkVersion` | `string` | Framework version (e.g. `15.2.4`) |
+| `isSrcDir` | `boolean` | Whether the project uses a `src/` directory |
+| `isRSC` | `boolean` | Whether React Server Components are enabled |
+| `isTsx` | `boolean` | Whether the project uses TypeScript |
+| `tailwindVersion` | `string` | `"v3"` or `"v4"` |
+| `tailwindConfigFile` | `string` | Path to the Tailwind config file |
+| `tailwindCssFile` | `string` | Path to the global CSS file |
+| `aliasPrefix` | `string` | Import alias prefix (e.g. `@`, `~`, `@/`) |
+| `packageManager` | `string` | Detected package manager (`npm`, `pnpm`, `yarn`, `bun`) |
+
+**Components.json fields:**
+
+| Field | Type | Meaning |
+| -------------------- | --------- | ------------------------------------------------------------------------------------------ |
+| `base` | `string` | Primitive library (`radix` or `base`) — determines component APIs and available props |
+| `style` | `string` | Visual style (e.g. `nova`, `vega`) |
+| `rsc` | `boolean` | RSC flag from config |
+| `tsx` | `boolean` | TypeScript flag |
+| `tailwind.config` | `string` | Tailwind config path |
+| `tailwind.css` | `string` | Global CSS path — this is where custom CSS variables go |
+| `iconLibrary` | `string` | Icon library — determines icon import package (e.g. `lucide-react`, `@tabler/icons-react`) |
+| `aliases.components` | `string` | Component import alias (e.g. `@/components`) |
+| `aliases.utils` | `string` | Utils import alias (e.g. `@/lib/utils`) |
+| `aliases.ui` | `string` | UI component alias (e.g. `@/components/ui`) |
+| `aliases.lib` | `string` | Lib alias (e.g. `@/lib`) |
+| `aliases.hooks` | `string` | Hooks alias (e.g. `@/hooks`) |
+| `resolvedPaths` | `object` | Absolute file-system paths for each alias |
+| `registries` | `object` | Configured custom registries |
+
+**Links fields:**
+
+The `info` output includes a **Links** section with templated URLs for component docs, source, and examples. For resolved URLs, use `npx shadcn@latest docs <component>` instead.
+
+### `build` — Build a custom registry
+
+```bash
+npx shadcn@latest build [registry] [options]
+```
+
+Builds `registry.json` into individual JSON files for distribution. Default input: `./registry.json`, default output: `./public/r`.
+
+For authoring rules, `include`, item definitions, `registryDependencies`, and
+GitHub registry behavior, see [registry.md](./registry.md).
+
+| Flag | Short | Description | Default |
+| ----------------- | ----- | ----------------- | ------------ |
+| `--output <path>` | `-o` | Output directory | `./public/r` |
+| `--cwd <cwd>` | `-c` | Working directory | current |
+
+---
+
+## Templates
+
+| Value | Framework | Monorepo support |
+| -------------- | -------------- | ---------------- |
+| `next` | Next.js | Yes |
+| `vite` | Vite | Yes |
+| `start` | TanStack Start | Yes |
+| `react-router` | React Router | Yes |
+| `astro` | Astro | Yes |
+| `laravel` | Laravel | No |
+
+All templates support monorepo scaffolding via the `--monorepo` flag. When passed, the CLI uses a monorepo-specific template directory (e.g. `next-monorepo`, `vite-monorepo`). When neither `--monorepo` nor `--no-monorepo` is passed, the CLI prompts interactively. Laravel does not support monorepo scaffolding.
+
+---
+
+## Presets
+
+Three ways to specify a preset via `--preset`:
+
+1. **Named:** `--preset nova` or `--preset lyra`
+2. **Code:** `--preset a2r6bw` (version-prefixed base62 string, e.g. `a2r6bw` or `b0`)
+3. **URL:** `--preset "https://ui.shadcn.com/init?base=radix&style=nova&..."`
+
+> **IMPORTANT:** Never try to decode, fetch, or resolve preset codes manually. Preset codes are opaque — pass them directly to `npx shadcn@latest init --preset <code>` and let the CLI handle resolution.
+> Use `npx shadcn@latest apply --preset <code>` when overwriting an existing project's preset.
+
+## Switching Presets
+
+Ask the user first: **overwrite**, **merge**, or **skip** existing components?
+
+- **Overwrite / Re-install** → `npx shadcn@latest apply --preset <code>`. Overwrites all detected component files with the new preset styles. Use when the user hasn't customized components.
+- **Merge** → `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to get the list of installed components and use the [smart merge workflow](./SKILL.md#updating-components) to update them one by one, preserving local changes. Use when the user has customized components.
+- **Skip** → `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS variables, leaves existing components as-is.
+
+Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
diff --git a/.agents/skills/shadcn/customization.md b/.agents/skills/shadcn/customization.md
new file mode 100644
index 00000000..16954f56
--- /dev/null
+++ b/.agents/skills/shadcn/customization.md
@@ -0,0 +1,209 @@
+# Customization & Theming
+
+Components reference semantic CSS variable tokens. Change the variables to change every component.
+
+## Contents
+
+- How it works (CSS variables → Tailwind utilities → components)
+- Color variables and OKLCH format
+- Dark mode setup
+- Changing the theme (presets, CSS variables)
+- Adding custom colors (Tailwind v3 and v4)
+- Border radius
+- Customizing components (variants, className, wrappers)
+- Checking for updates
+
+---
+
+## How It Works
+
+1. CSS variables defined in `:root` (light) and `.dark` (dark mode).
+2. Tailwind maps them to utilities: `bg-primary`, `text-muted-foreground`, etc.
+3. Components use these utilities — changing a variable changes all components that reference it.
+
+---
+
+## Color Variables
+
+Every color follows the `name` / `name-foreground` convention. The base variable is for backgrounds, `-foreground` is for text/icons on that background.
+
+| Variable | Purpose |
+| -------------------------------------------- | -------------------------------- |
+| `--background` / `--foreground` | Page background and default text |
+| `--card` / `--card-foreground` | Card surfaces |
+| `--primary` / `--primary-foreground` | Primary buttons and actions |
+| `--secondary` / `--secondary-foreground` | Secondary actions |
+| `--muted` / `--muted-foreground` | Muted/disabled states |
+| `--accent` / `--accent-foreground` | Hover and accent states |
+| `--destructive` / `--destructive-foreground` | Error and destructive actions |
+| `--border` | Default border color |
+| `--input` | Form input borders |
+| `--ring` | Focus ring color |
+| `--chart-1` through `--chart-5` | Chart/data visualization |
+| `--sidebar-*` | Sidebar-specific colors |
+| `--surface` / `--surface-foreground` | Secondary surface |
+
+Colors use OKLCH: `--primary: oklch(0.205 0 0)` where values are lightness (0–1), chroma (0 = gray), and hue (0–360).
+
+---
+
+## Dark Mode
+
+Class-based toggle via `.dark` on the root element. In Next.js, use `next-themes`:
+
+```tsx
+import { ThemeProvider } from "next-themes"
+
+<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
+ {children}
+</ThemeProvider>
+```
+
+---
+
+## Changing the Theme
+
+```bash
+# Apply a preset code from ui.shadcn.com.
+npx shadcn@latest apply --preset a2r6bw
+
+# Positional shorthand also works.
+npx shadcn@latest apply a2r6bw
+
+# Switch to a named preset and overwrite existing components.
+npx shadcn@latest apply --preset nova
+
+# Preserve existing components instead.
+npx shadcn@latest init --preset nova --force --no-reinstall
+
+# Use a custom theme URL.
+npx shadcn@latest apply --preset "https://ui.shadcn.com/init?base=radix&style=nova&theme=blue&..."
+```
+
+Or edit CSS variables directly in `globals.css`.
+
+---
+
+## Adding Custom Colors
+
+Add variables to the file at `tailwindCssFile` from `npx shadcn@latest info` (typically `globals.css`). Never create a new CSS file for this.
+
+```css
+/* 1. Define in the global CSS file. */
+:root {
+ --warning: oklch(0.84 0.16 84);
+ --warning-foreground: oklch(0.28 0.07 46);
+}
+.dark {
+ --warning: oklch(0.41 0.11 46);
+ --warning-foreground: oklch(0.99 0.02 95);
+}
+```
+
+```css
+/* 2a. Register with Tailwind v4 (@theme inline). */
+@theme inline {
+ --color-warning: var(--warning);
+ --color-warning-foreground: var(--warning-foreground);
+}
+```
+
+When `tailwindVersion` is `"v3"` (check via `npx shadcn@latest info`), register in `tailwind.config.js` instead:
+
+```js
+// 2b. Register with Tailwind v3 (tailwind.config.js).
+module.exports = {
+ theme: {
+ extend: {
+ colors: {
+ warning: "oklch(var(--warning) / <alpha-value>)",
+ "warning-foreground":
+ "oklch(var(--warning-foreground) / <alpha-value>)",
+ },
+ },
+ },
+}
+```
+
+```tsx
+// 3. Use in components.
+<div className="bg-warning text-warning-foreground">Warning</div>
+```
+
+---
+
+## Border Radius
+
+`--radius` controls border radius globally. Components derive values from it (`rounded-lg` = `var(--radius)`, `rounded-md` = `calc(var(--radius) - 2px)`).
+
+---
+
+## Customizing Components
+
+See also: [rules/styling.md](./rules/styling.md) for Incorrect/Correct examples.
+
+Prefer these approaches in order:
+
+### 1. Built-in variants
+
+```tsx
+<Button variant="outline" size="sm">
+ Click
+</Button>
+```
+
+### 2. Tailwind classes via `className`
+
+```tsx
+<Card className="mx-auto max-w-md">...</Card>
+```
+
+### 3. Add a new variant
+
+Edit the component source to add a variant via `cva`:
+
+```tsx
+// components/ui/button.tsx
+warning: "bg-warning text-warning-foreground hover:bg-warning/90",
+```
+
+### 4. Wrapper components
+
+Compose shadcn/ui primitives into higher-level components:
+
+```tsx
+export function ConfirmDialog({ title, description, onConfirm, children }) {
+ return (
+ <AlertDialog>
+ <AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{title}</AlertDialogTitle>
+ <AlertDialogDescription>{description}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={onConfirm}>Confirm</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
+```
+
+---
+
+## Checking for Updates
+
+```bash
+npx shadcn@latest add button --diff
+```
+
+To preview exactly what would change before updating, use `--dry-run` and `--diff`:
+
+```bash
+npx shadcn@latest add button --dry-run # see all affected files
+npx shadcn@latest add button --diff button.tsx # see the diff for a specific file
+```
+
+See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full smart merge workflow.
diff --git a/.agents/skills/shadcn/evals/evals.json b/.agents/skills/shadcn/evals/evals.json
new file mode 100644
index 00000000..1a90a2d9
--- /dev/null
+++ b/.agents/skills/shadcn/evals/evals.json
@@ -0,0 +1,77 @@
+{
+ "skill_name": "shadcn",
+ "evals": [
+ {
+ "id": 1,
+ "prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Create a settings form component with fields for: full name, email address, and notification preferences (email, SMS, push notifications as toggle options). Add validation states for required fields.",
+ "expected_output": "A React component using FieldGroup, Field, ToggleGroup, data-invalid/aria-invalid validation, gap-* spacing, and semantic colors.",
+ "files": [],
+ "expectations": [
+ "Uses FieldGroup and Field components for form layout instead of raw div with space-y",
+ "Uses Switch for independent on/off notification toggles (not looping Button with manual active state)",
+ "Uses data-invalid on Field and aria-invalid on the input control for validation states",
+ "Uses gap-* (e.g. gap-4, gap-6) instead of space-y-* or space-x-* for spacing",
+ "Uses semantic color tokens (e.g. bg-background, text-muted-foreground, text-destructive) instead of raw colors like bg-red-500",
+ "No manual dark: color overrides"
+ ]
+ },
+ {
+ "id": 2,
+ "prompt": "Create a dialog component for editing a user profile. It should have the user's avatar at the top, input fields for name and bio, and Save/Cancel buttons with appropriate icons. Using shadcn/ui with radix-nova preset and tabler icons.",
+ "expected_output": "A React component with DialogTitle, Avatar+AvatarFallback, data-icon on icon buttons, no icon sizing classes, tabler icon imports.",
+ "files": [],
+ "expectations": [
+ "Includes DialogTitle for accessibility (visible or with sr-only class)",
+ "Avatar component includes AvatarFallback",
+ "Icons on buttons use the data-icon attribute (data-icon=\"inline-start\" or data-icon=\"inline-end\")",
+ "No sizing classes on icons inside components (no size-4, w-4, h-4, etc.)",
+ "Uses tabler icons (@tabler/icons-react) instead of lucide-react",
+ "Uses asChild for custom triggers (radix preset)"
+ ]
+ },
+ {
+ "id": 3,
+ "prompt": "Create a dashboard component that shows 4 stat cards in a grid. Each card has a title, large number, percentage change badge, and a loading skeleton state. Using shadcn/ui with base-nova preset and lucide icons.",
+ "expected_output": "A React component with full Card composition, Skeleton for loading, Badge for changes, semantic colors, gap-* spacing.",
+ "files": [],
+ "expectations": [
+ "Uses full Card composition with CardHeader, CardTitle, CardContent (not dumping everything into CardContent)",
+ "Uses Skeleton component for loading placeholders instead of custom animate-pulse divs",
+ "Uses Badge component for percentage change instead of custom styled spans",
+ "Uses semantic color tokens instead of raw color values like bg-green-500 or text-red-600",
+ "Uses gap-* instead of space-y-* or space-x-* for spacing",
+ "Uses size-* when width and height are equal instead of separate w-* h-*"
+ ]
+ },
+ {
+ "id": 4,
+ "prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Build a chat conversation view: a scrollable thread of messages from two different people, each with an avatar, sender name, timestamp, and message bubble. A couple of messages include an image attachment and a PDF file attachment, and there's a 'Today' divider separating the days.",
+ "expected_output": "A React component composing MessageScroller, Message, Bubble, Attachment, and Marker from the registry instead of hand-rolled bubble/divider/attachment markup.",
+ "files": [],
+ "expectations": [
+ "Uses MessageScroller (MessageScrollerProvider, MessageScrollerViewport, MessageScrollerContent, MessageScrollerItem) for the scrollable thread instead of a raw overflow-y-auto div or ScrollArea",
+ "Wraps each row in MessageScrollerItem inside MessageScrollerContent",
+ "Uses Message with MessageAvatar/MessageContent/MessageHeader for row layout instead of custom flex divs",
+ "Uses Bubble + BubbleContent for the message surface instead of a styled div with bg-muted/bg-primary",
+ "Uses Attachment (AttachmentMedia, AttachmentContent, AttachmentTitle, AttachmentDescription) for the file and image attachments instead of Item or a custom card",
+ "Uses Marker (variant=\"separator\") for the 'Today' divider instead of Separator plus a centered label",
+ "Uses semantic color tokens and gap-* spacing; no raw colors like bg-emerald-500 and no space-y-*",
+ "Includes \"use client\" when the component uses state or event handlers (isRSC)"
+ ]
+ },
+ {
+ "id": 5,
+ "prompt": "Using shadcn/ui (base-nova preset, lucide icons), build a streaming AI chat UI. The assistant's reply streams in while it generates, the view auto-scrolls to follow the latest content but stops following if the user scrolls up to read earlier messages, a 'jump to latest' button appears when the user has scrolled away from the bottom, and a subtle 'thinking…' shimmer shows while the model is generating.",
+ "expected_output": "A React component that delegates scroll/anchor behavior to MessageScroller and uses MessageScrollerButton for jump-to-latest and the shimmer utility for the thinking indicator — no hand-rolled scroll logic or custom shimmer keyframes.",
+ "files": [],
+ "expectations": [
+ "Uses MessageScroller with MessageScrollerProvider (autoScroll) and scrollAnchor on message items for the stick-to-bottom/follow behavior instead of a custom useStickToBottom hook or ResizeObserver/scrollTop wiring",
+ "Uses MessageScrollerButton for the jump-to-latest control instead of a hand-built conditional button driven by manual scroll-position state",
+ "Uses the shimmer utility class for the 'thinking…' indicator instead of a custom @keyframes or bg-clip-text gradient animation",
+ "Wraps each message row in MessageScrollerItem inside MessageScrollerContent",
+ "Uses Message + Bubble + BubbleContent for the conversation rows instead of hand-rolled bubble divs",
+ "Uses semantic color tokens and gap-* spacing; includes \"use client\" (isRSC)"
+ ]
+ }
+ ]
+}
diff --git a/.agents/skills/shadcn/mcp.md b/.agents/skills/shadcn/mcp.md
new file mode 100644
index 00000000..6539ddaa
--- /dev/null
+++ b/.agents/skills/shadcn/mcp.md
@@ -0,0 +1,105 @@
+# shadcn MCP Server
+
+The CLI includes an MCP server that lets AI assistants search, browse, view, and install items from registries.
+
+---
+
+## Setup
+
+```bash
+shadcn mcp # start the MCP server (stdio)
+shadcn mcp init # write config for your editor
+```
+
+Editor config files:
+
+| Editor | Config file |
+| ----------- | ------------------------------- |
+| Claude Code | `.mcp.json` |
+| Cursor | `.cursor/mcp.json` |
+| VS Code | `.vscode/mcp.json` |
+| OpenCode | `opencode.json` |
+| Codex | `~/.codex/config.toml` (manual) |
+
+---
+
+## Tools
+
+> **Tip:** MCP tools handle registry operations (search, view, install). For project configuration (aliases, framework, Tailwind version), use `npx shadcn@latest info` — there is no MCP equivalent.
+
+### `shadcn:get_project_registries`
+
+Returns registry names from `components.json`. Errors if no `components.json` exists.
+
+**Input:** none
+
+### `shadcn:list_items_in_registries`
+
+Lists all items from one or more registries. Registries can be configured
+namespaces such as `@acme`, public GitHub sources such as `owner/repo`, or
+registry catalog URLs. Omit `registries` to list from every registry configured
+in `components.json`.
+
+**Input:** `registries` (string[], optional — omit for all configured), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
+
+### `shadcn:search_items_in_registries`
+
+Fuzzy search across registries. Registries can be configured namespaces, public
+GitHub sources, or registry catalog URLs. Omit `registries` to search every
+registry configured in `components.json` — e.g. "find me a hero" across all
+configured registries.
+
+**Input:** `registries` (string[], optional — omit for all configured), `query` (string), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
+
+### `shadcn:view_items_in_registries`
+
+View item details including full file contents.
+
+**Input:** `items` (string[]) — e.g.
+`["@shadcn/button", "@shadcn/card", "owner/repo/item"]`
+
+### `shadcn:get_item_examples_from_registries`
+
+Find usage examples and demos with source code. Omit `registries` to search
+every registry configured in `components.json`.
+
+**Input:** `registries` (string[], optional — omit for all configured), `query` (string) — e.g. `"accordion-demo"`, `"button example"`
+
+### `shadcn:get_add_command_for_items`
+
+Returns the CLI install command.
+
+**Input:** `items` (string[]) — e.g. `["@shadcn/button"]`
+
+### `shadcn:get_audit_checklist`
+
+Returns a checklist for verifying components (imports, deps, lint, TypeScript).
+
+**Input:** none
+
+---
+
+## Configuring Registries
+
+Namespaced and authenticated registries are set in `components.json`. The
+`@shadcn` registry is always built-in. Public GitHub registries can also be used
+directly as `owner/repo` registry sources when the repository has a root
+`registry.json`; they do not need `components.json` configuration.
+
+```json
+{
+ "registries": {
+ "@acme": "https://acme.com/r/{name}.json",
+ "@private": {
+ "url": "https://private.com/r/{name}.json",
+ "headers": { "Authorization": "Bearer ${MY_TOKEN}" }
+ }
+ }
+}
+```
+
+- Names must start with `@`.
+- URLs must contain `{name}`.
+- `${VAR}` references are resolved from environment variables.
+
+Community registry index: `https://ui.shadcn.com/r/registries.json`
diff --git a/.agents/skills/shadcn/registry.md b/.agents/skills/shadcn/registry.md
new file mode 100644
index 00000000..5369468b
--- /dev/null
+++ b/.agents/skills/shadcn/registry.md
@@ -0,0 +1,277 @@
+# Registry Authoring and Addresses
+
+Use this reference when the user wants to create, fix, publish, or reason about
+a shadcn registry.
+
+## Mental Model
+
+A registry has two forms:
+
+- **Source registry**: an authored `registry.json` in a project or repository.
+ It may use `include` and file paths that point at source files.
+- **Built registry**: generated JSON files served to CLI consumers, usually
+ from `public/r`. Use `npx shadcn@latest build` to create this form.
+
+The CLI installer consumes registry item payloads. A source registry is a way to
+author those payloads from real files.
+
+Registry items are not limited to React components. They can distribute
+components, hooks, utilities, design tokens, pages, config files, docs, rules,
+workflows, templates, MCP files, and other project files.
+
+## Root `registry.json`
+
+The root registry file should define registry metadata and either `items` or
+`include`.
+
+```json
+{
+ "$schema": "https://ui.shadcn.com/schema/registry.json",
+ "name": "acme",
+ "homepage": "https://acme.com",
+ "items": [
+ {
+ "name": "absolute-url",
+ "type": "registry:lib",
+ "title": "Absolute URL",
+ "description": "A utility to turn any path into an absolute URL.",
+ "files": [
+ {
+ "path": "lib/absolute-url.ts",
+ "type": "registry:lib"
+ }
+ ]
+ }
+ ]
+}
+```
+
+Root registry rules:
+
+- Root `registry.json` must include `name` and `homepage`.
+- `items` is an array of registry item definitions.
+- `include` may be used to split the source registry into multiple files.
+- Included registry files may omit `name` and `homepage`.
+
+## Include
+
+Use `include` to keep large registries modular.
+
+```json
+{
+ "$schema": "https://ui.shadcn.com/schema/registry.json",
+ "name": "acme",
+ "homepage": "https://acme.com",
+ "include": ["registry/ui/registry.json", "registry/blocks/registry.json"]
+}
+```
+
+Include rules:
+
+- Include paths are relative to the `registry.json` that declares them.
+- Include paths must explicitly point to a `registry.json` file.
+- Do not use remote URLs, absolute paths, or parent traversal (`..`).
+- Item file paths are relative to the registry file that declares the item.
+- Duplicate item names fail across the resolved registry.
+
+Example included file:
+
+```json
+{
+ "items": [
+ {
+ "name": "button",
+ "type": "registry:ui",
+ "files": [
+ {
+ "path": "button.tsx",
+ "type": "registry:ui"
+ }
+ ]
+ }
+ ]
+}
+```
+
+If this file is at `registry/ui/registry.json`, then `button.tsx` is read from
+`registry/ui/button.tsx`, and the built item path is emitted relative to the
+root registry.
+
+## Item Definitions
+
+Common item fields:
+
+```json
+{
+ "name": "login-form",
+ "type": "registry:block",
+ "title": "Login Form",
+ "description": "A login form with email and password fields.",
+ "dependencies": ["zod"],
+ "registryDependencies": ["button", "input", "label"],
+ "files": [
+ {
+ "path": "blocks/login-form.tsx",
+ "type": "registry:block"
+ }
+ ],
+ "cssVars": {
+ "light": {
+ "brand": "oklch(0.62 0.18 250)"
+ },
+ "dark": {
+ "brand": "oklch(0.72 0.16 250)"
+ }
+ }
+}
+```
+
+Important fields:
+
+- `name`: the installable item name. It is not necessarily a file path.
+- `type`: one of the registry item types, such as `registry:ui`,
+ `registry:block`, `registry:lib`, `registry:hook`, `registry:file`,
+ `registry:page`, `registry:theme`, `registry:style`, `registry:font`, or
+ `registry:item`.
+- `files`: source files copied or generated by the item.
+- `dependencies`: npm runtime dependencies.
+- `devDependencies`: npm development dependencies.
+- `registryDependencies`: other registry items required by this item.
+- `cssVars`, `css`, `tailwind`, `envVars`, and `docs`: optional install-time
+ additions.
+
+File rules:
+
+- File paths are relative to the declaring `registry.json`.
+- `registry:file` and `registry:page` files require a `target`.
+- Do not use remote file URLs in source registry file paths.
+- Keep source files copy-pasteable: no hidden app-only imports.
+
+## Registry Dependencies
+
+`registryDependencies` entries are item addresses, not file paths.
+
+```json
+{
+ "name": "login-form",
+ "type": "registry:block",
+ "registryDependencies": ["button", "@acme/input", "acme/ui/card#v1.2.0"],
+ "files": [
+ {
+ "path": "blocks/login-form.tsx",
+ "type": "registry:block"
+ }
+ ]
+}
+```
+
+Dependency rules:
+
+- Bare names such as `"button"` mean official shadcn items.
+- Bare names never mean same-registry or same-repository items.
+- Namespaced dependencies use `@namespace/item-name`.
+- GitHub dependencies use `owner/repo/item-name`.
+- Pin GitHub dependencies with `owner/repo/item-name#ref` when needed.
+- Refs are not inherited. If `owner/repo/foo#v2` depends on `bar` from the same
+ repo at `v2`, write `owner/repo/bar#v2`.
+- Do not use relative dependencies such as `"./bar"`.
+
+## Address Schemes
+
+When reasoning about a registry item string, classify it first.
+
+| Address | Scheme | Meaning |
+| ----------------------------------- | --------- | ------------------------------------------------------------ |
+| `button` | shadcn | Official shadcn item named `button`. |
+| `@acme/button` | namespace | Item `button` from configured registry `@acme`. |
+| `@acme/ui/button` | namespace | Item `ui/button` from configured registry `@acme`. |
+| `https://example.com/r/button.json` | url | Built registry item JSON at that URL. |
+| `./button.json` | file | Built registry item JSON on disk. |
+| `acme/ui/button` | github | Item `button` from GitHub repo `acme/ui`. |
+| `acme/ui/forms/login#main` | github | Item `forms/login` from GitHub repo `acme/ui` at ref `main`. |
+
+For namespace and GitHub addresses, slashful item names are allowed and are item
+names, not file paths. Addresses ending in `.json` keep file-address
+precedence, so `acme/ui/data/schema.json` is treated as a file path, not a
+GitHub item address.
+
+## GitHub Registries
+
+A public GitHub repository can act as a source registry when it has a root
+`registry.json`.
+
+```txt
+owner/repo/item-name[#ref]
+```
+
+Rules:
+
+- The first two path segments are GitHub owner and repo.
+- All remaining path segments are the registry item name.
+- The source entrypoint is always root `registry.json`.
+- GitHub registries are source registries consumed directly by the CLI. They do
+ not require `shadcn build` or generated item JSON files.
+- `include` follows the same source-registry rules as local registries.
+- Currently, GitHub addresses support public `github.com` repositories only.
+- Private repos and GitHub Enterprise require explicit product decisions.
+
+When implementing GitHub registry fetching, resolve refs to a commit SHA before
+reading source files. Do not read moving refs directly from
+`raw.githubusercontent.com`, because branch-like refs can be cached for several
+minutes.
+
+Preferred flow:
+
+```txt
+owner/repo[#ref]
+ -> resolve ref with git ls-remote
+ -> commit SHA
+ -> read https://raw.githubusercontent.com/{owner}/{repo}/{sha}/registry.json
+ -> read includes and item files from the same SHA
+```
+
+This keeps a command on one consistent repository snapshot.
+
+Full 40-character commit SHAs are already stable and can be used directly.
+Branches, tags, and short refs require Git so the CLI can resolve them to a
+commit SHA first.
+
+## Build and Verify
+
+Use the CLI to build source registries:
+
+```bash
+npx shadcn@latest build
+npx shadcn@latest build registry.json --output public/r
+```
+
+Use CLI commands to inspect the result:
+
+```bash
+npx shadcn@latest list @acme
+npx shadcn@latest search @acme -q "login"
+npx shadcn@latest view @acme/login-form
+npx shadcn@latest add @acme/login-form --dry-run
+npx shadcn@latest registry validate ./registry.json
+```
+
+Use GitHub addresses directly for public GitHub registries:
+
+```bash
+npx shadcn@latest list owner/repo
+npx shadcn@latest search owner/repo -q "login"
+npx shadcn@latest view owner/repo/item
+npx shadcn@latest add owner/repo/item --dry-run
+npx shadcn@latest registry validate owner/repo
+```
+
+When working on registry implementation in the shadcn/ui codebase:
+
+- Keep address parsing pure and testable.
+- Do not add side effects to validators.
+- Preserve existing behavior for official shadcn, namespace, URL, and file
+ schemes.
+- Add tests for address parsing, source loading, dependency resolution, list,
+ search, view, and add paths.
+- Prefer small source-reader abstractions over a plugin system until there are
+ multiple real providers.
diff --git a/.agents/skills/shadcn/rules/base-vs-radix.md b/.agents/skills/shadcn/rules/base-vs-radix.md
new file mode 100644
index 00000000..c1ed7d11
--- /dev/null
+++ b/.agents/skills/shadcn/rules/base-vs-radix.md
@@ -0,0 +1,306 @@
+# Base vs Radix
+
+API differences between `base` and `radix`. Check the `base` field from `npx shadcn@latest info`.
+
+## Contents
+
+- Composition: asChild vs render
+- Button / trigger as non-button element
+- Select (items prop, placeholder, positioning, multiple, object values)
+- ToggleGroup (type vs multiple)
+- Slider (scalar vs array)
+- Accordion (type and defaultValue)
+
+---
+
+## Composition: asChild (radix) vs render (base)
+
+Radix uses `asChild` to replace the default element. Base uses `render`. Don't wrap triggers in extra elements.
+
+**Incorrect:**
+
+```tsx
+<DialogTrigger>
+ <div>
+ <Button>Open</Button>
+ </div>
+</DialogTrigger>
+```
+
+**Correct (radix):**
+
+```tsx
+<DialogTrigger asChild>
+ <Button>Open</Button>
+</DialogTrigger>
+```
+
+**Correct (base):**
+
+```tsx
+<DialogTrigger render={<Button />}>Open</DialogTrigger>
+```
+
+This applies to all trigger and close components: `DialogTrigger`, `SheetTrigger`, `AlertDialogTrigger`, `DropdownMenuTrigger`, `PopoverTrigger`, `TooltipTrigger`, `CollapsibleTrigger`, `DialogClose`, `SheetClose`, `NavigationMenuLink`, `BreadcrumbLink`, `SidebarMenuButton`, `Badge`, `Item`.
+
+---
+
+## Button / trigger as non-button element (base only)
+
+When `render` changes an element to a non-button (`<a>`, `<span>`), add `nativeButton={false}`.
+
+**Incorrect (base):** missing `nativeButton={false}`.
+
+```tsx
+<Button render={<a href="/docs" />}>Read the docs</Button>
+```
+
+**Correct (base):**
+
+```tsx
+<Button render={<a href="/docs" />} nativeButton={false}>
+ Read the docs
+</Button>
+```
+
+**Correct (radix):**
+
+```tsx
+<Button asChild>
+ <a href="/docs">Read the docs</a>
+</Button>
+```
+
+Same for triggers whose `render` is not a `Button`:
+
+```tsx
+// base.
+<PopoverTrigger render={<InputGroupAddon />} nativeButton={false}>
+ Pick date
+</PopoverTrigger>
+```
+
+---
+
+## Select
+
+**items prop (base only).** Base requires an `items` prop on the root. Radix uses inline JSX only.
+
+**Incorrect (base):**
+
+```tsx
+<Select>
+ <SelectTrigger><SelectValue placeholder="Select a fruit" /></SelectTrigger>
+</Select>
+```
+
+**Correct (base):**
+
+```tsx
+const items = [
+ { label: "Select a fruit", value: null },
+ { label: "Apple", value: "apple" },
+ { label: "Banana", value: "banana" },
+]
+
+<Select items={items}>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {items.map((item) => (
+ <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+</Select>
+```
+
+**Correct (radix):**
+
+```tsx
+<Select>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a fruit" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectItem value="apple">Apple</SelectItem>
+ <SelectItem value="banana">Banana</SelectItem>
+ </SelectGroup>
+ </SelectContent>
+</Select>
+```
+
+**Placeholder.** Base uses a `{ value: null }` item in the items array. Radix uses `<SelectValue placeholder="...">`.
+
+**Content positioning.** Base uses `alignItemWithTrigger`. Radix uses `position`.
+
+```tsx
+// base.
+<SelectContent alignItemWithTrigger={false} side="bottom">
+
+// radix.
+<SelectContent position="popper">
+```
+
+---
+
+## Select — multiple selection and object values (base only)
+
+Base supports `multiple`, render-function children on `SelectValue`, and object values with `itemToStringValue`. Radix is single-select with string values only.
+
+**Correct (base — multiple selection):**
+
+```tsx
+<Select items={items} multiple defaultValue={[]}>
+ <SelectTrigger>
+ <SelectValue>
+ {(value: string[]) => value.length === 0 ? "Select fruits" : `${value.length} selected`}
+ </SelectValue>
+ </SelectTrigger>
+ ...
+</Select>
+```
+
+**Correct (base — object values):**
+
+```tsx
+<Select defaultValue={plans[0]} itemToStringValue={(plan) => plan.name}>
+ <SelectTrigger>
+ <SelectValue>{(value) => value.name}</SelectValue>
+ </SelectTrigger>
+ ...
+</Select>
+```
+
+---
+
+## ToggleGroup
+
+Base uses a `multiple` boolean prop. Radix uses `type="single"` or `type="multiple"`.
+
+**Incorrect (base):**
+
+```tsx
+<ToggleGroup type="single" defaultValue="daily">
+ <ToggleGroupItem value="daily">Daily</ToggleGroupItem>
+</ToggleGroup>
+```
+
+**Correct (base):**
+
+```tsx
+// Single (no prop needed), defaultValue is always an array.
+<ToggleGroup defaultValue={["daily"]} spacing={2}>
+ <ToggleGroupItem value="daily">Daily</ToggleGroupItem>
+ <ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
+</ToggleGroup>
+
+// Multi-selection.
+<ToggleGroup multiple>
+ <ToggleGroupItem value="bold">Bold</ToggleGroupItem>
+ <ToggleGroupItem value="italic">Italic</ToggleGroupItem>
+</ToggleGroup>
+```
+
+**Correct (radix):**
+
+```tsx
+// Single, defaultValue is a string.
+<ToggleGroup type="single" defaultValue="daily" spacing={2}>
+ <ToggleGroupItem value="daily">Daily</ToggleGroupItem>
+ <ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
+</ToggleGroup>
+
+// Multi-selection.
+<ToggleGroup type="multiple">
+ <ToggleGroupItem value="bold">Bold</ToggleGroupItem>
+ <ToggleGroupItem value="italic">Italic</ToggleGroupItem>
+</ToggleGroup>
+```
+
+**Controlled single value:**
+
+```tsx
+// base — wrap/unwrap arrays.
+const [value, setValue] = React.useState("normal")
+<ToggleGroup value={[value]} onValueChange={(v) => setValue(v[0])}>
+
+// radix — plain string.
+const [value, setValue] = React.useState("normal")
+<ToggleGroup type="single" value={value} onValueChange={setValue}>
+```
+
+---
+
+## Slider
+
+Base accepts a plain number for a single thumb. Radix always requires an array.
+
+**Incorrect (base):**
+
+```tsx
+<Slider defaultValue={[50]} max={100} step={1} />
+```
+
+**Correct (base):**
+
+```tsx
+<Slider defaultValue={50} max={100} step={1} />
+```
+
+**Correct (radix):**
+
+```tsx
+<Slider defaultValue={[50]} max={100} step={1} />
+```
+
+Both use arrays for range sliders. Controlled `onValueChange` in base may need a cast:
+
+```tsx
+// base.
+const [value, setValue] = React.useState([0.3, 0.7])
+<Slider value={value} onValueChange={(v) => setValue(v as number[])} />
+
+// radix.
+const [value, setValue] = React.useState([0.3, 0.7])
+<Slider value={value} onValueChange={setValue} />
+```
+
+---
+
+## Accordion
+
+Radix requires `type="single"` or `type="multiple"` and supports `collapsible`. `defaultValue` is a string. Base uses no `type` prop, uses `multiple` boolean, and `defaultValue` is always an array.
+
+**Incorrect (base):**
+
+```tsx
+<Accordion type="single" collapsible defaultValue="item-1">
+ <AccordionItem value="item-1">...</AccordionItem>
+</Accordion>
+```
+
+**Correct (base):**
+
+```tsx
+<Accordion defaultValue={["item-1"]}>
+ <AccordionItem value="item-1">...</AccordionItem>
+</Accordion>
+
+// Multi-select.
+<Accordion multiple defaultValue={["item-1", "item-2"]}>
+ <AccordionItem value="item-1">...</AccordionItem>
+ <AccordionItem value="item-2">...</AccordionItem>
+</Accordion>
+```
+
+**Correct (radix):**
+
+```tsx
+<Accordion type="single" collapsible defaultValue="item-1">
+ <AccordionItem value="item-1">...</AccordionItem>
+</Accordion>
+```
diff --git a/.agents/skills/shadcn/rules/chat.md b/.agents/skills/shadcn/rules/chat.md
new file mode 100644
index 00000000..8ce62fe4
--- /dev/null
+++ b/.agents/skills/shadcn/rules/chat.md
@@ -0,0 +1,224 @@
+# Chat & Messaging
+
+Components for conversation and chat UI. Compose these instead of hand-rolling
+bubbles, scroll containers, dividers, or attachment cards.
+
+Install: `npx shadcn@latest add message-scroller message bubble attachment marker`
+
+The same component names and props ship for both `base` and `radix`; only
+composition differs (`render` vs `asChild`). See [base-vs-radix.md](./base-vs-radix.md).
+
+## Contents
+
+- Scrollable threads use MessageScroller
+- Message rows use Message
+- Message surfaces use Bubble
+- Attachments use Attachment
+- System notes and dividers use Marker
+- Streaming, anchoring, and jump-to-latest are built in
+- Escape hatch: the scroller hooks
+
+---
+
+## Scrollable threads use MessageScroller
+
+A conversation that scrolls, follows new messages, restores position, or jumps
+to a message uses `MessageScroller`. Don't build a raw overflow container with
+manual scroll wiring, and don't reach for `ScrollArea`.
+
+The parts nest in a fixed order. Every direct child of the content is wrapped in
+a `MessageScrollerItem` so the scroller can measure, anchor, preserve position,
+track visibility, and jump to it. `MessageScrollerButton` sits inside
+`MessageScroller`, after the viewport.
+
+**Incorrect:**
+
+```tsx
+// Hand-rolled scroll container with manual stick-to-bottom logic.
+<div ref={scrollRef} onScroll={handleScroll} className="flex-1 overflow-y-auto">
+ <div className="flex flex-col gap-6 p-4">
+ {messages.map((m) => (
+ <ChatMessage key={m.id} message={m} />
+ ))}
+ </div>
+</div>
+```
+
+**Correct:**
+
+```tsx
+<MessageScrollerProvider autoScroll>
+ <MessageScroller>
+ <MessageScrollerViewport>
+ <MessageScrollerContent>
+ {messages.map((message) => (
+ <MessageScrollerItem
+ key={message.id}
+ messageId={message.id}
+ scrollAnchor={message.role === "user"}
+ >
+ <Message align={message.role === "user" ? "end" : "start"}>
+ {/* ...message content... */}
+ </Message>
+ </MessageScrollerItem>
+ ))}
+ </MessageScrollerContent>
+ </MessageScrollerViewport>
+ <MessageScrollerButton />
+ </MessageScroller>
+</MessageScrollerProvider>
+```
+
+---
+
+## Message rows use Message
+
+`Message` lays out a single row: avatar, header, content, footer, with
+alignment. Group consecutive rows from one sender with `MessageGroup`. Don't
+rebuild the row from flex divs.
+
+`align="end"` is the current user's side; `align="start"` is everyone else.
+
+```tsx
+<Message align="start">
+ <MessageAvatar>
+ <Avatar>
+ <AvatarImage src={sender.avatar} alt={sender.name} />
+ <AvatarFallback>{initials}</AvatarFallback>
+ </Avatar>
+ </MessageAvatar>
+ <MessageContent>
+ <MessageHeader>{sender.name}</MessageHeader>
+ <Bubble>
+ <BubbleContent>{text}</BubbleContent>
+ </Bubble>
+ <MessageFooter>{time}</MessageFooter>
+ </MessageContent>
+</Message>
+```
+
+---
+
+## Message surfaces use Bubble
+
+The colored message surface is `Bubble` + `BubbleContent`, never a styled `div`
+with `bg-muted` / `bg-primary` and hand-managed corners.
+
+- `variant`: `default`, `secondary`, `muted`, `tinted`, `outline`, `ghost`, `destructive`.
+- `align`: `start` or `end` (matches the `Message` side).
+
+`BubbleReactions` renders the reaction cluster. `side` (`top` | `bottom`) and
+`align` (`start` | `end`) position it against the bubble. Don't lay reactions out
+with absolutely-positioned `Badge`s.
+
+**Incorrect:**
+
+```tsx
+<div className="w-fit rounded-2xl bg-primary px-3 py-2 text-primary-foreground">
+ {text}
+</div>
+```
+
+**Correct:**
+
+```tsx
+<Bubble variant="default" align="end">
+ <BubbleContent>{text}</BubbleContent>
+ <BubbleReactions side="bottom" align="end">
+ <Badge variant="secondary">👍 2</Badge>
+ </BubbleReactions>
+</Bubble>
+```
+
+---
+
+## Attachments use Attachment
+
+File and image attachments use `Attachment`, not `Item` or a custom card. It
+carries upload state, so wire `state` to the real status rather than rendering a
+separate spinner.
+
+- `state`: `idle`, `uploading`, `processing`, `error`, `done`. `uploading` and
+ `processing` apply the `shimmer` animation to the title automatically.
+- `size`: `default`, `sm`, `xs`. `orientation`: `horizontal`, `vertical`.
+- Use `AttachmentGroup` to lay out several attachments in a scrolling row.
+
+```tsx
+<Attachment state="done">
+ <AttachmentMedia variant="icon">
+ <FileTextIcon />
+ </AttachmentMedia>
+ <AttachmentContent>
+ <AttachmentTitle>homepage-feedback.pdf</AttachmentTitle>
+ <AttachmentDescription>PDF · 2.4 MB</AttachmentDescription>
+ </AttachmentContent>
+ <AttachmentActions>
+ <AttachmentAction>
+ <DownloadIcon />
+ </AttachmentAction>
+ </AttachmentActions>
+</Attachment>
+```
+
+For an image, use `<AttachmentMedia variant="image">` with an `img` child.
+
+---
+
+## System notes and dividers use Marker
+
+Status lines ("Sarah joined the conversation"), date dividers ("Today"), and
+labeled separators are `Marker`, not a `Separator` plus a centered span.
+
+- `variant`: `default` (plain row), `separator` (centered label with rules on
+ each side), `border` (bottom-bordered row).
+- `MarkerIcon` holds a leading icon; `MarkerContent` holds the label.
+
+**Incorrect:**
+
+```tsx
+<div className="flex items-center gap-3 py-2">
+ <Separator className="flex-1" />
+ <span className="text-xs text-muted-foreground">Today</span>
+ <Separator className="flex-1" />
+</div>
+```
+
+**Correct:**
+
+```tsx
+<Marker variant="separator">
+ <MarkerContent>Today</MarkerContent>
+</Marker>
+```
+
+---
+
+## Streaming, anchoring, and jump-to-latest are built in
+
+`MessageScroller` handles the behavior that chat UIs usually reinvent. Don't
+write a `useStickToBottom` hook, a `ResizeObserver`, or manual `scrollTop` math.
+
+- **Follow the live edge while streaming.** `MessageScrollerProvider` with
+ `autoScroll` keeps the view pinned to new content and yields the moment the
+ user scrolls up. Streaming token updates that grow the last message are
+ followed automatically.
+- **Anchor a turn.** `scrollAnchor` on a `MessageScrollerItem` marks the row to
+ hold in view (typically the user's message that started the turn).
+- **Jump to latest.** `MessageScrollerButton` appears when the user scrolls away
+ and scrolls back on click. `direction="end"` (default) or `direction="start"`.
+ It is a self-managing control, so don't gate it behind your own scroll-position
+ state.
+
+For a "thinking…" indicator while the model generates, apply the `shimmer`
+utility to text. Don't author a custom keyframe animation. See
+[styling.md](./styling.md).
+
+---
+
+## Escape hatch: the scroller hooks
+
+For behavior the parts don't expose, read state from the hooks rather than
+re-implementing the scroller: `useMessageScroller`,
+`useMessageScrollerVisibility`, and `useMessageScrollerScrollable`. They come
+from the auto-installed `@shadcn/react` dependency, so there's nothing extra to
+install. Reach for them only when composition can't express what you need.
diff --git a/.agents/skills/shadcn/rules/composition.md b/.agents/skills/shadcn/rules/composition.md
new file mode 100644
index 00000000..a8aa4274
--- /dev/null
+++ b/.agents/skills/shadcn/rules/composition.md
@@ -0,0 +1,213 @@
+# Component Composition
+
+## Contents
+
+- Items always inside their Group component
+- Callouts use Alert
+- Empty states use Empty component
+- Toast notifications follow the project base
+- Choosing between overlay components
+- Dialog, Sheet, and Drawer always need a Title
+- Card structure
+- Button has no isPending or isLoading prop
+- TabsTrigger must be inside TabsList
+- Avatar always needs AvatarFallback
+- Use Separator instead of raw hr or border divs
+- Use Skeleton for loading placeholders
+- Use Badge instead of custom styled spans
+
+---
+
+## Items always inside their Group component
+
+Never render items directly inside the content container.
+
+**Incorrect:**
+
+```tsx
+<SelectContent>
+ <SelectItem value="apple">Apple</SelectItem>
+ <SelectItem value="banana">Banana</SelectItem>
+</SelectContent>
+```
+
+**Correct:**
+
+```tsx
+<SelectContent>
+ <SelectGroup>
+ <SelectItem value="apple">Apple</SelectItem>
+ <SelectItem value="banana">Banana</SelectItem>
+ </SelectGroup>
+</SelectContent>
+```
+
+This applies to all group-based components:
+
+| Item | Group |
+|------|-------|
+| `SelectItem`, `SelectLabel` | `SelectGroup` |
+| `DropdownMenuItem`, `DropdownMenuLabel`, `DropdownMenuSub` | `DropdownMenuGroup` |
+| `MenubarItem` | `MenubarGroup` |
+| `ContextMenuItem` | `ContextMenuGroup` |
+| `CommandItem` | `CommandGroup` |
+| `MessageScrollerItem` | `MessageScrollerContent` |
+| `Message` (consecutive, same sender) | `MessageGroup` |
+| `Bubble` (stacked) | `BubbleGroup` |
+| `Attachment` (in a row) | `AttachmentGroup` |
+
+Chat components nest in a fixed order (`MessageScrollerProvider` → `MessageScroller` → `MessageScrollerViewport` → `MessageScrollerContent` → `MessageScrollerItem`). See [chat.md](./chat.md).
+
+---
+
+## Callouts use Alert
+
+```tsx
+<Alert>
+ <AlertTitle>Warning</AlertTitle>
+ <AlertDescription>Something needs attention.</AlertDescription>
+</Alert>
+```
+
+---
+
+## Empty states use Empty component
+
+```tsx
+<Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon"><FolderIcon /></EmptyMedia>
+ <EmptyTitle>No projects yet</EmptyTitle>
+ <EmptyDescription>Get started by creating a new project.</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button>Create Project</Button>
+ </EmptyContent>
+</Empty>
+```
+
+---
+
+## Toast notifications follow the project base
+
+For Base UI projects, use the `toast` component:
+
+```tsx
+import { toast } from "@/components/ui/toast"
+
+toast.add({
+ title: "Changes saved.",
+})
+```
+
+For Radix and React Aria projects, use Sonner:
+
+```tsx
+import { toast } from "sonner"
+
+toast.success("Changes saved.")
+toast.error("Something went wrong.")
+toast("File deleted.", {
+ action: { label: "Undo", onClick: () => undoDelete() },
+})
+```
+
+---
+
+## Choosing between overlay components
+
+| Use case | Component |
+|----------|-----------|
+| Focused task that requires input | `Dialog` |
+| Destructive action confirmation | `AlertDialog` |
+| Side panel with details or filters | `Sheet` |
+| Mobile-first bottom panel | `Drawer` |
+| Quick info on hover | `HoverCard` |
+| Small contextual content on click | `Popover` |
+
+---
+
+## Dialog, Sheet, and Drawer always need a Title
+
+`DialogTitle`, `SheetTitle`, `DrawerTitle` are required for accessibility. Use `className="sr-only"` if visually hidden.
+
+```tsx
+<DialogContent>
+ <DialogHeader>
+ <DialogTitle>Edit Profile</DialogTitle>
+ <DialogDescription>Update your profile.</DialogDescription>
+ </DialogHeader>
+ ...
+</DialogContent>
+```
+
+---
+
+## Card structure
+
+Use full composition — don't dump everything into `CardContent`:
+
+```tsx
+<Card>
+ <CardHeader>
+ <CardTitle>Team Members</CardTitle>
+ <CardDescription>Manage your team.</CardDescription>
+ </CardHeader>
+ <CardContent>...</CardContent>
+ <CardFooter>
+ <Button>Invite</Button>
+ </CardFooter>
+</Card>
+```
+
+---
+
+## Button has no isPending or isLoading prop
+
+Compose with `Spinner` + `data-icon` + `disabled`:
+
+```tsx
+<Button disabled>
+ <Spinner data-icon="inline-start" />
+ Saving...
+</Button>
+```
+
+---
+
+## TabsTrigger must be inside TabsList
+
+Never render `TabsTrigger` directly inside `Tabs` — always wrap in `TabsList`:
+
+```tsx
+<Tabs defaultValue="account">
+ <TabsList>
+ <TabsTrigger value="account">Account</TabsTrigger>
+ <TabsTrigger value="password">Password</TabsTrigger>
+ </TabsList>
+ <TabsContent value="account">...</TabsContent>
+</Tabs>
+```
+
+---
+
+## Avatar always needs AvatarFallback
+
+Always include `AvatarFallback` for when the image fails to load:
+
+```tsx
+<Avatar>
+ <AvatarImage src="/avatar.png" alt="User" />
+ <AvatarFallback>JD</AvatarFallback>
+</Avatar>
+```
+
+---
+
+## Use existing components instead of custom markup
+
+| Instead of | Use |
+|---|---|
+| `<hr>` or `<div className="border-t">` | `<Separator />` |
+| `<div className="animate-pulse">` with styled divs | `<Skeleton className="h-4 w-3/4" />` |
+| `<span className="rounded-full bg-green-100 ...">` | `<Badge variant="secondary">` |
diff --git a/.agents/skills/shadcn/rules/forms.md b/.agents/skills/shadcn/rules/forms.md
new file mode 100644
index 00000000..f451e2f7
--- /dev/null
+++ b/.agents/skills/shadcn/rules/forms.md
@@ -0,0 +1,192 @@
+# Forms & Inputs
+
+## Contents
+
+- Forms use FieldGroup + Field
+- InputGroup requires InputGroupInput/InputGroupTextarea
+- Buttons inside inputs use InputGroup + InputGroupAddon
+- Option sets (2–7 choices) use ToggleGroup
+- FieldSet + FieldLegend for grouping related fields
+- Field validation and disabled states
+
+---
+
+## Forms use FieldGroup + Field
+
+Always use `FieldGroup` + `Field` — never raw `div` with `space-y-*`:
+
+```tsx
+<FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="email">Email</FieldLabel>
+ <Input id="email" type="email" />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="password">Password</FieldLabel>
+ <Input id="password" type="password" />
+ </Field>
+</FieldGroup>
+```
+
+Use `Field orientation="horizontal"` for settings pages. Use `FieldLabel className="sr-only"` for visually hidden labels.
+
+**Choosing form controls:**
+
+- Simple text input → `Input`
+- Dropdown with predefined options → `Select`
+- Searchable dropdown → `Combobox`
+- Native HTML select (no JS) → `native-select`
+- Boolean toggle → `Switch` (for settings) or `Checkbox` (for forms)
+- Single choice from few options → `RadioGroup`
+- Toggle between 2–5 options → `ToggleGroup` + `ToggleGroupItem`
+- OTP/verification code → `InputOTP`
+- Multi-line text → `Textarea`
+
+---
+
+## InputGroup requires InputGroupInput/InputGroupTextarea
+
+Never use raw `Input` or `Textarea` inside an `InputGroup`.
+
+**Incorrect:**
+
+```tsx
+<InputGroup>
+ <Input placeholder="Search..." />
+</InputGroup>
+```
+
+**Correct:**
+
+```tsx
+import { InputGroup, InputGroupInput } from "@/components/ui/input-group"
+
+<InputGroup>
+ <InputGroupInput placeholder="Search..." />
+</InputGroup>
+```
+
+---
+
+## Buttons inside inputs use InputGroup + InputGroupAddon
+
+Never place a `Button` directly inside or adjacent to an `Input` with custom positioning.
+
+**Incorrect:**
+
+```tsx
+<div className="relative">
+ <Input placeholder="Search..." className="pr-10" />
+ <Button className="absolute right-0 top-0" size="icon">
+ <SearchIcon />
+ </Button>
+</div>
+```
+
+**Correct:**
+
+```tsx
+import { InputGroup, InputGroupInput, InputGroupAddon } from "@/components/ui/input-group"
+
+<InputGroup>
+ <InputGroupInput placeholder="Search..." />
+ <InputGroupAddon>
+ <Button size="icon">
+ <SearchIcon data-icon="inline-start" />
+ </Button>
+ </InputGroupAddon>
+</InputGroup>
+```
+
+---
+
+## Option sets (2–7 choices) use ToggleGroup
+
+Don't manually loop `Button` components with active state.
+
+**Incorrect:**
+
+```tsx
+const [selected, setSelected] = useState("daily")
+
+<div className="flex gap-2">
+ {["daily", "weekly", "monthly"].map((option) => (
+ <Button
+ key={option}
+ variant={selected === option ? "default" : "outline"}
+ onClick={() => setSelected(option)}
+ >
+ {option}
+ </Button>
+ ))}
+</div>
+```
+
+**Correct:**
+
+```tsx
+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
+
+<ToggleGroup spacing={2}>
+ <ToggleGroupItem value="daily">Daily</ToggleGroupItem>
+ <ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
+ <ToggleGroupItem value="monthly">Monthly</ToggleGroupItem>
+</ToggleGroup>
+```
+
+Combine with `Field` for labelled toggle groups:
+
+```tsx
+<Field orientation="horizontal">
+ <FieldTitle id="theme-label">Theme</FieldTitle>
+ <ToggleGroup aria-labelledby="theme-label" spacing={2}>
+ <ToggleGroupItem value="light">Light</ToggleGroupItem>
+ <ToggleGroupItem value="dark">Dark</ToggleGroupItem>
+ <ToggleGroupItem value="system">System</ToggleGroupItem>
+ </ToggleGroup>
+</Field>
+```
+
+> **Note:** `defaultValue` and `type`/`multiple` props differ between base and radix. See [base-vs-radix.md](./base-vs-radix.md#togglegroup).
+
+---
+
+## FieldSet + FieldLegend for grouping related fields
+
+Use `FieldSet` + `FieldLegend` for related checkboxes, radios, or switches — not `div` with a heading:
+
+```tsx
+<FieldSet>
+ <FieldLegend variant="label">Preferences</FieldLegend>
+ <FieldDescription>Select all that apply.</FieldDescription>
+ <FieldGroup className="gap-3">
+ <Field orientation="horizontal">
+ <Checkbox id="dark" />
+ <FieldLabel htmlFor="dark" className="font-normal">Dark mode</FieldLabel>
+ </Field>
+ </FieldGroup>
+</FieldSet>
+```
+
+---
+
+## Field validation and disabled states
+
+Both attributes are needed — `data-invalid`/`data-disabled` styles the field (label, description), while `aria-invalid`/`disabled` styles the control.
+
+```tsx
+// Invalid.
+<Field data-invalid>
+ <FieldLabel htmlFor="email">Email</FieldLabel>
+ <Input id="email" aria-invalid />
+ <FieldDescription>Invalid email address.</FieldDescription>
+</Field>
+
+// Disabled.
+<Field data-disabled>
+ <FieldLabel htmlFor="email">Email</FieldLabel>
+ <Input id="email" disabled />
+</Field>
+```
+
+Works for all controls: `Input`, `Textarea`, `Select`, `Checkbox`, `RadioGroupItem`, `Switch`, `Slider`, `NativeSelect`, `InputOTP`.
diff --git a/.agents/skills/shadcn/rules/icons.md b/.agents/skills/shadcn/rules/icons.md
new file mode 100644
index 00000000..bba8102f
--- /dev/null
+++ b/.agents/skills/shadcn/rules/icons.md
@@ -0,0 +1,101 @@
+# Icons
+
+**Always use the project's configured `iconLibrary` for imports.** Check the `iconLibrary` field from project context: `lucide` → `lucide-react`, `tabler` → `@tabler/icons-react`, etc. Never assume `lucide-react`.
+
+---
+
+## Icons in Button use data-icon attribute
+
+Add `data-icon="inline-start"` (prefix) or `data-icon="inline-end"` (suffix) to the icon. No sizing classes on the icon.
+
+**Incorrect:**
+
+```tsx
+<Button>
+ <SearchIcon className="mr-2 size-4" />
+ Search
+</Button>
+```
+
+**Correct:**
+
+```tsx
+<Button>
+ <SearchIcon data-icon="inline-start"/>
+ Search
+</Button>
+
+<Button>
+ Next
+ <ArrowRightIcon data-icon="inline-end"/>
+</Button>
+```
+
+---
+
+## No sizing classes on icons inside components
+
+Components handle icon sizing via CSS. Don't add `size-4`, `w-4 h-4`, or other sizing classes to icons inside `Button`, `DropdownMenuItem`, `Alert`, `Sidebar*`, or other shadcn components. Unless the user explicitly asks for custom icon sizes.
+
+**Incorrect:**
+
+```tsx
+<Button>
+ <SearchIcon className="size-4" data-icon="inline-start" />
+ Search
+</Button>
+
+<DropdownMenuItem>
+ <SettingsIcon className="mr-2 size-4" />
+ Settings
+</DropdownMenuItem>
+```
+
+**Correct:**
+
+```tsx
+<Button>
+ <SearchIcon data-icon="inline-start" />
+ Search
+</Button>
+
+<DropdownMenuItem>
+ <SettingsIcon />
+ Settings
+</DropdownMenuItem>
+```
+
+---
+
+## Pass icons as component objects, not string keys
+
+Use `icon={CheckIcon}`, not a string key to a lookup map.
+
+**Incorrect:**
+
+```tsx
+const iconMap = {
+ check: CheckIcon,
+ alert: AlertIcon,
+}
+
+function StatusBadge({ icon }: { icon: string }) {
+ const Icon = iconMap[icon]
+ return <Icon />
+}
+
+<StatusBadge icon="check" />
+```
+
+**Correct:**
+
+```tsx
+// Import from the project's configured iconLibrary (e.g. lucide-react, @tabler/icons-react).
+import { CheckIcon } from "lucide-react"
+
+function StatusBadge({ icon: Icon }: { icon: React.ComponentType }) {
+ return <Icon />
+}
+
+<StatusBadge icon={CheckIcon} />
+```
diff --git a/.agents/skills/shadcn/rules/styling.md b/.agents/skills/shadcn/rules/styling.md
new file mode 100644
index 00000000..fe751979
--- /dev/null
+++ b/.agents/skills/shadcn/rules/styling.md
@@ -0,0 +1,185 @@
+# Styling & Customization
+
+See [customization.md](../customization.md) for theming, CSS variables, and adding custom colors.
+
+## Contents
+
+- Semantic colors
+- Built-in variants first
+- className for layout only
+- No space-x-* / space-y-*
+- Prefer size-* over w-* h-* when equal
+- Prefer truncate shorthand
+- No manual dark: color overrides
+- Use cn() for conditional classes
+- No manual z-index on overlay components
+- Use shimmer / scroll-fade utilities, not custom animations
+
+---
+
+## Semantic colors
+
+**Incorrect:**
+
+```tsx
+<div className="bg-blue-500 text-white">
+ <p className="text-gray-600">Secondary text</p>
+</div>
+```
+
+**Correct:**
+
+```tsx
+<div className="bg-primary text-primary-foreground">
+ <p className="text-muted-foreground">Secondary text</p>
+</div>
+```
+
+---
+
+## No raw color values for status/state indicators
+
+For positive, negative, or status indicators, use Badge variants, semantic tokens like `text-destructive`, or define custom CSS variables — don't reach for raw Tailwind colors.
+
+**Incorrect:**
+
+```tsx
+<span className="text-emerald-600">+20.1%</span>
+<span className="text-green-500">Active</span>
+<span className="text-red-600">-3.2%</span>
+```
+
+**Correct:**
+
+```tsx
+<Badge variant="secondary">+20.1%</Badge>
+<Badge>Active</Badge>
+<span className="text-destructive">-3.2%</span>
+```
+
+If you need a success/positive color that doesn't exist as a semantic token, use a Badge variant or ask the user about adding a custom CSS variable to the theme (see [customization.md](../customization.md)).
+
+---
+
+## Built-in variants first
+
+**Incorrect:**
+
+```tsx
+<Button className="border border-input bg-transparent hover:bg-accent">
+ Click me
+</Button>
+```
+
+**Correct:**
+
+```tsx
+<Button variant="outline">Click me</Button>
+```
+
+---
+
+## className for layout only
+
+Use `className` for layout (e.g. `max-w-md`, `mx-auto`, `mt-4`), **not** for overriding component colors or typography. To change colors, use semantic tokens, built-in variants, or CSS variables.
+
+**Incorrect:**
+
+```tsx
+<Card className="bg-blue-100 text-blue-900 font-bold">
+ <CardContent>Dashboard</CardContent>
+</Card>
+```
+
+**Correct:**
+
+```tsx
+<Card className="max-w-md mx-auto">
+ <CardContent>Dashboard</CardContent>
+</Card>
+```
+
+To customize a component's appearance, prefer these approaches in order:
+1. **Built-in variants** — `variant="outline"`, `variant="destructive"`, etc.
+2. **Semantic color tokens** — `bg-primary`, `text-muted-foreground`.
+3. **CSS variables** — define custom colors in the global CSS file (see [customization.md](../customization.md)).
+
+---
+
+## No space-x-* / space-y-*
+
+Use `gap-*` instead. `space-y-4` → `flex flex-col gap-4`. `space-x-2` → `flex gap-2`.
+
+```tsx
+<div className="flex flex-col gap-4">
+ <Input />
+ <Input />
+ <Button>Submit</Button>
+</div>
+```
+
+---
+
+## Prefer size-* over w-* h-* when equal
+
+`size-10` not `w-10 h-10`. Applies to icons, avatars, skeletons, etc.
+
+---
+
+## Prefer truncate shorthand
+
+`truncate` not `overflow-hidden text-ellipsis whitespace-nowrap`.
+
+---
+
+## No manual dark: color overrides
+
+Use semantic tokens — they handle light/dark via CSS variables. `bg-background text-foreground` not `bg-white dark:bg-gray-950`.
+
+---
+
+## Use cn() for conditional classes
+
+Use the `cn()` utility from the project for conditional or merged class names. Don't write manual ternaries in className strings.
+
+**Incorrect:**
+
+```tsx
+<div className={`flex items-center ${isActive ? "bg-primary text-primary-foreground" : "bg-muted"}`}>
+```
+
+**Correct:**
+
+```tsx
+import { cn } from "@/lib/utils"
+
+<div className={cn("flex items-center", isActive ? "bg-primary text-primary-foreground" : "bg-muted")}>
+```
+
+---
+
+## No manual z-index on overlay components
+
+`Dialog`, `Sheet`, `Drawer`, `AlertDialog`, `DropdownMenu`, `Popover`, `Tooltip`, `HoverCard` handle their own stacking. Never add `z-50` or `z-[999]`.
+
+---
+
+## Use shimmer / scroll-fade utilities, not custom animations
+
+For a live "thinking…" or loading-text shimmer, apply the `shimmer` utility. Don't author a custom `@keyframes` or a `bg-clip-text` gradient sweep.
+
+For scroll-aware edge fading on a scroll container, use `scroll-fade` (and the axis variants `scroll-fade-x` / `scroll-fade-b`). Don't hand-roll mask gradients. The chat components already apply these internally: `Attachment` shimmers its title during upload, and `MessageScrollerViewport` fades its edges.
+
+**Incorrect:**
+
+```tsx
+<span className="animate-pulse bg-gradient-to-r from-muted-foreground/40 via-foreground/70 to-muted-foreground/40 bg-clip-text text-transparent [animation:shimmer_1.6s_infinite]">
+ Thinking…
+</span>
+```
+
+**Correct:**
+
+```tsx
+<span className="shimmer">Thinking…</span>
+```
diff --git a/.agents/skills/skill-creator/LICENSE.txt b/.agents/skills/skill-creator/LICENSE.txt
new file mode 100644
index 00000000..4f881c52
--- /dev/null
+++ b/.agents/skills/skill-creator/LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 Anthropic, PBC.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/.agents/skills/skill-creator/SKILL.md b/.agents/skills/skill-creator/SKILL.md
new file mode 100644
index 00000000..65b3a402
--- /dev/null
+++ b/.agents/skills/skill-creator/SKILL.md
@@ -0,0 +1,485 @@
+---
+name: skill-creator
+description: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.
+---
+
+# Skill Creator
+
+A skill for creating new skills and iteratively improving them.
+
+At a high level, the process of creating a skill goes like this:
+
+- Decide what you want the skill to do and roughly how it should do it
+- Write a draft of the skill
+- Create a few test prompts and run claude-with-access-to-the-skill on them
+- Help the user evaluate the results both qualitatively and quantitatively
+ - While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist)
+ - Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics
+- Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks)
+- Repeat until you're satisfied
+- Expand the test set and try again at larger scale
+
+Your job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like "I want to make a skill for X". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat.
+
+On the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop.
+
+Of course, you should always be flexible and if the user is like "I don't need to run a bunch of evaluations, just vibe with me", you can do that instead.
+
+Then after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill.
+
+Cool? Cool.
+
+## Communicating with the user
+
+The skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of Claude is inspiring plumbers to open up their terminals, parents and grandparents to google "how to install npm". On the other hand, the bulk of users are probably fairly computer-literate.
+
+So please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea:
+
+- "evaluation" and "benchmark" are borderline, but OK
+- for "JSON" and "assertion" you want to see serious cues from the user that they know what those things are before using them without explaining them
+
+It's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it.
+
+---
+
+## Creating a skill
+
+### Capture Intent
+
+Start by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say "turn this into a skill"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step.
+
+1. What should this skill enable Claude to do?
+2. When should this skill trigger? (what user phrases/contexts)
+3. What's the expected output format?
+4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide.
+
+### Interview and Research
+
+Proactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out.
+
+Check available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user.
+
+### Write the SKILL.md
+
+Based on the user interview, fill in these components:
+
+- **name**: Skill identifier
+- **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All "when to use" info goes here, not in the body. Note: currently Claude has a tendency to "undertrigger" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit "pushy". So for instance, instead of "How to build a simple fast dashboard to display internal Anthropic data.", you might write "How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'"
+- **compatibility**: Required tools, dependencies (optional, rarely needed)
+- **the rest of the skill :)**
+
+### Skill Writing Guide
+
+#### Anatomy of a Skill
+
+```
+skill-name/
+├── SKILL.md (required)
+│ ├── YAML frontmatter (name, description required)
+│ └── Markdown instructions
+└── Bundled Resources (optional)
+ ├── scripts/ - Executable code for deterministic/repetitive tasks
+ ├── references/ - Docs loaded into context as needed
+ └── assets/ - Files used in output (templates, icons, fonts)
+```
+
+#### Progressive Disclosure
+
+Skills use a three-level loading system:
+1. **Metadata** (name + description) - Always in context (~100 words)
+2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal)
+3. **Bundled resources** - As needed (unlimited, scripts can execute without loading)
+
+These word counts are approximate and you can feel free to go longer if needed.
+
+**Key patterns:**
+- Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up.
+- Reference files clearly from SKILL.md with guidance on when to read them
+- For large reference files (>300 lines), include a table of contents
+
+**Domain organization**: When a skill supports multiple domains/frameworks, organize by variant:
+```
+cloud-deploy/
+├── SKILL.md (workflow + selection)
+└── references/
+ ├── aws.md
+ ├── gcp.md
+ └── azure.md
+```
+Claude reads only the relevant reference file.
+
+#### Principle of Lack of Surprise
+
+This goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a "roleplay as an XYZ" are OK though.
+
+#### Writing Patterns
+
+Prefer using the imperative form in instructions.
+
+**Defining output formats** - You can do it like this:
+```markdown
+## Report structure
+ALWAYS use this exact template:
+# [Title]
+## Executive summary
+## Key findings
+## Recommendations
+```
+
+**Examples pattern** - It's useful to include examples. You can format them like this (but if "Input" and "Output" are in the examples you might want to deviate a little):
+```markdown
+## Commit message format
+**Example 1:**
+Input: Added user authentication with JWT tokens
+Output: feat(auth): implement JWT-based authentication
+```
+
+### Writing Style
+
+Try to explain to the model why things are important in lieu of heavy-handed musty MUSTs. Use theory of mind and try to make the skill general and not super-narrow to specific examples. Start by writing a draft and then look at it with fresh eyes and improve it.
+
+### Test Cases
+
+After writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] "Here are a few test cases I'd like to try. Do these look right, or do you want to add more?" Then run them.
+
+Save test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress.
+
+```json
+{
+ "skill_name": "example-skill",
+ "evals": [
+ {
+ "id": 1,
+ "prompt": "User's task prompt",
+ "expected_output": "Description of expected result",
+ "files": []
+ }
+ ]
+}
+```
+
+See `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later).
+
+## Running and evaluating test cases
+
+This section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill.
+
+Put results in `<skill-name>-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go.
+
+### Step 1: Spawn all runs (with-skill AND baseline) in the same turn
+
+For each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time.
+
+**With-skill run:**
+
+```
+Execute this task:
+- Skill path: <path-to-skill>
+- Task: <eval prompt>
+- Input files: <eval files if any, or "none">
+- Save outputs to: <workspace>/iteration-<N>/eval-<ID>/with_skill/outputs/
+- Outputs to save: <what the user cares about — e.g., "the .docx file", "the final CSV">
+```
+
+**Baseline run** (same prompt, but the baseline depends on context):
+- **Creating a new skill**: no skill at all. Same prompt, no skill path, save to `without_skill/outputs/`.
+- **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r <skill-path> <workspace>/skill-snapshot/`), then point the baseline subagent at the snapshot. Save to `old_skill/outputs/`.
+
+Write an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just "eval-0". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations.
+
+```json
+{
+ "eval_id": 0,
+ "eval_name": "descriptive-name-here",
+ "prompt": "The user's task prompt",
+ "assertions": []
+}
+```
+
+### Step 2: While runs are in progress, draft assertions
+
+Don't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check.
+
+Good assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment.
+
+Update the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark.
+
+### Step 3: As runs complete, capture timing data
+
+When each subagent task completes, you receive a notification containing `total_tokens` and `duration_ms`. Save this data immediately to `timing.json` in the run directory:
+
+```json
+{
+ "total_tokens": 84852,
+ "duration_ms": 23332,
+ "total_duration_seconds": 23.3
+}
+```
+
+This is the only opportunity to capture this data — it comes through the task notification and isn't persisted elsewhere. Process each notification as it arrives rather than trying to batch them.
+
+### Step 4: Grade, aggregate, and launch the viewer
+
+Once all runs are done:
+
+1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations.
+
+2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory:
+ ```bash
+ python -m scripts.aggregate_benchmark <workspace>/iteration-N --skill-name <name>
+ ```
+ This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects.
+Put each with_skill version before its baseline counterpart.
+
+3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the "Analyzing Benchmark Results" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs.
+
+4. **Launch the viewer** with both qualitative outputs and quantitative data:
+ ```bash
+ nohup python <skill-creator-path>/eval-viewer/generate_review.py \
+ <workspace>/iteration-N \
+ --skill-name "my-skill" \
+ --benchmark <workspace>/iteration-N/benchmark.json \
+ > /dev/null 2>&1 &
+ VIEWER_PID=$!
+ ```
+ For iteration 2+, also pass `--previous-workspace <workspace>/iteration-<N-1>`.
+
+ **Cowork / headless environments:** If `webbrowser.open()` is not available or the environment has no display, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Feedback will be downloaded as a `feedback.json` file when the user clicks "Submit All Reviews". After download, copy `feedback.json` into the workspace directory for the next iteration to pick up.
+
+Note: please use generate_review.py to create the viewer; there's no need to write custom HTML.
+
+5. **Tell the user** something like: "I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know."
+
+### What the user sees in the viewer
+
+The "Outputs" tab shows one test case at a time:
+- **Prompt**: the task that was given
+- **Output**: the files the skill produced, rendered inline where possible
+- **Previous Output** (iteration 2+): collapsed section showing last iteration's output
+- **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail
+- **Feedback**: a textbox that auto-saves as they type
+- **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox
+
+The "Benchmark" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations.
+
+Navigation is via prev/next buttons or arrow keys. When done, they click "Submit All Reviews" which saves all feedback to `feedback.json`.
+
+### Step 5: Read the feedback
+
+When the user tells you they're done, read `feedback.json`:
+
+```json
+{
+ "reviews": [
+ {"run_id": "eval-0-with_skill", "feedback": "the chart is missing axis labels", "timestamp": "..."},
+ {"run_id": "eval-1-with_skill", "feedback": "", "timestamp": "..."},
+ {"run_id": "eval-2-with_skill", "feedback": "perfect, love this", "timestamp": "..."}
+ ],
+ "status": "complete"
+}
+```
+
+Empty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints.
+
+Kill the viewer server when you're done with it:
+
+```bash
+kill $VIEWER_PID 2>/dev/null
+```
+
+---
+
+## Improving the skill
+
+This is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback.
+
+### How to think about improvements
+
+1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great.
+
+2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens.
+
+3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are *smart*. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach.
+
+4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel.
+
+This task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need.
+
+### The iteration loop
+
+After improving the skill:
+
+1. Apply your improvements to the skill
+2. Rerun all test cases into a new `iteration-<N+1>/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration.
+3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration
+4. Wait for the user to review and tell you they're done
+5. Read the new feedback, improve again, repeat
+
+Keep going until:
+- The user says they're happy
+- The feedback is all empty (everything looks good)
+- You're not making meaningful progress
+
+---
+
+## Advanced: Blind comparison
+
+For situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks "is the new version actually better?"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won.
+
+This is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient.
+
+---
+
+## Description Optimization
+
+The description field in SKILL.md frontmatter is the primary mechanism that determines whether Claude invokes a skill. After creating or improving a skill, offer to optimize the description for better triggering accuracy.
+
+### Step 1: Generate trigger eval queries
+
+Create 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON:
+
+```json
+[
+ {"query": "the user prompt", "should_trigger": true},
+ {"query": "another prompt", "should_trigger": false}
+]
+```
+
+The queries must be realistic and something a Claude Code or Claude.ai user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them).
+
+Bad: `"Format this data"`, `"Extract text from PDF"`, `"Create a chart"`
+
+Good: `"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think"`
+
+For the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win.
+
+For the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate.
+
+The key thing to avoid: don't make should-not-trigger queries obviously irrelevant. "Write a fibonacci function" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky.
+
+### Step 2: Review with user
+
+Present the eval set to the user for review using the HTML template:
+
+1. Read the template from `assets/eval_review.html`
+2. Replace the placeholders:
+ - `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment)
+ - `__SKILL_NAME_PLACEHOLDER__` → the skill's name
+ - `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description
+3. Write to a temp file (e.g., `/tmp/eval_review_<skill-name>.html`) and open it: `open /tmp/eval_review_<skill-name>.html`
+4. The user can edit queries, toggle should-trigger, add/remove entries, then click "Export Eval Set"
+5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`)
+
+This step matters — bad eval queries lead to bad descriptions.
+
+### Step 3: Run the optimization loop
+
+Tell the user: "This will take some time — I'll run the optimization loop in the background and check on it periodically."
+
+Save the eval set to the workspace, then run in the background:
+
+```bash
+python -m scripts.run_loop \
+ --eval-set <path-to-trigger-eval.json> \
+ --skill-path <path-to-skill> \
+ --model <model-id-powering-this-session> \
+ --max-iterations 5 \
+ --verbose
+```
+
+Use the model ID from your system prompt (the one powering the current session) so the triggering test matches what the user actually experiences.
+
+While it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like.
+
+This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting.
+
+### How skill triggering works
+
+Understanding the triggering mechanism helps design better eval queries. Skills appear in Claude's `available_skills` list with their name + description, and Claude decides whether to consult a skill based on that description. The important thing to know is that Claude only consults skills for tasks it can't easily handle on its own — simple, one-step queries like "read this PDF" may not trigger a skill even if the description matches perfectly, because Claude can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches.
+
+This means your eval queries should be substantive enough that Claude would actually benefit from consulting a skill. Simple queries like "read file X" are poor test cases — they won't trigger skills regardless of description quality.
+
+### Step 4: Apply the result
+
+Take `best_description` from the JSON output and update the skill's SKILL.md frontmatter. Show the user before/after and report the scores.
+
+---
+
+### Package and Present (only if `present_files` tool is available)
+
+Check whether you have access to the `present_files` tool. If you don't, skip this step. If you do, package the skill and present the .skill file to the user:
+
+```bash
+python -m scripts.package_skill <path/to/skill-folder>
+```
+
+After packaging, direct the user to the resulting `.skill` file path so they can install it.
+
+---
+
+## Claude.ai-specific instructions
+
+In Claude.ai, the core workflow is the same (draft → test → review → improve → repeat), but because Claude.ai doesn't have subagents, some mechanics change. Here's what to adapt:
+
+**Running test cases**: No subagents means no parallel execution. For each test case, read the skill's SKILL.md, then follow its instructions to accomplish the test prompt yourself. Do them one at a time. This is less rigorous than independent subagents (you wrote the skill and you're also running it, so you have full context), but it's a useful sanity check — and the human review step compensates. Skip the baseline runs — just use the skill to complete the task as requested.
+
+**Reviewing results**: If you can't open a browser (e.g., Claude.ai's VM has no display, or you're on a remote server), skip the browser reviewer entirely. Instead, present results directly in the conversation. For each test case, show the prompt and the output. If the output is a file the user needs to see (like a .docx or .xlsx), save it to the filesystem and tell them where it is so they can download and inspect it. Ask for feedback inline: "How does this look? Anything you'd change?"
+
+**Benchmarking**: Skip the quantitative benchmarking — it relies on baseline comparisons which aren't meaningful without subagents. Focus on qualitative feedback from the user.
+
+**The iteration loop**: Same as before — improve the skill, rerun the test cases, ask for feedback — just without the browser reviewer in the middle. You can still organize results into iteration directories on the filesystem if you have one.
+
+**Description optimization**: This section requires the `claude` CLI tool (specifically `claude -p`) which is only available in Claude Code. Skip it if you're on Claude.ai.
+
+**Blind comparison**: Requires subagents. Skip it.
+
+**Packaging**: The `package_skill.py` script works anywhere with Python and a filesystem. On Claude.ai, you can run it and the user can download the resulting `.skill` file.
+
+**Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. In this case:
+- **Preserve the original name.** Note the skill's directory name and `name` frontmatter field -- use them unchanged. E.g., if the installed skill is `research-helper`, output `research-helper.skill` (not `research-helper-v2`).
+- **Copy to a writeable location before editing.** The installed skill path may be read-only. Copy to `/tmp/skill-name/`, edit there, and package from the copy.
+- **If packaging manually, stage in `/tmp/` first**, then copy to the output directory -- direct writes may fail due to permissions.
+
+---
+
+## Cowork-Specific Instructions
+
+If you're in Cowork, the main things to know are:
+
+- You have subagents, so the main workflow (spawn test cases in parallel, run baselines, grade, etc.) all works. (However, if you run into severe problems with timeouts, it's OK to run the test prompts in series rather than parallel.)
+- You don't have a browser or display, so when generating the eval viewer, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Then proffer a link that the user can click to open the HTML in their browser.
+- For whatever reason, the Cowork setup seems to disincline Claude from generating the eval viewer after running the tests, so just to reiterate: whether you're in Cowork or in Claude Code, after running tests, you should always generate the eval viewer for the human to look at examples before revising the skill yourself and trying to make corrections, using `generate_review.py` (not writing your own boutique html code). Sorry in advance but I'm gonna go all caps here: GENERATE THE EVAL VIEWER *BEFORE* evaluating inputs yourself. You want to get them in front of the human ASAP!
+- Feedback works differently: since there's no running server, the viewer's "Submit All Reviews" button will download `feedback.json` as a file. You can then read it from there (you may have to request access first).
+- Packaging works — `package_skill.py` just needs Python and a filesystem.
+- Description optimization (`run_loop.py` / `run_eval.py`) should work in Cowork just fine since it uses `claude -p` via subprocess, not a browser, but please save it until you've fully finished making the skill and the user agrees it's in good shape.
+- **Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. Follow the update guidance in the claude.ai section above.
+
+---
+
+## Reference files
+
+The agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent.
+
+- `agents/grader.md` — How to evaluate assertions against outputs
+- `agents/comparator.md` — How to do blind A/B comparison between two outputs
+- `agents/analyzer.md` — How to analyze why one version beat another
+
+The references/ directory has additional documentation:
+- `references/schemas.md` — JSON structures for evals.json, grading.json, etc.
+
+---
+
+Repeating one more time the core loop here for emphasis:
+
+- Figure out what the skill is about
+- Draft or edit the skill
+- Run claude-with-access-to-the-skill on test prompts
+- With the user, evaluate the outputs:
+ - Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them
+ - Run quantitative evals
+- Repeat until you and the user are satisfied
+- Package the final skill and return it to the user.
+
+Please add steps to your TodoList, if you have such a thing, to make sure you don't forget. If you're in Cowork, please specifically put "Create evals JSON and run `eval-viewer/generate_review.py` so human can review test cases" in your TodoList to make sure it happens.
+
+Good luck!
diff --git a/.agents/skills/skill-creator/agents/analyzer.md b/.agents/skills/skill-creator/agents/analyzer.md
new file mode 100644
index 00000000..14e41d60
--- /dev/null
+++ b/.agents/skills/skill-creator/agents/analyzer.md
@@ -0,0 +1,274 @@
+# Post-hoc Analyzer Agent
+
+Analyze blind comparison results to understand WHY the winner won and generate improvement suggestions.
+
+## Role
+
+After the blind comparator determines a winner, the Post-hoc Analyzer "unblids" the results by examining the skills and transcripts. The goal is to extract actionable insights: what made the winner better, and how can the loser be improved?
+
+## Inputs
+
+You receive these parameters in your prompt:
+
+- **winner**: "A" or "B" (from blind comparison)
+- **winner_skill_path**: Path to the skill that produced the winning output
+- **winner_transcript_path**: Path to the execution transcript for the winner
+- **loser_skill_path**: Path to the skill that produced the losing output
+- **loser_transcript_path**: Path to the execution transcript for the loser
+- **comparison_result_path**: Path to the blind comparator's output JSON
+- **output_path**: Where to save the analysis results
+
+## Process
+
+### Step 1: Read Comparison Result
+
+1. Read the blind comparator's output at comparison_result_path
+2. Note the winning side (A or B), the reasoning, and any scores
+3. Understand what the comparator valued in the winning output
+
+### Step 2: Read Both Skills
+
+1. Read the winner skill's SKILL.md and key referenced files
+2. Read the loser skill's SKILL.md and key referenced files
+3. Identify structural differences:
+ - Instructions clarity and specificity
+ - Script/tool usage patterns
+ - Example coverage
+ - Edge case handling
+
+### Step 3: Read Both Transcripts
+
+1. Read the winner's transcript
+2. Read the loser's transcript
+3. Compare execution patterns:
+ - How closely did each follow their skill's instructions?
+ - What tools were used differently?
+ - Where did the loser diverge from optimal behavior?
+ - Did either encounter errors or make recovery attempts?
+
+### Step 4: Analyze Instruction Following
+
+For each transcript, evaluate:
+- Did the agent follow the skill's explicit instructions?
+- Did the agent use the skill's provided tools/scripts?
+- Were there missed opportunities to leverage skill content?
+- Did the agent add unnecessary steps not in the skill?
+
+Score instruction following 1-10 and note specific issues.
+
+### Step 5: Identify Winner Strengths
+
+Determine what made the winner better:
+- Clearer instructions that led to better behavior?
+- Better scripts/tools that produced better output?
+- More comprehensive examples that guided edge cases?
+- Better error handling guidance?
+
+Be specific. Quote from skills/transcripts where relevant.
+
+### Step 6: Identify Loser Weaknesses
+
+Determine what held the loser back:
+- Ambiguous instructions that led to suboptimal choices?
+- Missing tools/scripts that forced workarounds?
+- Gaps in edge case coverage?
+- Poor error handling that caused failures?
+
+### Step 7: Generate Improvement Suggestions
+
+Based on the analysis, produce actionable suggestions for improving the loser skill:
+- Specific instruction changes to make
+- Tools/scripts to add or modify
+- Examples to include
+- Edge cases to address
+
+Prioritize by impact. Focus on changes that would have changed the outcome.
+
+### Step 8: Write Analysis Results
+
+Save structured analysis to `{output_path}`.
+
+## Output Format
+
+Write a JSON file with this structure:
+
+```json
+{
+ "comparison_summary": {
+ "winner": "A",
+ "winner_skill": "path/to/winner/skill",
+ "loser_skill": "path/to/loser/skill",
+ "comparator_reasoning": "Brief summary of why comparator chose winner"
+ },
+ "winner_strengths": [
+ "Clear step-by-step instructions for handling multi-page documents",
+ "Included validation script that caught formatting errors",
+ "Explicit guidance on fallback behavior when OCR fails"
+ ],
+ "loser_weaknesses": [
+ "Vague instruction 'process the document appropriately' led to inconsistent behavior",
+ "No script for validation, agent had to improvise and made errors",
+ "No guidance on OCR failure, agent gave up instead of trying alternatives"
+ ],
+ "instruction_following": {
+ "winner": {
+ "score": 9,
+ "issues": [
+ "Minor: skipped optional logging step"
+ ]
+ },
+ "loser": {
+ "score": 6,
+ "issues": [
+ "Did not use the skill's formatting template",
+ "Invented own approach instead of following step 3",
+ "Missed the 'always validate output' instruction"
+ ]
+ }
+ },
+ "improvement_suggestions": [
+ {
+ "priority": "high",
+ "category": "instructions",
+ "suggestion": "Replace 'process the document appropriately' with explicit steps: 1) Extract text, 2) Identify sections, 3) Format per template",
+ "expected_impact": "Would eliminate ambiguity that caused inconsistent behavior"
+ },
+ {
+ "priority": "high",
+ "category": "tools",
+ "suggestion": "Add validate_output.py script similar to winner skill's validation approach",
+ "expected_impact": "Would catch formatting errors before final output"
+ },
+ {
+ "priority": "medium",
+ "category": "error_handling",
+ "suggestion": "Add fallback instructions: 'If OCR fails, try: 1) different resolution, 2) image preprocessing, 3) manual extraction'",
+ "expected_impact": "Would prevent early failure on difficult documents"
+ }
+ ],
+ "transcript_insights": {
+ "winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script -> Fixed 2 issues -> Produced output",
+ "loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods -> No validation -> Output had errors"
+ }
+}
+```
+
+## Guidelines
+
+- **Be specific**: Quote from skills and transcripts, don't just say "instructions were unclear"
+- **Be actionable**: Suggestions should be concrete changes, not vague advice
+- **Focus on skill improvements**: The goal is to improve the losing skill, not critique the agent
+- **Prioritize by impact**: Which changes would most likely have changed the outcome?
+- **Consider causation**: Did the skill weakness actually cause the worse output, or is it incidental?
+- **Stay objective**: Analyze what happened, don't editorialize
+- **Think about generalization**: Would this improvement help on other evals too?
+
+## Categories for Suggestions
+
+Use these categories to organize improvement suggestions:
+
+| Category | Description |
+|----------|-------------|
+| `instructions` | Changes to the skill's prose instructions |
+| `tools` | Scripts, templates, or utilities to add/modify |
+| `examples` | Example inputs/outputs to include |
+| `error_handling` | Guidance for handling failures |
+| `structure` | Reorganization of skill content |
+| `references` | External docs or resources to add |
+
+## Priority Levels
+
+- **high**: Would likely change the outcome of this comparison
+- **medium**: Would improve quality but may not change win/loss
+- **low**: Nice to have, marginal improvement
+
+---
+
+# Analyzing Benchmark Results
+
+When analyzing benchmark results, the analyzer's purpose is to **surface patterns and anomalies** across multiple runs, not suggest skill improvements.
+
+## Role
+
+Review all benchmark run results and generate freeform notes that help the user understand skill performance. Focus on patterns that wouldn't be visible from aggregate metrics alone.
+
+## Inputs
+
+You receive these parameters in your prompt:
+
+- **benchmark_data_path**: Path to the in-progress benchmark.json with all run results
+- **skill_path**: Path to the skill being benchmarked
+- **output_path**: Where to save the notes (as JSON array of strings)
+
+## Process
+
+### Step 1: Read Benchmark Data
+
+1. Read the benchmark.json containing all run results
+2. Note the configurations tested (with_skill, without_skill)
+3. Understand the run_summary aggregates already calculated
+
+### Step 2: Analyze Per-Assertion Patterns
+
+For each expectation across all runs:
+- Does it **always pass** in both configurations? (may not differentiate skill value)
+- Does it **always fail** in both configurations? (may be broken or beyond capability)
+- Does it **always pass with skill but fail without**? (skill clearly adds value here)
+- Does it **always fail with skill but pass without**? (skill may be hurting)
+- Is it **highly variable**? (flaky expectation or non-deterministic behavior)
+
+### Step 3: Analyze Cross-Eval Patterns
+
+Look for patterns across evals:
+- Are certain eval types consistently harder/easier?
+- Do some evals show high variance while others are stable?
+- Are there surprising results that contradict expectations?
+
+### Step 4: Analyze Metrics Patterns
+
+Look at time_seconds, tokens, tool_calls:
+- Does the skill significantly increase execution time?
+- Is there high variance in resource usage?
+- Are there outlier runs that skew the aggregates?
+
+### Step 5: Generate Notes
+
+Write freeform observations as a list of strings. Each note should:
+- State a specific observation
+- Be grounded in the data (not speculation)
+- Help the user understand something the aggregate metrics don't show
+
+Examples:
+- "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value"
+- "Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure that may be flaky"
+- "Without-skill runs consistently fail on table extraction expectations (0% pass rate)"
+- "Skill adds 13s average execution time but improves pass rate by 50%"
+- "Token usage is 80% higher with skill, primarily due to script output parsing"
+- "All 3 without-skill runs for eval 1 produced empty output"
+
+### Step 6: Write Notes
+
+Save notes to `{output_path}` as a JSON array of strings:
+
+```json
+[
+ "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value",
+ "Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure",
+ "Without-skill runs consistently fail on table extraction expectations",
+ "Skill adds 13s average execution time but improves pass rate by 50%"
+]
+```
+
+## Guidelines
+
+**DO:**
+- Report what you observe in the data
+- Be specific about which evals, expectations, or runs you're referring to
+- Note patterns that aggregate metrics would hide
+- Provide context that helps interpret the numbers
+
+**DO NOT:**
+- Suggest improvements to the skill (that's for the improvement step, not benchmarking)
+- Make subjective quality judgments ("the output was good/bad")
+- Speculate about causes without evidence
+- Repeat information already in the run_summary aggregates
diff --git a/.agents/skills/skill-creator/agents/comparator.md b/.agents/skills/skill-creator/agents/comparator.md
new file mode 100644
index 00000000..80e00eb4
--- /dev/null
+++ b/.agents/skills/skill-creator/agents/comparator.md
@@ -0,0 +1,202 @@
+# Blind Comparator Agent
+
+Compare two outputs WITHOUT knowing which skill produced them.
+
+## Role
+
+The Blind Comparator judges which output better accomplishes the eval task. You receive two outputs labeled A and B, but you do NOT know which skill produced which. This prevents bias toward a particular skill or approach.
+
+Your judgment is based purely on output quality and task completion.
+
+## Inputs
+
+You receive these parameters in your prompt:
+
+- **output_a_path**: Path to the first output file or directory
+- **output_b_path**: Path to the second output file or directory
+- **eval_prompt**: The original task/prompt that was executed
+- **expectations**: List of expectations to check (optional - may be empty)
+
+## Process
+
+### Step 1: Read Both Outputs
+
+1. Examine output A (file or directory)
+2. Examine output B (file or directory)
+3. Note the type, structure, and content of each
+4. If outputs are directories, examine all relevant files inside
+
+### Step 2: Understand the Task
+
+1. Read the eval_prompt carefully
+2. Identify what the task requires:
+ - What should be produced?
+ - What qualities matter (accuracy, completeness, format)?
+ - What would distinguish a good output from a poor one?
+
+### Step 3: Generate Evaluation Rubric
+
+Based on the task, generate a rubric with two dimensions:
+
+**Content Rubric** (what the output contains):
+| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) |
+|-----------|----------|----------------|---------------|
+| Correctness | Major errors | Minor errors | Fully correct |
+| Completeness | Missing key elements | Mostly complete | All elements present |
+| Accuracy | Significant inaccuracies | Minor inaccuracies | Accurate throughout |
+
+**Structure Rubric** (how the output is organized):
+| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) |
+|-----------|----------|----------------|---------------|
+| Organization | Disorganized | Reasonably organized | Clear, logical structure |
+| Formatting | Inconsistent/broken | Mostly consistent | Professional, polished |
+| Usability | Difficult to use | Usable with effort | Easy to use |
+
+Adapt criteria to the specific task. For example:
+- PDF form → "Field alignment", "Text readability", "Data placement"
+- Document → "Section structure", "Heading hierarchy", "Paragraph flow"
+- Data output → "Schema correctness", "Data types", "Completeness"
+
+### Step 4: Evaluate Each Output Against the Rubric
+
+For each output (A and B):
+
+1. **Score each criterion** on the rubric (1-5 scale)
+2. **Calculate dimension totals**: Content score, Structure score
+3. **Calculate overall score**: Average of dimension scores, scaled to 1-10
+
+### Step 5: Check Assertions (if provided)
+
+If expectations are provided:
+
+1. Check each expectation against output A
+2. Check each expectation against output B
+3. Count pass rates for each output
+4. Use expectation scores as secondary evidence (not the primary decision factor)
+
+### Step 6: Determine the Winner
+
+Compare A and B based on (in priority order):
+
+1. **Primary**: Overall rubric score (content + structure)
+2. **Secondary**: Assertion pass rates (if applicable)
+3. **Tiebreaker**: If truly equal, declare a TIE
+
+Be decisive - ties should be rare. One output is usually better, even if marginally.
+
+### Step 7: Write Comparison Results
+
+Save results to a JSON file at the path specified (or `comparison.json` if not specified).
+
+## Output Format
+
+Write a JSON file with this structure:
+
+```json
+{
+ "winner": "A",
+ "reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.",
+ "rubric": {
+ "A": {
+ "content": {
+ "correctness": 5,
+ "completeness": 5,
+ "accuracy": 4
+ },
+ "structure": {
+ "organization": 4,
+ "formatting": 5,
+ "usability": 4
+ },
+ "content_score": 4.7,
+ "structure_score": 4.3,
+ "overall_score": 9.0
+ },
+ "B": {
+ "content": {
+ "correctness": 3,
+ "completeness": 2,
+ "accuracy": 3
+ },
+ "structure": {
+ "organization": 3,
+ "formatting": 2,
+ "usability": 3
+ },
+ "content_score": 2.7,
+ "structure_score": 2.7,
+ "overall_score": 5.4
+ }
+ },
+ "output_quality": {
+ "A": {
+ "score": 9,
+ "strengths": ["Complete solution", "Well-formatted", "All fields present"],
+ "weaknesses": ["Minor style inconsistency in header"]
+ },
+ "B": {
+ "score": 5,
+ "strengths": ["Readable output", "Correct basic structure"],
+ "weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"]
+ }
+ },
+ "expectation_results": {
+ "A": {
+ "passed": 4,
+ "total": 5,
+ "pass_rate": 0.80,
+ "details": [
+ {"text": "Output includes name", "passed": true},
+ {"text": "Output includes date", "passed": true},
+ {"text": "Format is PDF", "passed": true},
+ {"text": "Contains signature", "passed": false},
+ {"text": "Readable text", "passed": true}
+ ]
+ },
+ "B": {
+ "passed": 3,
+ "total": 5,
+ "pass_rate": 0.60,
+ "details": [
+ {"text": "Output includes name", "passed": true},
+ {"text": "Output includes date", "passed": false},
+ {"text": "Format is PDF", "passed": true},
+ {"text": "Contains signature", "passed": false},
+ {"text": "Readable text", "passed": true}
+ ]
+ }
+ }
+}
+```
+
+If no expectations were provided, omit the `expectation_results` field entirely.
+
+## Field Descriptions
+
+- **winner**: "A", "B", or "TIE"
+- **reasoning**: Clear explanation of why the winner was chosen (or why it's a tie)
+- **rubric**: Structured rubric evaluation for each output
+ - **content**: Scores for content criteria (correctness, completeness, accuracy)
+ - **structure**: Scores for structure criteria (organization, formatting, usability)
+ - **content_score**: Average of content criteria (1-5)
+ - **structure_score**: Average of structure criteria (1-5)
+ - **overall_score**: Combined score scaled to 1-10
+- **output_quality**: Summary quality assessment
+ - **score**: 1-10 rating (should match rubric overall_score)
+ - **strengths**: List of positive aspects
+ - **weaknesses**: List of issues or shortcomings
+- **expectation_results**: (Only if expectations provided)
+ - **passed**: Number of expectations that passed
+ - **total**: Total number of expectations
+ - **pass_rate**: Fraction passed (0.0 to 1.0)
+ - **details**: Individual expectation results
+
+## Guidelines
+
+- **Stay blind**: DO NOT try to infer which skill produced which output. Judge purely on output quality.
+- **Be specific**: Cite specific examples when explaining strengths and weaknesses.
+- **Be decisive**: Choose a winner unless outputs are genuinely equivalent.
+- **Output quality first**: Assertion scores are secondary to overall task completion.
+- **Be objective**: Don't favor outputs based on style preferences; focus on correctness and completeness.
+- **Explain your reasoning**: The reasoning field should make it clear why you chose the winner.
+- **Handle edge cases**: If both outputs fail, pick the one that fails less badly. If both are excellent, pick the one that's marginally better.
diff --git a/.agents/skills/skill-creator/agents/grader.md b/.agents/skills/skill-creator/agents/grader.md
new file mode 100644
index 00000000..558ab05c
--- /dev/null
+++ b/.agents/skills/skill-creator/agents/grader.md
@@ -0,0 +1,223 @@
+# Grader Agent
+
+Evaluate expectations against an execution transcript and outputs.
+
+## Role
+
+The Grader reviews a transcript and output files, then determines whether each expectation passes or fails. Provide clear evidence for each judgment.
+
+You have two jobs: grade the outputs, and critique the evals themselves. A passing grade on a weak assertion is worse than useless — it creates false confidence. When you notice an assertion that's trivially satisfied, or an important outcome that no assertion checks, say so.
+
+## Inputs
+
+You receive these parameters in your prompt:
+
+- **expectations**: List of expectations to evaluate (strings)
+- **transcript_path**: Path to the execution transcript (markdown file)
+- **outputs_dir**: Directory containing output files from execution
+
+## Process
+
+### Step 1: Read the Transcript
+
+1. Read the transcript file completely
+2. Note the eval prompt, execution steps, and final result
+3. Identify any issues or errors documented
+
+### Step 2: Examine Output Files
+
+1. List files in outputs_dir
+2. Read/examine each file relevant to the expectations. If outputs aren't plain text, use the inspection tools provided in your prompt — don't rely solely on what the transcript says the executor produced.
+3. Note contents, structure, and quality
+
+### Step 3: Evaluate Each Assertion
+
+For each expectation:
+
+1. **Search for evidence** in the transcript and outputs
+2. **Determine verdict**:
+ - **PASS**: Clear evidence the expectation is true AND the evidence reflects genuine task completion, not just surface-level compliance
+ - **FAIL**: No evidence, or evidence contradicts the expectation, or the evidence is superficial (e.g., correct filename but empty/wrong content)
+3. **Cite the evidence**: Quote the specific text or describe what you found
+
+### Step 4: Extract and Verify Claims
+
+Beyond the predefined expectations, extract implicit claims from the outputs and verify them:
+
+1. **Extract claims** from the transcript and outputs:
+ - Factual statements ("The form has 12 fields")
+ - Process claims ("Used pypdf to fill the form")
+ - Quality claims ("All fields were filled correctly")
+
+2. **Verify each claim**:
+ - **Factual claims**: Can be checked against the outputs or external sources
+ - **Process claims**: Can be verified from the transcript
+ - **Quality claims**: Evaluate whether the claim is justified
+
+3. **Flag unverifiable claims**: Note claims that cannot be verified with available information
+
+This catches issues that predefined expectations might miss.
+
+### Step 5: Read User Notes
+
+If `{outputs_dir}/user_notes.md` exists:
+1. Read it and note any uncertainties or issues flagged by the executor
+2. Include relevant concerns in the grading output
+3. These may reveal problems even when expectations pass
+
+### Step 6: Critique the Evals
+
+After grading, consider whether the evals themselves could be improved. Only surface suggestions when there's a clear gap.
+
+Good suggestions test meaningful outcomes — assertions that are hard to satisfy without actually doing the work correctly. Think about what makes an assertion *discriminating*: it passes when the skill genuinely succeeds and fails when it doesn't.
+
+Suggestions worth raising:
+- An assertion that passed but would also pass for a clearly wrong output (e.g., checking filename existence but not file content)
+- An important outcome you observed — good or bad — that no assertion covers at all
+- An assertion that can't actually be verified from the available outputs
+
+Keep the bar high. The goal is to flag things the eval author would say "good catch" about, not to nitpick every assertion.
+
+### Step 7: Write Grading Results
+
+Save results to `{outputs_dir}/../grading.json` (sibling to outputs_dir).
+
+## Grading Criteria
+
+**PASS when**:
+- The transcript or outputs clearly demonstrate the expectation is true
+- Specific evidence can be cited
+- The evidence reflects genuine substance, not just surface compliance (e.g., a file exists AND contains correct content, not just the right filename)
+
+**FAIL when**:
+- No evidence found for the expectation
+- Evidence contradicts the expectation
+- The expectation cannot be verified from available information
+- The evidence is superficial — the assertion is technically satisfied but the underlying task outcome is wrong or incomplete
+- The output appears to meet the assertion by coincidence rather than by actually doing the work
+
+**When uncertain**: The burden of proof to pass is on the expectation.
+
+### Step 8: Read Executor Metrics and Timing
+
+1. If `{outputs_dir}/metrics.json` exists, read it and include in grading output
+2. If `{outputs_dir}/../timing.json` exists, read it and include timing data
+
+## Output Format
+
+Write a JSON file with this structure:
+
+```json
+{
+ "expectations": [
+ {
+ "text": "The output includes the name 'John Smith'",
+ "passed": true,
+ "evidence": "Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'"
+ },
+ {
+ "text": "The spreadsheet has a SUM formula in cell B10",
+ "passed": false,
+ "evidence": "No spreadsheet was created. The output was a text file."
+ },
+ {
+ "text": "The assistant used the skill's OCR script",
+ "passed": true,
+ "evidence": "Transcript Step 2 shows: 'Tool: Bash - python ocr_script.py image.png'"
+ }
+ ],
+ "summary": {
+ "passed": 2,
+ "failed": 1,
+ "total": 3,
+ "pass_rate": 0.67
+ },
+ "execution_metrics": {
+ "tool_calls": {
+ "Read": 5,
+ "Write": 2,
+ "Bash": 8
+ },
+ "total_tool_calls": 15,
+ "total_steps": 6,
+ "errors_encountered": 0,
+ "output_chars": 12450,
+ "transcript_chars": 3200
+ },
+ "timing": {
+ "executor_duration_seconds": 165.0,
+ "grader_duration_seconds": 26.0,
+ "total_duration_seconds": 191.0
+ },
+ "claims": [
+ {
+ "claim": "The form has 12 fillable fields",
+ "type": "factual",
+ "verified": true,
+ "evidence": "Counted 12 fields in field_info.json"
+ },
+ {
+ "claim": "All required fields were populated",
+ "type": "quality",
+ "verified": false,
+ "evidence": "Reference section was left blank despite data being available"
+ }
+ ],
+ "user_notes_summary": {
+ "uncertainties": ["Used 2023 data, may be stale"],
+ "needs_review": [],
+ "workarounds": ["Fell back to text overlay for non-fillable fields"]
+ },
+ "eval_feedback": {
+ "suggestions": [
+ {
+ "assertion": "The output includes the name 'John Smith'",
+ "reason": "A hallucinated document that mentions the name would also pass — consider checking it appears as the primary contact with matching phone and email from the input"
+ },
+ {
+ "reason": "No assertion checks whether the extracted phone numbers match the input — I observed incorrect numbers in the output that went uncaught"
+ }
+ ],
+ "overall": "Assertions check presence but not correctness. Consider adding content verification."
+ }
+}
+```
+
+## Field Descriptions
+
+- **expectations**: Array of graded expectations
+ - **text**: The original expectation text
+ - **passed**: Boolean - true if expectation passes
+ - **evidence**: Specific quote or description supporting the verdict
+- **summary**: Aggregate statistics
+ - **passed**: Count of passed expectations
+ - **failed**: Count of failed expectations
+ - **total**: Total expectations evaluated
+ - **pass_rate**: Fraction passed (0.0 to 1.0)
+- **execution_metrics**: Copied from executor's metrics.json (if available)
+ - **output_chars**: Total character count of output files (proxy for tokens)
+ - **transcript_chars**: Character count of transcript
+- **timing**: Wall clock timing from timing.json (if available)
+ - **executor_duration_seconds**: Time spent in executor subagent
+ - **total_duration_seconds**: Total elapsed time for the run
+- **claims**: Extracted and verified claims from the output
+ - **claim**: The statement being verified
+ - **type**: "factual", "process", or "quality"
+ - **verified**: Boolean - whether the claim holds
+ - **evidence**: Supporting or contradicting evidence
+- **user_notes_summary**: Issues flagged by the executor
+ - **uncertainties**: Things the executor wasn't sure about
+ - **needs_review**: Items requiring human attention
+ - **workarounds**: Places where the skill didn't work as expected
+- **eval_feedback**: Improvement suggestions for the evals (only when warranted)
+ - **suggestions**: List of concrete suggestions, each with a `reason` and optionally an `assertion` it relates to
+ - **overall**: Brief assessment — can be "No suggestions, evals look solid" if nothing to flag
+
+## Guidelines
+
+- **Be objective**: Base verdicts on evidence, not assumptions
+- **Be specific**: Quote the exact text that supports your verdict
+- **Be thorough**: Check both transcript and output files
+- **Be consistent**: Apply the same standard to each expectation
+- **Explain failures**: Make it clear why evidence was insufficient
+- **No partial credit**: Each expectation is pass or fail, not partial
diff --git a/.agents/skills/skill-creator/assets/eval_review.html b/.agents/skills/skill-creator/assets/eval_review.html
new file mode 100644
index 00000000..938ff32a
--- /dev/null
+++ b/.agents/skills/skill-creator/assets/eval_review.html
@@ -0,0 +1,146 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Eval Set Review - __SKILL_NAME_PLACEHOLDER__</title>
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap" rel="stylesheet">
+ <style>
+ * { box-sizing: border-box; margin: 0; padding: 0; }
+ body { font-family: 'Lora', Georgia, serif; background: #faf9f5; padding: 2rem; color: #141413; }
+ h1 { font-family: 'Poppins', sans-serif; margin-bottom: 0.5rem; font-size: 1.5rem; }
+ .description { color: #b0aea5; margin-bottom: 1.5rem; font-style: italic; max-width: 900px; }
+ .controls { margin-bottom: 1rem; display: flex; gap: 0.5rem; }
+ .btn { font-family: 'Poppins', sans-serif; padding: 0.5rem 1rem; border: none; border-radius: 6px; cursor: pointer; font-size: 0.875rem; font-weight: 500; }
+ .btn-add { background: #6a9bcc; color: white; }
+ .btn-add:hover { background: #5889b8; }
+ .btn-export { background: #d97757; color: white; }
+ .btn-export:hover { background: #c4613f; }
+ table { width: 100%; max-width: 1100px; border-collapse: collapse; background: white; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
+ th { font-family: 'Poppins', sans-serif; background: #141413; color: #faf9f5; padding: 0.75rem 1rem; text-align: left; font-size: 0.875rem; }
+ td { padding: 0.75rem 1rem; border-bottom: 1px solid #e8e6dc; vertical-align: top; }
+ tr:nth-child(even) td { background: #faf9f5; }
+ tr:hover td { background: #f3f1ea; }
+ .section-header td { background: #e8e6dc; font-family: 'Poppins', sans-serif; font-weight: 500; font-size: 0.8rem; color: #141413; text-transform: uppercase; letter-spacing: 0.05em; }
+ .query-input { width: 100%; padding: 0.4rem; border: 1px solid #e8e6dc; border-radius: 4px; font-size: 0.875rem; font-family: 'Lora', Georgia, serif; resize: vertical; min-height: 60px; }
+ .query-input:focus { outline: none; border-color: #d97757; box-shadow: 0 0 0 2px rgba(217,119,87,0.15); }
+ .toggle { position: relative; display: inline-block; width: 44px; height: 24px; }
+ .toggle input { opacity: 0; width: 0; height: 0; }
+ .toggle .slider { position: absolute; inset: 0; background: #b0aea5; border-radius: 24px; cursor: pointer; transition: 0.2s; }
+ .toggle .slider::before { content: ""; position: absolute; width: 18px; height: 18px; left: 3px; bottom: 3px; background: white; border-radius: 50%; transition: 0.2s; }
+ .toggle input:checked + .slider { background: #d97757; }
+ .toggle input:checked + .slider::before { transform: translateX(20px); }
+ .btn-delete { background: #c44; color: white; padding: 0.3rem 0.6rem; border: none; border-radius: 4px; cursor: pointer; font-size: 0.75rem; font-family: 'Poppins', sans-serif; }
+ .btn-delete:hover { background: #a33; }
+ .summary { margin-top: 1rem; color: #b0aea5; font-size: 0.875rem; }
+ </style>
+</head>
+<body>
+ <h1>Eval Set Review: <span id="skill-name">__SKILL_NAME_PLACEHOLDER__</span></h1>
+ <p class="description">Current description: <span id="skill-desc">__SKILL_DESCRIPTION_PLACEHOLDER__</span></p>
+
+ <div class="controls">
+ <button class="btn btn-add" onclick="addRow()">+ Add Query</button>
+ <button class="btn btn-export" onclick="exportEvalSet()">Export Eval Set</button>
+ </div>
+
+ <table>
+ <thead>
+ <tr>
+ <th style="width:65%">Query</th>
+ <th style="width:18%">Should Trigger</th>
+ <th style="width:10%">Actions</th>
+ </tr>
+ </thead>
+ <tbody id="eval-body"></tbody>
+ </table>
+
+ <p class="summary" id="summary"></p>
+
+ <script>
+ const EVAL_DATA = __EVAL_DATA_PLACEHOLDER__;
+
+ let evalItems = [...EVAL_DATA];
+
+ function render() {
+ const tbody = document.getElementById('eval-body');
+ tbody.innerHTML = '';
+
+ // Sort: should-trigger first, then should-not-trigger
+ const sorted = evalItems
+ .map((item, origIdx) => ({ ...item, origIdx }))
+ .sort((a, b) => (b.should_trigger ? 1 : 0) - (a.should_trigger ? 1 : 0));
+
+ let lastGroup = null;
+ sorted.forEach(item => {
+ const group = item.should_trigger ? 'trigger' : 'no-trigger';
+ if (group !== lastGroup) {
+ const headerRow = document.createElement('tr');
+ headerRow.className = 'section-header';
+ headerRow.innerHTML = `<td colspan="3">${item.should_trigger ? 'Should Trigger' : 'Should NOT Trigger'}</td>`;
+ tbody.appendChild(headerRow);
+ lastGroup = group;
+ }
+
+ const idx = item.origIdx;
+ const tr = document.createElement('tr');
+ tr.innerHTML = `
+ <td><textarea class="query-input" onchange="updateQuery(${idx}, this.value)">${escapeHtml(item.query)}</textarea></td>
+ <td>
+ <label class="toggle">
+ <input type="checkbox" ${item.should_trigger ? 'checked' : ''} onchange="updateTrigger(${idx}, this.checked)">
+ <span class="slider"></span>
+ </label>
+ <span style="margin-left:8px;font-size:0.8rem;color:#b0aea5">${item.should_trigger ? 'Yes' : 'No'}</span>
+ </td>
+ <td><button class="btn-delete" onclick="deleteRow(${idx})">Delete</button></td>
+ `;
+ tbody.appendChild(tr);
+ });
+ updateSummary();
+ }
+
+ function escapeHtml(text) {
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+ }
+
+ function updateQuery(idx, value) { evalItems[idx].query = value; updateSummary(); }
+ function updateTrigger(idx, value) { evalItems[idx].should_trigger = value; render(); }
+ function deleteRow(idx) { evalItems.splice(idx, 1); render(); }
+
+ function addRow() {
+ evalItems.push({ query: '', should_trigger: true });
+ render();
+ const inputs = document.querySelectorAll('.query-input');
+ inputs[inputs.length - 1].focus();
+ }
+
+ function updateSummary() {
+ const trigger = evalItems.filter(i => i.should_trigger).length;
+ const noTrigger = evalItems.filter(i => !i.should_trigger).length;
+ document.getElementById('summary').textContent =
+ `${evalItems.length} queries total: ${trigger} should trigger, ${noTrigger} should not trigger`;
+ }
+
+ function exportEvalSet() {
+ const valid = evalItems.filter(i => i.query.trim() !== '');
+ const data = valid.map(i => ({ query: i.query.trim(), should_trigger: i.should_trigger }));
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = 'eval_set.json';
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ }
+
+ render();
+ </script>
+</body>
+</html>
diff --git a/.agents/skills/skill-creator/eval-viewer/generate_review.py b/.agents/skills/skill-creator/eval-viewer/generate_review.py
new file mode 100644
index 00000000..7fa59786
--- /dev/null
+++ b/.agents/skills/skill-creator/eval-viewer/generate_review.py
@@ -0,0 +1,471 @@
+#!/usr/bin/env python3
+"""Generate and serve a review page for eval results.
+
+Reads the workspace directory, discovers runs (directories with outputs/),
+embeds all output data into a self-contained HTML page, and serves it via
+a tiny HTTP server. Feedback auto-saves to feedback.json in the workspace.
+
+Usage:
+ python generate_review.py <workspace-path> [--port PORT] [--skill-name NAME]
+ python generate_review.py <workspace-path> --previous-feedback /path/to/old/feedback.json
+
+No dependencies beyond the Python stdlib are required.
+"""
+
+import argparse
+import base64
+import json
+import mimetypes
+import os
+import re
+import signal
+import subprocess
+import sys
+import time
+import webbrowser
+from functools import partial
+from http.server import HTTPServer, BaseHTTPRequestHandler
+from pathlib import Path
+
+# Files to exclude from output listings
+METADATA_FILES = {"transcript.md", "user_notes.md", "metrics.json"}
+
+# Extensions we render as inline text
+TEXT_EXTENSIONS = {
+ ".txt", ".md", ".json", ".csv", ".py", ".js", ".ts", ".tsx", ".jsx",
+ ".yaml", ".yml", ".xml", ".html", ".css", ".sh", ".rb", ".go", ".rs",
+ ".java", ".c", ".cpp", ".h", ".hpp", ".sql", ".r", ".toml",
+}
+
+# Extensions we render as inline images
+IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"}
+
+# MIME type overrides for common types
+MIME_OVERRIDES = {
+ ".svg": "image/svg+xml",
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+}
+
+
+def get_mime_type(path: Path) -> str:
+ ext = path.suffix.lower()
+ if ext in MIME_OVERRIDES:
+ return MIME_OVERRIDES[ext]
+ mime, _ = mimetypes.guess_type(str(path))
+ return mime or "application/octet-stream"
+
+
+def find_runs(workspace: Path) -> list[dict]:
+ """Recursively find directories that contain an outputs/ subdirectory."""
+ runs: list[dict] = []
+ _find_runs_recursive(workspace, workspace, runs)
+ runs.sort(key=lambda r: (r.get("eval_id", float("inf")), r["id"]))
+ return runs
+
+
+def _find_runs_recursive(root: Path, current: Path, runs: list[dict]) -> None:
+ if not current.is_dir():
+ return
+
+ outputs_dir = current / "outputs"
+ if outputs_dir.is_dir():
+ run = build_run(root, current)
+ if run:
+ runs.append(run)
+ return
+
+ skip = {"node_modules", ".git", "__pycache__", "skill", "inputs"}
+ for child in sorted(current.iterdir()):
+ if child.is_dir() and child.name not in skip:
+ _find_runs_recursive(root, child, runs)
+
+
+def build_run(root: Path, run_dir: Path) -> dict | None:
+ """Build a run dict with prompt, outputs, and grading data."""
+ prompt = ""
+ eval_id = None
+
+ # Try eval_metadata.json
+ for candidate in [run_dir / "eval_metadata.json", run_dir.parent / "eval_metadata.json"]:
+ if candidate.exists():
+ try:
+ metadata = json.loads(candidate.read_text())
+ prompt = metadata.get("prompt", "")
+ eval_id = metadata.get("eval_id")
+ except (json.JSONDecodeError, OSError):
+ pass
+ if prompt:
+ break
+
+ # Fall back to transcript.md
+ if not prompt:
+ for candidate in [run_dir / "transcript.md", run_dir / "outputs" / "transcript.md"]:
+ if candidate.exists():
+ try:
+ text = candidate.read_text()
+ match = re.search(r"## Eval Prompt\n\n([\s\S]*?)(?=\n##|$)", text)
+ if match:
+ prompt = match.group(1).strip()
+ except OSError:
+ pass
+ if prompt:
+ break
+
+ if not prompt:
+ prompt = "(No prompt found)"
+
+ run_id = str(run_dir.relative_to(root)).replace("/", "-").replace("\\", "-")
+
+ # Collect output files
+ outputs_dir = run_dir / "outputs"
+ output_files: list[dict] = []
+ if outputs_dir.is_dir():
+ for f in sorted(outputs_dir.iterdir()):
+ if f.is_file() and f.name not in METADATA_FILES:
+ output_files.append(embed_file(f))
+
+ # Load grading if present
+ grading = None
+ for candidate in [run_dir / "grading.json", run_dir.parent / "grading.json"]:
+ if candidate.exists():
+ try:
+ grading = json.loads(candidate.read_text())
+ except (json.JSONDecodeError, OSError):
+ pass
+ if grading:
+ break
+
+ return {
+ "id": run_id,
+ "prompt": prompt,
+ "eval_id": eval_id,
+ "outputs": output_files,
+ "grading": grading,
+ }
+
+
+def embed_file(path: Path) -> dict:
+ """Read a file and return an embedded representation."""
+ ext = path.suffix.lower()
+ mime = get_mime_type(path)
+
+ if ext in TEXT_EXTENSIONS:
+ try:
+ content = path.read_text(errors="replace")
+ except OSError:
+ content = "(Error reading file)"
+ return {
+ "name": path.name,
+ "type": "text",
+ "content": content,
+ }
+ elif ext in IMAGE_EXTENSIONS:
+ try:
+ raw = path.read_bytes()
+ b64 = base64.b64encode(raw).decode("ascii")
+ except OSError:
+ return {"name": path.name, "type": "error", "content": "(Error reading file)"}
+ return {
+ "name": path.name,
+ "type": "image",
+ "mime": mime,
+ "data_uri": f"data:{mime};base64,{b64}",
+ }
+ elif ext == ".pdf":
+ try:
+ raw = path.read_bytes()
+ b64 = base64.b64encode(raw).decode("ascii")
+ except OSError:
+ return {"name": path.name, "type": "error", "content": "(Error reading file)"}
+ return {
+ "name": path.name,
+ "type": "pdf",
+ "data_uri": f"data:{mime};base64,{b64}",
+ }
+ elif ext == ".xlsx":
+ try:
+ raw = path.read_bytes()
+ b64 = base64.b64encode(raw).decode("ascii")
+ except OSError:
+ return {"name": path.name, "type": "error", "content": "(Error reading file)"}
+ return {
+ "name": path.name,
+ "type": "xlsx",
+ "data_b64": b64,
+ }
+ else:
+ # Binary / unknown — base64 download link
+ try:
+ raw = path.read_bytes()
+ b64 = base64.b64encode(raw).decode("ascii")
+ except OSError:
+ return {"name": path.name, "type": "error", "content": "(Error reading file)"}
+ return {
+ "name": path.name,
+ "type": "binary",
+ "mime": mime,
+ "data_uri": f"data:{mime};base64,{b64}",
+ }
+
+
+def load_previous_iteration(workspace: Path) -> dict[str, dict]:
+ """Load previous iteration's feedback and outputs.
+
+ Returns a map of run_id -> {"feedback": str, "outputs": list[dict]}.
+ """
+ result: dict[str, dict] = {}
+
+ # Load feedback
+ feedback_map: dict[str, str] = {}
+ feedback_path = workspace / "feedback.json"
+ if feedback_path.exists():
+ try:
+ data = json.loads(feedback_path.read_text())
+ feedback_map = {
+ r["run_id"]: r["feedback"]
+ for r in data.get("reviews", [])
+ if r.get("feedback", "").strip()
+ }
+ except (json.JSONDecodeError, OSError, KeyError):
+ pass
+
+ # Load runs (to get outputs)
+ prev_runs = find_runs(workspace)
+ for run in prev_runs:
+ result[run["id"]] = {
+ "feedback": feedback_map.get(run["id"], ""),
+ "outputs": run.get("outputs", []),
+ }
+
+ # Also add feedback for run_ids that had feedback but no matching run
+ for run_id, fb in feedback_map.items():
+ if run_id not in result:
+ result[run_id] = {"feedback": fb, "outputs": []}
+
+ return result
+
+
+def generate_html(
+ runs: list[dict],
+ skill_name: str,
+ previous: dict[str, dict] | None = None,
+ benchmark: dict | None = None,
+) -> str:
+ """Generate the complete standalone HTML page with embedded data."""
+ template_path = Path(__file__).parent / "viewer.html"
+ template = template_path.read_text()
+
+ # Build previous_feedback and previous_outputs maps for the template
+ previous_feedback: dict[str, str] = {}
+ previous_outputs: dict[str, list[dict]] = {}
+ if previous:
+ for run_id, data in previous.items():
+ if data.get("feedback"):
+ previous_feedback[run_id] = data["feedback"]
+ if data.get("outputs"):
+ previous_outputs[run_id] = data["outputs"]
+
+ embedded = {
+ "skill_name": skill_name,
+ "runs": runs,
+ "previous_feedback": previous_feedback,
+ "previous_outputs": previous_outputs,
+ }
+ if benchmark:
+ embedded["benchmark"] = benchmark
+
+ data_json = json.dumps(embedded)
+
+ return template.replace("/*__EMBEDDED_DATA__*/", f"const EMBEDDED_DATA = {data_json};")
+
+
+# ---------------------------------------------------------------------------
+# HTTP server (stdlib only, zero dependencies)
+# ---------------------------------------------------------------------------
+
+def _kill_port(port: int) -> None:
+ """Kill any process listening on the given port."""
+ try:
+ result = subprocess.run(
+ ["lsof", "-ti", f":{port}"],
+ capture_output=True, text=True, timeout=5,
+ )
+ for pid_str in result.stdout.strip().split("\n"):
+ if pid_str.strip():
+ try:
+ os.kill(int(pid_str.strip()), signal.SIGTERM)
+ except (ProcessLookupError, ValueError):
+ pass
+ if result.stdout.strip():
+ time.sleep(0.5)
+ except subprocess.TimeoutExpired:
+ pass
+ except FileNotFoundError:
+ print("Note: lsof not found, cannot check if port is in use", file=sys.stderr)
+
+class ReviewHandler(BaseHTTPRequestHandler):
+ """Serves the review HTML and handles feedback saves.
+
+ Regenerates the HTML on each page load so that refreshing the browser
+ picks up new eval outputs without restarting the server.
+ """
+
+ def __init__(
+ self,
+ workspace: Path,
+ skill_name: str,
+ feedback_path: Path,
+ previous: dict[str, dict],
+ benchmark_path: Path | None,
+ *args,
+ **kwargs,
+ ):
+ self.workspace = workspace
+ self.skill_name = skill_name
+ self.feedback_path = feedback_path
+ self.previous = previous
+ self.benchmark_path = benchmark_path
+ super().__init__(*args, **kwargs)
+
+ def do_GET(self) -> None:
+ if self.path == "/" or self.path == "/index.html":
+ # Regenerate HTML on each request (re-scans workspace for new outputs)
+ runs = find_runs(self.workspace)
+ benchmark = None
+ if self.benchmark_path and self.benchmark_path.exists():
+ try:
+ benchmark = json.loads(self.benchmark_path.read_text())
+ except (json.JSONDecodeError, OSError):
+ pass
+ html = generate_html(runs, self.skill_name, self.previous, benchmark)
+ content = html.encode("utf-8")
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.send_header("Content-Length", str(len(content)))
+ self.end_headers()
+ self.wfile.write(content)
+ elif self.path == "/api/feedback":
+ data = b"{}"
+ if self.feedback_path.exists():
+ data = self.feedback_path.read_bytes()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ else:
+ self.send_error(404)
+
+ def do_POST(self) -> None:
+ if self.path == "/api/feedback":
+ length = int(self.headers.get("Content-Length", 0))
+ body = self.rfile.read(length)
+ try:
+ data = json.loads(body)
+ if not isinstance(data, dict) or "reviews" not in data:
+ raise ValueError("Expected JSON object with 'reviews' key")
+ self.feedback_path.write_text(json.dumps(data, indent=2) + "\n")
+ resp = b'{"ok":true}'
+ self.send_response(200)
+ except (json.JSONDecodeError, OSError, ValueError) as e:
+ resp = json.dumps({"error": str(e)}).encode()
+ self.send_response(500)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(resp)))
+ self.end_headers()
+ self.wfile.write(resp)
+ else:
+ self.send_error(404)
+
+ def log_message(self, format: str, *args: object) -> None:
+ # Suppress request logging to keep terminal clean
+ pass
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Generate and serve eval review")
+ parser.add_argument("workspace", type=Path, help="Path to workspace directory")
+ parser.add_argument("--port", "-p", type=int, default=3117, help="Server port (default: 3117)")
+ parser.add_argument("--skill-name", "-n", type=str, default=None, help="Skill name for header")
+ parser.add_argument(
+ "--previous-workspace", type=Path, default=None,
+ help="Path to previous iteration's workspace (shows old outputs and feedback as context)",
+ )
+ parser.add_argument(
+ "--benchmark", type=Path, default=None,
+ help="Path to benchmark.json to show in the Benchmark tab",
+ )
+ parser.add_argument(
+ "--static", "-s", type=Path, default=None,
+ help="Write standalone HTML to this path instead of starting a server",
+ )
+ args = parser.parse_args()
+
+ workspace = args.workspace.resolve()
+ if not workspace.is_dir():
+ print(f"Error: {workspace} is not a directory", file=sys.stderr)
+ sys.exit(1)
+
+ runs = find_runs(workspace)
+ if not runs:
+ print(f"No runs found in {workspace}", file=sys.stderr)
+ sys.exit(1)
+
+ skill_name = args.skill_name or workspace.name.replace("-workspace", "")
+ feedback_path = workspace / "feedback.json"
+
+ previous: dict[str, dict] = {}
+ if args.previous_workspace:
+ previous = load_previous_iteration(args.previous_workspace.resolve())
+
+ benchmark_path = args.benchmark.resolve() if args.benchmark else None
+ benchmark = None
+ if benchmark_path and benchmark_path.exists():
+ try:
+ benchmark = json.loads(benchmark_path.read_text())
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ if args.static:
+ html = generate_html(runs, skill_name, previous, benchmark)
+ args.static.parent.mkdir(parents=True, exist_ok=True)
+ args.static.write_text(html)
+ print(f"\n Static viewer written to: {args.static}\n")
+ sys.exit(0)
+
+ # Kill any existing process on the target port
+ port = args.port
+ _kill_port(port)
+ handler = partial(ReviewHandler, workspace, skill_name, feedback_path, previous, benchmark_path)
+ try:
+ server = HTTPServer(("127.0.0.1", port), handler)
+ except OSError:
+ # Port still in use after kill attempt — find a free one
+ server = HTTPServer(("127.0.0.1", 0), handler)
+ port = server.server_address[1]
+
+ url = f"http://localhost:{port}"
+ print(f"\n Eval Viewer")
+ print(f" ─────────────────────────────────")
+ print(f" URL: {url}")
+ print(f" Workspace: {workspace}")
+ print(f" Feedback: {feedback_path}")
+ if previous:
+ print(f" Previous: {args.previous_workspace} ({len(previous)} runs)")
+ if benchmark_path:
+ print(f" Benchmark: {benchmark_path}")
+ print(f"\n Press Ctrl+C to stop.\n")
+
+ webbrowser.open(url)
+
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ print("\nStopped.")
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/skill-creator/eval-viewer/viewer.html b/.agents/skills/skill-creator/eval-viewer/viewer.html
new file mode 100644
index 00000000..6d8e9634
--- /dev/null
+++ b/.agents/skills/skill-creator/eval-viewer/viewer.html
@@ -0,0 +1,1325 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Eval Review</title>
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap" rel="stylesheet">
+ <script src="https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js" integrity="sha384-EnyY0/GSHQGSxSgMwaIPzSESbqoOLSexfnSMN2AP+39Ckmn92stwABZynq1JyzdT" crossorigin="anonymous"></script>
+ <style>
+ :root {
+ --bg: #faf9f5;
+ --surface: #ffffff;
+ --border: #e8e6dc;
+ --text: #141413;
+ --text-muted: #b0aea5;
+ --accent: #d97757;
+ --accent-hover: #c4613f;
+ --green: #788c5d;
+ --green-bg: #eef2e8;
+ --red: #c44;
+ --red-bg: #fceaea;
+ --header-bg: #141413;
+ --header-text: #faf9f5;
+ --radius: 6px;
+ }
+
+ * { box-sizing: border-box; margin: 0; padding: 0; }
+
+ body {
+ font-family: 'Lora', Georgia, serif;
+ background: var(--bg);
+ color: var(--text);
+ height: 100vh;
+ display: flex;
+ flex-direction: column;
+ }
+
+ /* ---- Header ---- */
+ .header {
+ background: var(--header-bg);
+ color: var(--header-text);
+ padding: 1rem 2rem;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ flex-shrink: 0;
+ }
+ .header h1 {
+ font-family: 'Poppins', sans-serif;
+ font-size: 1.25rem;
+ font-weight: 600;
+ }
+ .header .instructions {
+ font-size: 0.8rem;
+ opacity: 0.7;
+ margin-top: 0.25rem;
+ }
+ .header .progress {
+ font-size: 0.875rem;
+ opacity: 0.8;
+ text-align: right;
+ }
+
+ /* ---- Main content ---- */
+ .main {
+ flex: 1;
+ overflow-y: auto;
+ padding: 1.5rem 2rem;
+ display: flex;
+ flex-direction: column;
+ gap: 1.25rem;
+ }
+
+ /* ---- Sections ---- */
+ .section {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ flex-shrink: 0;
+ }
+ .section-header {
+ font-family: 'Poppins', sans-serif;
+ padding: 0.75rem 1rem;
+ font-size: 0.75rem;
+ font-weight: 500;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--text-muted);
+ border-bottom: 1px solid var(--border);
+ background: var(--bg);
+ }
+ .section-body {
+ padding: 1rem;
+ }
+
+ /* ---- Config badge ---- */
+ .config-badge {
+ display: inline-block;
+ padding: 0.2rem 0.625rem;
+ border-radius: 9999px;
+ font-family: 'Poppins', sans-serif;
+ font-size: 0.6875rem;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+ margin-left: 0.75rem;
+ vertical-align: middle;
+ }
+ .config-badge.config-primary {
+ background: rgba(33, 150, 243, 0.12);
+ color: #1976d2;
+ }
+ .config-badge.config-baseline {
+ background: rgba(255, 193, 7, 0.15);
+ color: #f57f17;
+ }
+
+ /* ---- Prompt ---- */
+ .prompt-text {
+ white-space: pre-wrap;
+ font-size: 0.9375rem;
+ line-height: 1.6;
+ }
+
+ /* ---- Outputs ---- */
+ .output-file {
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ overflow: hidden;
+ }
+ .output-file + .output-file {
+ margin-top: 1rem;
+ }
+ .output-file-header {
+ padding: 0.5rem 0.75rem;
+ font-size: 0.8rem;
+ font-weight: 600;
+ color: var(--text-muted);
+ background: var(--bg);
+ border-bottom: 1px solid var(--border);
+ font-family: 'SF Mono', SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ }
+ .output-file-header .dl-btn {
+ font-size: 0.7rem;
+ color: var(--accent);
+ text-decoration: none;
+ cursor: pointer;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ font-weight: 500;
+ opacity: 0.8;
+ }
+ .output-file-header .dl-btn:hover {
+ opacity: 1;
+ text-decoration: underline;
+ }
+ .output-file-content {
+ padding: 0.75rem;
+ overflow-x: auto;
+ }
+ .output-file-content pre {
+ font-size: 0.8125rem;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-word;
+ font-family: 'SF Mono', SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
+ }
+ .output-file-content img {
+ max-width: 100%;
+ height: auto;
+ border-radius: 4px;
+ }
+ .output-file-content iframe {
+ width: 100%;
+ height: 600px;
+ border: none;
+ }
+ .output-file-content table {
+ border-collapse: collapse;
+ font-size: 0.8125rem;
+ width: 100%;
+ }
+ .output-file-content table td,
+ .output-file-content table th {
+ border: 1px solid var(--border);
+ padding: 0.375rem 0.5rem;
+ text-align: left;
+ }
+ .output-file-content table th {
+ background: var(--bg);
+ font-weight: 600;
+ }
+ .output-file-content .download-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.5rem 1rem;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ color: var(--accent);
+ text-decoration: none;
+ font-size: 0.875rem;
+ cursor: pointer;
+ }
+ .output-file-content .download-link:hover {
+ background: var(--border);
+ }
+ .empty-state {
+ color: var(--text-muted);
+ font-style: italic;
+ padding: 2rem;
+ text-align: center;
+ }
+
+ /* ---- Feedback ---- */
+ .prev-feedback {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 0.625rem 0.75rem;
+ margin-top: 0.75rem;
+ font-size: 0.8125rem;
+ color: var(--text-muted);
+ line-height: 1.5;
+ }
+ .prev-feedback-label {
+ font-size: 0.7rem;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ margin-bottom: 0.25rem;
+ color: var(--text-muted);
+ }
+ .feedback-textarea {
+ width: 100%;
+ min-height: 100px;
+ padding: 0.75rem;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ font-family: inherit;
+ font-size: 0.9375rem;
+ line-height: 1.5;
+ resize: vertical;
+ color: var(--text);
+ }
+ .feedback-textarea:focus {
+ outline: none;
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
+ }
+ .feedback-status {
+ font-size: 0.75rem;
+ color: var(--text-muted);
+ margin-top: 0.5rem;
+ min-height: 1.1em;
+ }
+
+ /* ---- Grades (collapsible) ---- */
+ .grades-toggle {
+ display: flex;
+ align-items: center;
+ cursor: pointer;
+ user-select: none;
+ }
+ .grades-toggle:hover {
+ color: var(--accent);
+ }
+ .grades-toggle .arrow {
+ margin-right: 0.5rem;
+ transition: transform 0.15s;
+ font-size: 0.75rem;
+ }
+ .grades-toggle .arrow.open {
+ transform: rotate(90deg);
+ }
+ .grades-content {
+ display: none;
+ margin-top: 0.75rem;
+ }
+ .grades-content.open {
+ display: block;
+ }
+ .grades-summary {
+ font-size: 0.875rem;
+ margin-bottom: 0.75rem;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ }
+ .grade-badge {
+ display: inline-block;
+ padding: 0.125rem 0.5rem;
+ border-radius: 9999px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ }
+ .grade-pass { background: var(--green-bg); color: var(--green); }
+ .grade-fail { background: var(--red-bg); color: var(--red); }
+ .assertion-list {
+ list-style: none;
+ }
+ .assertion-item {
+ padding: 0.625rem 0;
+ border-bottom: 1px solid var(--border);
+ font-size: 0.8125rem;
+ }
+ .assertion-item:last-child { border-bottom: none; }
+ .assertion-status {
+ font-weight: 600;
+ margin-right: 0.5rem;
+ }
+ .assertion-status.pass { color: var(--green); }
+ .assertion-status.fail { color: var(--red); }
+ .assertion-evidence {
+ color: var(--text-muted);
+ font-size: 0.75rem;
+ margin-top: 0.25rem;
+ padding-left: 1.5rem;
+ }
+
+ /* ---- View tabs ---- */
+ .view-tabs {
+ display: flex;
+ gap: 0;
+ padding: 0 2rem;
+ background: var(--bg);
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ }
+ .view-tab {
+ font-family: 'Poppins', sans-serif;
+ padding: 0.625rem 1.25rem;
+ font-size: 0.8125rem;
+ font-weight: 500;
+ cursor: pointer;
+ border: none;
+ background: none;
+ color: var(--text-muted);
+ border-bottom: 2px solid transparent;
+ transition: all 0.15s;
+ }
+ .view-tab:hover { color: var(--text); }
+ .view-tab.active {
+ color: var(--accent);
+ border-bottom-color: var(--accent);
+ }
+ .view-panel { display: none; }
+ .view-panel.active { display: flex; flex-direction: column; flex: 1; overflow: hidden; }
+
+ /* ---- Benchmark view ---- */
+ .benchmark-view {
+ padding: 1.5rem 2rem;
+ overflow-y: auto;
+ flex: 1;
+ }
+ .benchmark-table {
+ border-collapse: collapse;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ font-size: 0.8125rem;
+ width: 100%;
+ margin-bottom: 1.5rem;
+ }
+ .benchmark-table th, .benchmark-table td {
+ padding: 0.625rem 0.75rem;
+ text-align: left;
+ border: 1px solid var(--border);
+ }
+ .benchmark-table th {
+ font-family: 'Poppins', sans-serif;
+ background: var(--header-bg);
+ color: var(--header-text);
+ font-weight: 500;
+ font-size: 0.75rem;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ }
+ .benchmark-table tr:hover { background: var(--bg); }
+ .benchmark-table tr.benchmark-row-with { background: rgba(33, 150, 243, 0.06); }
+ .benchmark-table tr.benchmark-row-without { background: rgba(255, 193, 7, 0.06); }
+ .benchmark-table tr.benchmark-row-with:hover { background: rgba(33, 150, 243, 0.12); }
+ .benchmark-table tr.benchmark-row-without:hover { background: rgba(255, 193, 7, 0.12); }
+ .benchmark-table tr.benchmark-row-avg { font-weight: 600; border-top: 2px solid var(--border); }
+ .benchmark-table tr.benchmark-row-avg.benchmark-row-with { background: rgba(33, 150, 243, 0.12); }
+ .benchmark-table tr.benchmark-row-avg.benchmark-row-without { background: rgba(255, 193, 7, 0.12); }
+ .benchmark-delta-positive { color: var(--green); font-weight: 600; }
+ .benchmark-delta-negative { color: var(--red); font-weight: 600; }
+ .benchmark-notes {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ padding: 1rem;
+ }
+ .benchmark-notes h3 {
+ font-family: 'Poppins', sans-serif;
+ font-size: 0.875rem;
+ margin-bottom: 0.75rem;
+ }
+ .benchmark-notes ul {
+ list-style: disc;
+ padding-left: 1.25rem;
+ }
+ .benchmark-notes li {
+ font-size: 0.8125rem;
+ line-height: 1.6;
+ margin-bottom: 0.375rem;
+ }
+ .benchmark-empty {
+ color: var(--text-muted);
+ font-style: italic;
+ text-align: center;
+ padding: 3rem;
+ }
+
+ /* ---- Navigation ---- */
+ .nav {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 1rem 2rem;
+ border-top: 1px solid var(--border);
+ background: var(--surface);
+ flex-shrink: 0;
+ }
+ .nav-btn {
+ font-family: 'Poppins', sans-serif;
+ padding: 0.5rem 1.25rem;
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ background: var(--surface);
+ cursor: pointer;
+ font-size: 0.875rem;
+ font-weight: 500;
+ color: var(--text);
+ transition: all 0.15s;
+ }
+ .nav-btn:hover:not(:disabled) {
+ background: var(--bg);
+ border-color: var(--text-muted);
+ }
+ .nav-btn:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ .done-btn {
+ font-family: 'Poppins', sans-serif;
+ padding: 0.5rem 1.5rem;
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ background: var(--surface);
+ color: var(--text);
+ cursor: pointer;
+ font-size: 0.875rem;
+ font-weight: 500;
+ transition: all 0.15s;
+ }
+ .done-btn:hover {
+ background: var(--bg);
+ border-color: var(--text-muted);
+ }
+ .done-btn.ready {
+ border: none;
+ background: var(--accent);
+ color: white;
+ font-weight: 600;
+ }
+ .done-btn.ready:hover {
+ background: var(--accent-hover);
+ }
+ /* ---- Done overlay ---- */
+ .done-overlay {
+ display: none;
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.5);
+ z-index: 100;
+ justify-content: center;
+ align-items: center;
+ }
+ .done-overlay.visible {
+ display: flex;
+ }
+ .done-card {
+ background: var(--surface);
+ border-radius: 12px;
+ padding: 2rem 3rem;
+ text-align: center;
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
+ max-width: 500px;
+ }
+ .done-card h2 {
+ font-size: 1.5rem;
+ margin-bottom: 0.5rem;
+ }
+ .done-card p {
+ color: var(--text-muted);
+ margin-bottom: 1.5rem;
+ line-height: 1.5;
+ }
+ .done-card .btn-row {
+ display: flex;
+ gap: 0.5rem;
+ justify-content: center;
+ }
+ .done-card button {
+ padding: 0.5rem 1.25rem;
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ background: var(--surface);
+ cursor: pointer;
+ font-size: 0.875rem;
+ }
+ .done-card button:hover {
+ background: var(--bg);
+ }
+ /* ---- Toast ---- */
+ .toast {
+ position: fixed;
+ bottom: 5rem;
+ left: 50%;
+ transform: translateX(-50%);
+ background: var(--header-bg);
+ color: var(--header-text);
+ padding: 0.625rem 1.25rem;
+ border-radius: var(--radius);
+ font-size: 0.875rem;
+ opacity: 0;
+ transition: opacity 0.3s;
+ pointer-events: none;
+ z-index: 200;
+ }
+ .toast.visible {
+ opacity: 1;
+ }
+ </style>
+</head>
+<body>
+ <div id="app" style="height:100vh; display:flex; flex-direction:column;">
+ <div class="header">
+ <div>
+ <h1>Eval Review: <span id="skill-name"></span></h1>
+ <div class="instructions">Review each output and leave feedback below. Navigate with arrow keys or buttons. When done, copy feedback and paste into Claude Code.</div>
+ </div>
+ <div class="progress" id="progress"></div>
+ </div>
+
+ <!-- View tabs (only shown when benchmark data exists) -->
+ <div class="view-tabs" id="view-tabs" style="display:none;">
+ <button class="view-tab active" onclick="switchView('outputs')">Outputs</button>
+ <button class="view-tab" onclick="switchView('benchmark')">Benchmark</button>
+ </div>
+
+ <!-- Outputs panel (qualitative review) -->
+ <div class="view-panel active" id="panel-outputs">
+ <div class="main">
+ <!-- Prompt -->
+ <div class="section">
+ <div class="section-header">Prompt <span class="config-badge" id="config-badge" style="display:none;"></span></div>
+ <div class="section-body">
+ <div class="prompt-text" id="prompt-text"></div>
+ </div>
+ </div>
+
+ <!-- Outputs -->
+ <div class="section">
+ <div class="section-header">Output</div>
+ <div class="section-body" id="outputs-body">
+ <div class="empty-state">No output files found</div>
+ </div>
+ </div>
+
+ <!-- Previous Output (collapsible) -->
+ <div class="section" id="prev-outputs-section" style="display:none;">
+ <div class="section-header">
+ <div class="grades-toggle" onclick="togglePrevOutputs()">
+ <span class="arrow" id="prev-outputs-arrow">&#9654;</span>
+ Previous Output
+ </div>
+ </div>
+ <div class="grades-content" id="prev-outputs-content"></div>
+ </div>
+
+ <!-- Grades (collapsible) -->
+ <div class="section" id="grades-section" style="display:none;">
+ <div class="section-header">
+ <div class="grades-toggle" onclick="toggleGrades()">
+ <span class="arrow" id="grades-arrow">&#9654;</span>
+ Formal Grades
+ </div>
+ </div>
+ <div class="grades-content" id="grades-content"></div>
+ </div>
+
+ <!-- Feedback -->
+ <div class="section">
+ <div class="section-header">Your Feedback</div>
+ <div class="section-body">
+ <textarea
+ class="feedback-textarea"
+ id="feedback"
+ placeholder="What do you think of this output? Any issues, suggestions, or things that look great?"
+ ></textarea>
+ <div class="feedback-status" id="feedback-status"></div>
+ <div class="prev-feedback" id="prev-feedback" style="display:none;">
+ <div class="prev-feedback-label">Previous feedback</div>
+ <div id="prev-feedback-text"></div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="nav" id="outputs-nav">
+ <button class="nav-btn" id="prev-btn" onclick="navigate(-1)">&#8592; Previous</button>
+ <button class="done-btn" id="done-btn" onclick="showDoneDialog()">Submit All Reviews</button>
+ <button class="nav-btn" id="next-btn" onclick="navigate(1)">Next &#8594;</button>
+ </div>
+ </div><!-- end panel-outputs -->
+
+ <!-- Benchmark panel (quantitative stats) -->
+ <div class="view-panel" id="panel-benchmark">
+ <div class="benchmark-view" id="benchmark-content">
+ <div class="benchmark-empty">No benchmark data available. Run a benchmark to see quantitative results here.</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Done overlay -->
+ <div class="done-overlay" id="done-overlay">
+ <div class="done-card">
+ <h2>Review Complete</h2>
+ <p>Your feedback has been saved. Go back to your Claude Code session and tell Claude you're done reviewing.</p>
+ <div class="btn-row">
+ <button onclick="closeDoneDialog()">OK</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Toast -->
+ <div class="toast" id="toast"></div>
+
+ <script>
+ // ---- Embedded data (injected by generate_review.py) ----
+ /*__EMBEDDED_DATA__*/
+
+ // ---- State ----
+ let feedbackMap = {}; // run_id -> feedback text
+ let currentIndex = 0;
+ let visitedRuns = new Set();
+
+ // ---- Init ----
+ async function init() {
+ // Load saved feedback from server — but only if this isn't a fresh
+ // iteration (indicated by previous_feedback being present). When
+ // previous feedback exists, the feedback.json on disk is stale from
+ // the prior iteration and should not pre-fill the textareas.
+ const hasPrevious = Object.keys(EMBEDDED_DATA.previous_feedback || {}).length > 0
+ || Object.keys(EMBEDDED_DATA.previous_outputs || {}).length > 0;
+ if (!hasPrevious) {
+ try {
+ const resp = await fetch("/api/feedback");
+ const data = await resp.json();
+ if (data.reviews) {
+ for (const r of data.reviews) feedbackMap[r.run_id] = r.feedback;
+ }
+ } catch { /* first run, no feedback yet */ }
+ }
+
+ document.getElementById("skill-name").textContent = EMBEDDED_DATA.skill_name;
+ showRun(0);
+
+ // Wire up feedback auto-save
+ const textarea = document.getElementById("feedback");
+ let saveTimeout = null;
+ textarea.addEventListener("input", () => {
+ clearTimeout(saveTimeout);
+ document.getElementById("feedback-status").textContent = "";
+ saveTimeout = setTimeout(() => saveCurrentFeedback(), 800);
+ });
+ }
+
+ // ---- Navigation ----
+ function navigate(delta) {
+ const newIndex = currentIndex + delta;
+ if (newIndex >= 0 && newIndex < EMBEDDED_DATA.runs.length) {
+ saveCurrentFeedback();
+ showRun(newIndex);
+ }
+ }
+
+ function updateNavButtons() {
+ document.getElementById("prev-btn").disabled = currentIndex === 0;
+ document.getElementById("next-btn").disabled =
+ currentIndex === EMBEDDED_DATA.runs.length - 1;
+ }
+
+ // ---- Show a run ----
+ function showRun(index) {
+ currentIndex = index;
+ const run = EMBEDDED_DATA.runs[index];
+
+ // Progress
+ document.getElementById("progress").textContent =
+ `${index + 1} of ${EMBEDDED_DATA.runs.length}`;
+
+ // Prompt
+ document.getElementById("prompt-text").textContent = run.prompt;
+
+ // Config badge
+ const badge = document.getElementById("config-badge");
+ const configMatch = run.id.match(/(with_skill|without_skill|new_skill|old_skill)/);
+ if (configMatch) {
+ const config = configMatch[1];
+ const isBaseline = config === "without_skill" || config === "old_skill";
+ badge.textContent = config.replace(/_/g, " ");
+ badge.className = "config-badge " + (isBaseline ? "config-baseline" : "config-primary");
+ badge.style.display = "inline-block";
+ } else {
+ badge.style.display = "none";
+ }
+
+ // Outputs
+ renderOutputs(run);
+
+ // Previous outputs
+ renderPrevOutputs(run);
+
+ // Grades
+ renderGrades(run);
+
+ // Previous feedback
+ const prevFb = (EMBEDDED_DATA.previous_feedback || {})[run.id];
+ const prevEl = document.getElementById("prev-feedback");
+ if (prevFb) {
+ document.getElementById("prev-feedback-text").textContent = prevFb;
+ prevEl.style.display = "block";
+ } else {
+ prevEl.style.display = "none";
+ }
+
+ // Feedback
+ document.getElementById("feedback").value = feedbackMap[run.id] || "";
+ document.getElementById("feedback-status").textContent = "";
+
+ updateNavButtons();
+
+ // Track visited runs and promote done button when all visited
+ visitedRuns.add(index);
+ const doneBtn = document.getElementById("done-btn");
+ if (visitedRuns.size >= EMBEDDED_DATA.runs.length) {
+ doneBtn.classList.add("ready");
+ }
+
+ // Scroll main content to top
+ document.querySelector(".main").scrollTop = 0;
+ }
+
+ // ---- Render outputs ----
+ function renderOutputs(run) {
+ const container = document.getElementById("outputs-body");
+ container.innerHTML = "";
+
+ const outputs = run.outputs || [];
+ if (outputs.length === 0) {
+ container.innerHTML = '<div class="empty-state">No output files</div>';
+ return;
+ }
+
+ for (const file of outputs) {
+ const fileDiv = document.createElement("div");
+ fileDiv.className = "output-file";
+
+ // Always show file header with download link
+ const header = document.createElement("div");
+ header.className = "output-file-header";
+ const nameSpan = document.createElement("span");
+ nameSpan.textContent = file.name;
+ header.appendChild(nameSpan);
+ const dlBtn = document.createElement("a");
+ dlBtn.className = "dl-btn";
+ dlBtn.textContent = "Download";
+ dlBtn.download = file.name;
+ dlBtn.href = getDownloadUri(file);
+ header.appendChild(dlBtn);
+ fileDiv.appendChild(header);
+
+ const content = document.createElement("div");
+ content.className = "output-file-content";
+
+ if (file.type === "text") {
+ const pre = document.createElement("pre");
+ pre.textContent = file.content;
+ content.appendChild(pre);
+ } else if (file.type === "image") {
+ const img = document.createElement("img");
+ img.src = file.data_uri;
+ img.alt = file.name;
+ content.appendChild(img);
+ } else if (file.type === "pdf") {
+ const iframe = document.createElement("iframe");
+ iframe.src = file.data_uri;
+ content.appendChild(iframe);
+ } else if (file.type === "xlsx") {
+ renderXlsx(content, file.data_b64);
+ } else if (file.type === "binary") {
+ const a = document.createElement("a");
+ a.className = "download-link";
+ a.href = file.data_uri;
+ a.download = file.name;
+ a.textContent = "Download " + file.name;
+ content.appendChild(a);
+ } else if (file.type === "error") {
+ const pre = document.createElement("pre");
+ pre.textContent = file.content;
+ pre.style.color = "var(--red)";
+ content.appendChild(pre);
+ }
+
+ fileDiv.appendChild(content);
+ container.appendChild(fileDiv);
+ }
+ }
+
+ // ---- XLSX rendering via SheetJS ----
+ function renderXlsx(container, b64Data) {
+ try {
+ const raw = Uint8Array.from(atob(b64Data), c => c.charCodeAt(0));
+ const wb = XLSX.read(raw, { type: "array" });
+
+ for (let i = 0; i < wb.SheetNames.length; i++) {
+ const sheetName = wb.SheetNames[i];
+ const ws = wb.Sheets[sheetName];
+
+ if (wb.SheetNames.length > 1) {
+ const sheetLabel = document.createElement("div");
+ sheetLabel.style.cssText =
+ "font-weight:600; font-size:0.8rem; color:#b0aea5; margin-top:0.5rem; margin-bottom:0.25rem;";
+ sheetLabel.textContent = "Sheet: " + sheetName;
+ container.appendChild(sheetLabel);
+ }
+
+ const htmlStr = XLSX.utils.sheet_to_html(ws, { editable: false });
+ const wrapper = document.createElement("div");
+ wrapper.innerHTML = htmlStr;
+ container.appendChild(wrapper);
+ }
+ } catch (err) {
+ container.textContent = "Error rendering spreadsheet: " + err.message;
+ }
+ }
+
+ // ---- Grades ----
+ function renderGrades(run) {
+ const section = document.getElementById("grades-section");
+ const content = document.getElementById("grades-content");
+
+ if (!run.grading) {
+ section.style.display = "none";
+ return;
+ }
+
+ const grading = run.grading;
+ section.style.display = "block";
+ // Reset to collapsed
+ content.classList.remove("open");
+ document.getElementById("grades-arrow").classList.remove("open");
+
+ const summary = grading.summary || {};
+ const expectations = grading.expectations || [];
+
+ let html = '<div style="padding: 1rem;">';
+
+ // Summary line
+ const passRate = summary.pass_rate != null
+ ? Math.round(summary.pass_rate * 100) + "%"
+ : "?";
+ const badgeClass = summary.pass_rate >= 0.8 ? "grade-pass" : summary.pass_rate >= 0.5 ? "" : "grade-fail";
+ html += '<div class="grades-summary">';
+ html += '<span class="grade-badge ' + badgeClass + '">' + passRate + '</span>';
+ html += '<span>' + (summary.passed || 0) + ' passed, ' + (summary.failed || 0) + ' failed of ' + (summary.total || 0) + '</span>';
+ html += '</div>';
+
+ // Assertions list
+ html += '<ul class="assertion-list">';
+ for (const exp of expectations) {
+ const statusClass = exp.passed ? "pass" : "fail";
+ const statusIcon = exp.passed ? "\u2713" : "\u2717";
+ html += '<li class="assertion-item">';
+ html += '<span class="assertion-status ' + statusClass + '">' + statusIcon + '</span>';
+ html += '<span>' + escapeHtml(exp.text) + '</span>';
+ if (exp.evidence) {
+ html += '<div class="assertion-evidence">' + escapeHtml(exp.evidence) + '</div>';
+ }
+ html += '</li>';
+ }
+ html += '</ul>';
+
+ html += '</div>';
+ content.innerHTML = html;
+ }
+
+ function toggleGrades() {
+ const content = document.getElementById("grades-content");
+ const arrow = document.getElementById("grades-arrow");
+ content.classList.toggle("open");
+ arrow.classList.toggle("open");
+ }
+
+ // ---- Previous outputs (collapsible) ----
+ function renderPrevOutputs(run) {
+ const section = document.getElementById("prev-outputs-section");
+ const content = document.getElementById("prev-outputs-content");
+ const prevOutputs = (EMBEDDED_DATA.previous_outputs || {})[run.id];
+
+ if (!prevOutputs || prevOutputs.length === 0) {
+ section.style.display = "none";
+ return;
+ }
+
+ section.style.display = "block";
+ // Reset to collapsed
+ content.classList.remove("open");
+ document.getElementById("prev-outputs-arrow").classList.remove("open");
+
+ // Render the files into the content area
+ content.innerHTML = "";
+ const wrapper = document.createElement("div");
+ wrapper.style.padding = "1rem";
+
+ for (const file of prevOutputs) {
+ const fileDiv = document.createElement("div");
+ fileDiv.className = "output-file";
+
+ const header = document.createElement("div");
+ header.className = "output-file-header";
+ const nameSpan = document.createElement("span");
+ nameSpan.textContent = file.name;
+ header.appendChild(nameSpan);
+ const dlBtn = document.createElement("a");
+ dlBtn.className = "dl-btn";
+ dlBtn.textContent = "Download";
+ dlBtn.download = file.name;
+ dlBtn.href = getDownloadUri(file);
+ header.appendChild(dlBtn);
+ fileDiv.appendChild(header);
+
+ const fc = document.createElement("div");
+ fc.className = "output-file-content";
+
+ if (file.type === "text") {
+ const pre = document.createElement("pre");
+ pre.textContent = file.content;
+ fc.appendChild(pre);
+ } else if (file.type === "image") {
+ const img = document.createElement("img");
+ img.src = file.data_uri;
+ img.alt = file.name;
+ fc.appendChild(img);
+ } else if (file.type === "pdf") {
+ const iframe = document.createElement("iframe");
+ iframe.src = file.data_uri;
+ fc.appendChild(iframe);
+ } else if (file.type === "xlsx") {
+ renderXlsx(fc, file.data_b64);
+ } else if (file.type === "binary") {
+ const a = document.createElement("a");
+ a.className = "download-link";
+ a.href = file.data_uri;
+ a.download = file.name;
+ a.textContent = "Download " + file.name;
+ fc.appendChild(a);
+ }
+
+ fileDiv.appendChild(fc);
+ wrapper.appendChild(fileDiv);
+ }
+
+ content.appendChild(wrapper);
+ }
+
+ function togglePrevOutputs() {
+ const content = document.getElementById("prev-outputs-content");
+ const arrow = document.getElementById("prev-outputs-arrow");
+ content.classList.toggle("open");
+ arrow.classList.toggle("open");
+ }
+
+ // ---- Feedback (saved to server -> feedback.json) ----
+ function saveCurrentFeedback() {
+ const run = EMBEDDED_DATA.runs[currentIndex];
+ const text = document.getElementById("feedback").value;
+
+ if (text.trim() === "") {
+ delete feedbackMap[run.id];
+ } else {
+ feedbackMap[run.id] = text;
+ }
+
+ // Build reviews array from map
+ const reviews = [];
+ for (const [run_id, feedback] of Object.entries(feedbackMap)) {
+ if (feedback.trim()) {
+ reviews.push({ run_id, feedback, timestamp: new Date().toISOString() });
+ }
+ }
+
+ fetch("/api/feedback", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ reviews, status: "in_progress" }),
+ }).then(() => {
+ document.getElementById("feedback-status").textContent = "Saved";
+ }).catch(() => {
+ // Static mode or server unavailable — no-op on auto-save,
+ // feedback will be downloaded on final submit
+ document.getElementById("feedback-status").textContent = "Will download on submit";
+ });
+ }
+
+ // ---- Done ----
+ function showDoneDialog() {
+ // Save current textarea to feedbackMap (but don't POST yet)
+ const run = EMBEDDED_DATA.runs[currentIndex];
+ const text = document.getElementById("feedback").value;
+ if (text.trim() === "") {
+ delete feedbackMap[run.id];
+ } else {
+ feedbackMap[run.id] = text;
+ }
+
+ // POST once with status: complete — include ALL runs so the model
+ // can distinguish "no feedback" (looks good) from "not reviewed"
+ const reviews = [];
+ const ts = new Date().toISOString();
+ for (const r of EMBEDDED_DATA.runs) {
+ reviews.push({ run_id: r.id, feedback: feedbackMap[r.id] || "", timestamp: ts });
+ }
+ const payload = JSON.stringify({ reviews, status: "complete" }, null, 2);
+ fetch("/api/feedback", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: payload,
+ }).then(() => {
+ document.getElementById("done-overlay").classList.add("visible");
+ }).catch(() => {
+ // Server not available (static mode) — download as file
+ const blob = new Blob([payload], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "feedback.json";
+ a.click();
+ URL.revokeObjectURL(url);
+ document.getElementById("done-overlay").classList.add("visible");
+ });
+ }
+
+ function closeDoneDialog() {
+ // Reset status back to in_progress
+ saveCurrentFeedback();
+ document.getElementById("done-overlay").classList.remove("visible");
+ }
+
+ // ---- Toast ----
+ function showToast(message) {
+ const toast = document.getElementById("toast");
+ toast.textContent = message;
+ toast.classList.add("visible");
+ setTimeout(() => toast.classList.remove("visible"), 2000);
+ }
+
+ // ---- Keyboard nav ----
+ document.addEventListener("keydown", (e) => {
+ // Don't capture when typing in textarea
+ if (e.target.tagName === "TEXTAREA") return;
+
+ if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
+ e.preventDefault();
+ navigate(-1);
+ } else if (e.key === "ArrowRight" || e.key === "ArrowDown") {
+ e.preventDefault();
+ navigate(1);
+ }
+ });
+
+ // ---- Util ----
+ function getDownloadUri(file) {
+ if (file.data_uri) return file.data_uri;
+ if (file.data_b64) return "data:application/octet-stream;base64," + file.data_b64;
+ if (file.type === "text") return "data:text/plain;charset=utf-8," + encodeURIComponent(file.content);
+ return "#";
+ }
+
+ function escapeHtml(text) {
+ const div = document.createElement("div");
+ div.textContent = text;
+ return div.innerHTML;
+ }
+
+ // ---- View switching ----
+ function switchView(view) {
+ document.querySelectorAll(".view-tab").forEach(t => t.classList.remove("active"));
+ document.querySelectorAll(".view-panel").forEach(p => p.classList.remove("active"));
+ document.querySelector(`[onclick="switchView('${view}')"]`).classList.add("active");
+ document.getElementById("panel-" + view).classList.add("active");
+ }
+
+ // ---- Benchmark rendering ----
+ function renderBenchmark() {
+ const data = EMBEDDED_DATA.benchmark;
+ if (!data) return;
+
+ // Show the tabs
+ document.getElementById("view-tabs").style.display = "flex";
+
+ const container = document.getElementById("benchmark-content");
+ const summary = data.run_summary || {};
+ const metadata = data.metadata || {};
+ const notes = data.notes || [];
+
+ let html = "";
+
+ // Header
+ html += "<h2 style='font-family: Poppins, sans-serif; margin-bottom: 0.5rem;'>Benchmark Results</h2>";
+ html += "<p style='color: var(--text-muted); font-size: 0.875rem; margin-bottom: 1.25rem;'>";
+ if (metadata.skill_name) html += "<strong>" + escapeHtml(metadata.skill_name) + "</strong> &mdash; ";
+ if (metadata.timestamp) html += metadata.timestamp + " &mdash; ";
+ if (metadata.evals_run) html += "Evals: " + metadata.evals_run.join(", ") + " &mdash; ";
+ html += (metadata.runs_per_configuration || "?") + " runs per configuration";
+ html += "</p>";
+
+ // Summary table
+ html += '<table class="benchmark-table">';
+
+ function fmtStat(stat, pct) {
+ if (!stat) return "—";
+ const suffix = pct ? "%" : "";
+ const m = pct ? (stat.mean * 100).toFixed(0) : stat.mean.toFixed(1);
+ const s = pct ? (stat.stddev * 100).toFixed(0) : stat.stddev.toFixed(1);
+ return m + suffix + " ± " + s + suffix;
+ }
+
+ function deltaClass(val) {
+ if (!val) return "";
+ const n = parseFloat(val);
+ if (n > 0) return "benchmark-delta-positive";
+ if (n < 0) return "benchmark-delta-negative";
+ return "";
+ }
+
+ // Discover config names dynamically (everything except "delta")
+ const configs = Object.keys(summary).filter(k => k !== "delta");
+ const configA = configs[0] || "config_a";
+ const configB = configs[1] || "config_b";
+ const labelA = configA.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
+ const labelB = configB.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
+ const a = summary[configA] || {};
+ const b = summary[configB] || {};
+ const delta = summary.delta || {};
+
+ html += "<thead><tr><th>Metric</th><th>" + escapeHtml(labelA) + "</th><th>" + escapeHtml(labelB) + "</th><th>Delta</th></tr></thead>";
+ html += "<tbody>";
+
+ html += "<tr><td><strong>Pass Rate</strong></td>";
+ html += "<td>" + fmtStat(a.pass_rate, true) + "</td>";
+ html += "<td>" + fmtStat(b.pass_rate, true) + "</td>";
+ html += '<td class="' + deltaClass(delta.pass_rate) + '">' + (delta.pass_rate || "—") + "</td></tr>";
+
+ // Time (only show row if data exists)
+ if (a.time_seconds || b.time_seconds) {
+ html += "<tr><td><strong>Time (s)</strong></td>";
+ html += "<td>" + fmtStat(a.time_seconds, false) + "</td>";
+ html += "<td>" + fmtStat(b.time_seconds, false) + "</td>";
+ html += '<td class="' + deltaClass(delta.time_seconds) + '">' + (delta.time_seconds ? delta.time_seconds + "s" : "—") + "</td></tr>";
+ }
+
+ // Tokens (only show row if data exists)
+ if (a.tokens || b.tokens) {
+ html += "<tr><td><strong>Tokens</strong></td>";
+ html += "<td>" + fmtStat(a.tokens, false) + "</td>";
+ html += "<td>" + fmtStat(b.tokens, false) + "</td>";
+ html += '<td class="' + deltaClass(delta.tokens) + '">' + (delta.tokens || "—") + "</td></tr>";
+ }
+
+ html += "</tbody></table>";
+
+ // Per-eval breakdown (if runs data available)
+ const runs = data.runs || [];
+ if (runs.length > 0) {
+ const evalIds = [...new Set(runs.map(r => r.eval_id))].sort((a, b) => a - b);
+
+ html += "<h3 style='font-family: Poppins, sans-serif; margin-bottom: 0.75rem;'>Per-Eval Breakdown</h3>";
+
+ const hasTime = runs.some(r => r.result && r.result.time_seconds != null);
+ const hasErrors = runs.some(r => r.result && r.result.errors > 0);
+
+ for (const evalId of evalIds) {
+ const evalRuns = runs.filter(r => r.eval_id === evalId);
+ const evalName = evalRuns[0] && evalRuns[0].eval_name ? evalRuns[0].eval_name : "Eval " + evalId;
+
+ html += "<h4 style='font-family: Poppins, sans-serif; margin: 1rem 0 0.5rem; color: var(--text);'>" + escapeHtml(evalName) + "</h4>";
+ html += '<table class="benchmark-table">';
+ html += "<thead><tr><th>Config</th><th>Run</th><th>Pass Rate</th>";
+ if (hasTime) html += "<th>Time (s)</th>";
+ if (hasErrors) html += "<th>Crashes During Execution</th>";
+ html += "</tr></thead>";
+ html += "<tbody>";
+
+ // Group by config and render with average rows
+ const configGroups = [...new Set(evalRuns.map(r => r.configuration))];
+ for (let ci = 0; ci < configGroups.length; ci++) {
+ const config = configGroups[ci];
+ const configRuns = evalRuns.filter(r => r.configuration === config);
+ if (configRuns.length === 0) continue;
+
+ const rowClass = ci === 0 ? "benchmark-row-with" : "benchmark-row-without";
+ const configLabel = config.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
+
+ for (const run of configRuns) {
+ const r = run.result || {};
+ const prClass = r.pass_rate >= 0.8 ? "benchmark-delta-positive" : r.pass_rate < 0.5 ? "benchmark-delta-negative" : "";
+ html += '<tr class="' + rowClass + '">';
+ html += "<td>" + configLabel + "</td>";
+ html += "<td>" + run.run_number + "</td>";
+ html += '<td class="' + prClass + '">' + ((r.pass_rate || 0) * 100).toFixed(0) + "% (" + (r.passed || 0) + "/" + (r.total || 0) + ")</td>";
+ if (hasTime) html += "<td>" + (r.time_seconds != null ? r.time_seconds.toFixed(1) : "—") + "</td>";
+ if (hasErrors) html += "<td>" + (r.errors || 0) + "</td>";
+ html += "</tr>";
+ }
+
+ // Average row
+ const rates = configRuns.map(r => (r.result || {}).pass_rate || 0);
+ const avgRate = rates.reduce((a, b) => a + b, 0) / rates.length;
+ const avgPrClass = avgRate >= 0.8 ? "benchmark-delta-positive" : avgRate < 0.5 ? "benchmark-delta-negative" : "";
+ html += '<tr class="benchmark-row-avg ' + rowClass + '">';
+ html += "<td>" + configLabel + "</td>";
+ html += "<td>Avg</td>";
+ html += '<td class="' + avgPrClass + '">' + (avgRate * 100).toFixed(0) + "%</td>";
+ if (hasTime) {
+ const times = configRuns.map(r => (r.result || {}).time_seconds).filter(t => t != null);
+ html += "<td>" + (times.length ? (times.reduce((a, b) => a + b, 0) / times.length).toFixed(1) : "—") + "</td>";
+ }
+ if (hasErrors) html += "<td></td>";
+ html += "</tr>";
+ }
+ html += "</tbody></table>";
+
+ // Per-assertion detail for this eval
+ const runsWithExpectations = {};
+ for (const config of configGroups) {
+ runsWithExpectations[config] = evalRuns.filter(r => r.configuration === config && r.expectations && r.expectations.length > 0);
+ }
+ const hasAnyExpectations = Object.values(runsWithExpectations).some(runs => runs.length > 0);
+ if (hasAnyExpectations) {
+ // Collect all unique assertion texts across all configs
+ const allAssertions = [];
+ const seen = new Set();
+ for (const config of configGroups) {
+ for (const run of runsWithExpectations[config]) {
+ for (const exp of (run.expectations || [])) {
+ if (!seen.has(exp.text)) {
+ seen.add(exp.text);
+ allAssertions.push(exp.text);
+ }
+ }
+ }
+ }
+
+ html += '<table class="benchmark-table" style="margin-top: 0.5rem;">';
+ html += "<thead><tr><th>Assertion</th>";
+ for (const config of configGroups) {
+ const label = config.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
+ html += "<th>" + escapeHtml(label) + "</th>";
+ }
+ html += "</tr></thead><tbody>";
+
+ for (const assertionText of allAssertions) {
+ html += "<tr><td>" + escapeHtml(assertionText) + "</td>";
+
+ for (const config of configGroups) {
+ html += "<td>";
+ for (const run of runsWithExpectations[config]) {
+ const exp = (run.expectations || []).find(e => e.text === assertionText);
+ if (exp) {
+ const cls = exp.passed ? "benchmark-delta-positive" : "benchmark-delta-negative";
+ const icon = exp.passed ? "\u2713" : "\u2717";
+ html += '<span class="' + cls + '" title="Run ' + run.run_number + ': ' + escapeHtml(exp.evidence || "") + '">' + icon + "</span> ";
+ } else {
+ html += "— ";
+ }
+ }
+ html += "</td>";
+ }
+ html += "</tr>";
+ }
+ html += "</tbody></table>";
+ }
+ }
+ }
+
+ // Notes
+ if (notes.length > 0) {
+ html += '<div class="benchmark-notes">';
+ html += "<h3>Analysis Notes</h3>";
+ html += "<ul>";
+ for (const note of notes) {
+ html += "<li>" + escapeHtml(note) + "</li>";
+ }
+ html += "</ul></div>";
+ }
+
+ container.innerHTML = html;
+ }
+
+ // ---- Start ----
+ init();
+ renderBenchmark();
+ </script>
+</body>
+</html>
diff --git a/.agents/skills/skill-creator/references/schemas.md b/.agents/skills/skill-creator/references/schemas.md
new file mode 100644
index 00000000..b6eeaa2d
--- /dev/null
+++ b/.agents/skills/skill-creator/references/schemas.md
@@ -0,0 +1,430 @@
+# JSON Schemas
+
+This document defines the JSON schemas used by skill-creator.
+
+---
+
+## evals.json
+
+Defines the evals for a skill. Located at `evals/evals.json` within the skill directory.
+
+```json
+{
+ "skill_name": "example-skill",
+ "evals": [
+ {
+ "id": 1,
+ "prompt": "User's example prompt",
+ "expected_output": "Description of expected result",
+ "files": ["evals/files/sample1.pdf"],
+ "expectations": [
+ "The output includes X",
+ "The skill used script Y"
+ ]
+ }
+ ]
+}
+```
+
+**Fields:**
+- `skill_name`: Name matching the skill's frontmatter
+- `evals[].id`: Unique integer identifier
+- `evals[].prompt`: The task to execute
+- `evals[].expected_output`: Human-readable description of success
+- `evals[].files`: Optional list of input file paths (relative to skill root)
+- `evals[].expectations`: List of verifiable statements
+
+---
+
+## history.json
+
+Tracks version progression in Improve mode. Located at workspace root.
+
+```json
+{
+ "started_at": "2026-01-15T10:30:00Z",
+ "skill_name": "pdf",
+ "current_best": "v2",
+ "iterations": [
+ {
+ "version": "v0",
+ "parent": null,
+ "expectation_pass_rate": 0.65,
+ "grading_result": "baseline",
+ "is_current_best": false
+ },
+ {
+ "version": "v1",
+ "parent": "v0",
+ "expectation_pass_rate": 0.75,
+ "grading_result": "won",
+ "is_current_best": false
+ },
+ {
+ "version": "v2",
+ "parent": "v1",
+ "expectation_pass_rate": 0.85,
+ "grading_result": "won",
+ "is_current_best": true
+ }
+ ]
+}
+```
+
+**Fields:**
+- `started_at`: ISO timestamp of when improvement started
+- `skill_name`: Name of the skill being improved
+- `current_best`: Version identifier of the best performer
+- `iterations[].version`: Version identifier (v0, v1, ...)
+- `iterations[].parent`: Parent version this was derived from
+- `iterations[].expectation_pass_rate`: Pass rate from grading
+- `iterations[].grading_result`: "baseline", "won", "lost", or "tie"
+- `iterations[].is_current_best`: Whether this is the current best version
+
+---
+
+## grading.json
+
+Output from the grader agent. Located at `<run-dir>/grading.json`.
+
+```json
+{
+ "expectations": [
+ {
+ "text": "The output includes the name 'John Smith'",
+ "passed": true,
+ "evidence": "Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'"
+ },
+ {
+ "text": "The spreadsheet has a SUM formula in cell B10",
+ "passed": false,
+ "evidence": "No spreadsheet was created. The output was a text file."
+ }
+ ],
+ "summary": {
+ "passed": 2,
+ "failed": 1,
+ "total": 3,
+ "pass_rate": 0.67
+ },
+ "execution_metrics": {
+ "tool_calls": {
+ "Read": 5,
+ "Write": 2,
+ "Bash": 8
+ },
+ "total_tool_calls": 15,
+ "total_steps": 6,
+ "errors_encountered": 0,
+ "output_chars": 12450,
+ "transcript_chars": 3200
+ },
+ "timing": {
+ "executor_duration_seconds": 165.0,
+ "grader_duration_seconds": 26.0,
+ "total_duration_seconds": 191.0
+ },
+ "claims": [
+ {
+ "claim": "The form has 12 fillable fields",
+ "type": "factual",
+ "verified": true,
+ "evidence": "Counted 12 fields in field_info.json"
+ }
+ ],
+ "user_notes_summary": {
+ "uncertainties": ["Used 2023 data, may be stale"],
+ "needs_review": [],
+ "workarounds": ["Fell back to text overlay for non-fillable fields"]
+ },
+ "eval_feedback": {
+ "suggestions": [
+ {
+ "assertion": "The output includes the name 'John Smith'",
+ "reason": "A hallucinated document that mentions the name would also pass"
+ }
+ ],
+ "overall": "Assertions check presence but not correctness."
+ }
+}
+```
+
+**Fields:**
+- `expectations[]`: Graded expectations with evidence
+- `summary`: Aggregate pass/fail counts
+- `execution_metrics`: Tool usage and output size (from executor's metrics.json)
+- `timing`: Wall clock timing (from timing.json)
+- `claims`: Extracted and verified claims from the output
+- `user_notes_summary`: Issues flagged by the executor
+- `eval_feedback`: (optional) Improvement suggestions for the evals, only present when the grader identifies issues worth raising
+
+---
+
+## metrics.json
+
+Output from the executor agent. Located at `<run-dir>/outputs/metrics.json`.
+
+```json
+{
+ "tool_calls": {
+ "Read": 5,
+ "Write": 2,
+ "Bash": 8,
+ "Edit": 1,
+ "Glob": 2,
+ "Grep": 0
+ },
+ "total_tool_calls": 18,
+ "total_steps": 6,
+ "files_created": ["filled_form.pdf", "field_values.json"],
+ "errors_encountered": 0,
+ "output_chars": 12450,
+ "transcript_chars": 3200
+}
+```
+
+**Fields:**
+- `tool_calls`: Count per tool type
+- `total_tool_calls`: Sum of all tool calls
+- `total_steps`: Number of major execution steps
+- `files_created`: List of output files created
+- `errors_encountered`: Number of errors during execution
+- `output_chars`: Total character count of output files
+- `transcript_chars`: Character count of transcript
+
+---
+
+## timing.json
+
+Wall clock timing for a run. Located at `<run-dir>/timing.json`.
+
+**How to capture:** When a subagent task completes, the task notification includes `total_tokens` and `duration_ms`. Save these immediately — they are not persisted anywhere else and cannot be recovered after the fact.
+
+```json
+{
+ "total_tokens": 84852,
+ "duration_ms": 23332,
+ "total_duration_seconds": 23.3,
+ "executor_start": "2026-01-15T10:30:00Z",
+ "executor_end": "2026-01-15T10:32:45Z",
+ "executor_duration_seconds": 165.0,
+ "grader_start": "2026-01-15T10:32:46Z",
+ "grader_end": "2026-01-15T10:33:12Z",
+ "grader_duration_seconds": 26.0
+}
+```
+
+---
+
+## benchmark.json
+
+Output from Benchmark mode. Located at `benchmarks/<timestamp>/benchmark.json`.
+
+```json
+{
+ "metadata": {
+ "skill_name": "pdf",
+ "skill_path": "/path/to/pdf",
+ "executor_model": "claude-sonnet-4-20250514",
+ "analyzer_model": "most-capable-model",
+ "timestamp": "2026-01-15T10:30:00Z",
+ "evals_run": [1, 2, 3],
+ "runs_per_configuration": 3
+ },
+
+ "runs": [
+ {
+ "eval_id": 1,
+ "eval_name": "Ocean",
+ "configuration": "with_skill",
+ "run_number": 1,
+ "result": {
+ "pass_rate": 0.85,
+ "passed": 6,
+ "failed": 1,
+ "total": 7,
+ "time_seconds": 42.5,
+ "tokens": 3800,
+ "tool_calls": 18,
+ "errors": 0
+ },
+ "expectations": [
+ {"text": "...", "passed": true, "evidence": "..."}
+ ],
+ "notes": [
+ "Used 2023 data, may be stale",
+ "Fell back to text overlay for non-fillable fields"
+ ]
+ }
+ ],
+
+ "run_summary": {
+ "with_skill": {
+ "pass_rate": {"mean": 0.85, "stddev": 0.05, "min": 0.80, "max": 0.90},
+ "time_seconds": {"mean": 45.0, "stddev": 12.0, "min": 32.0, "max": 58.0},
+ "tokens": {"mean": 3800, "stddev": 400, "min": 3200, "max": 4100}
+ },
+ "without_skill": {
+ "pass_rate": {"mean": 0.35, "stddev": 0.08, "min": 0.28, "max": 0.45},
+ "time_seconds": {"mean": 32.0, "stddev": 8.0, "min": 24.0, "max": 42.0},
+ "tokens": {"mean": 2100, "stddev": 300, "min": 1800, "max": 2500}
+ },
+ "delta": {
+ "pass_rate": "+0.50",
+ "time_seconds": "+13.0",
+ "tokens": "+1700"
+ }
+ },
+
+ "notes": [
+ "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value",
+ "Eval 3 shows high variance (50% ± 40%) - may be flaky or model-dependent",
+ "Without-skill runs consistently fail on table extraction expectations",
+ "Skill adds 13s average execution time but improves pass rate by 50%"
+ ]
+}
+```
+
+**Fields:**
+- `metadata`: Information about the benchmark run
+ - `skill_name`: Name of the skill
+ - `timestamp`: When the benchmark was run
+ - `evals_run`: List of eval names or IDs
+ - `runs_per_configuration`: Number of runs per config (e.g. 3)
+- `runs[]`: Individual run results
+ - `eval_id`: Numeric eval identifier
+ - `eval_name`: Human-readable eval name (used as section header in the viewer)
+ - `configuration`: Must be `"with_skill"` or `"without_skill"` (the viewer uses this exact string for grouping and color coding)
+ - `run_number`: Integer run number (1, 2, 3...)
+ - `result`: Nested object with `pass_rate`, `passed`, `total`, `time_seconds`, `tokens`, `errors`
+- `run_summary`: Statistical aggregates per configuration
+ - `with_skill` / `without_skill`: Each contains `pass_rate`, `time_seconds`, `tokens` objects with `mean` and `stddev` fields
+ - `delta`: Difference strings like `"+0.50"`, `"+13.0"`, `"+1700"`
+- `notes`: Freeform observations from the analyzer
+
+**Important:** The viewer reads these field names exactly. Using `config` instead of `configuration`, or putting `pass_rate` at the top level of a run instead of nested under `result`, will cause the viewer to show empty/zero values. Always reference this schema when generating benchmark.json manually.
+
+---
+
+## comparison.json
+
+Output from blind comparator. Located at `<grading-dir>/comparison-N.json`.
+
+```json
+{
+ "winner": "A",
+ "reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.",
+ "rubric": {
+ "A": {
+ "content": {
+ "correctness": 5,
+ "completeness": 5,
+ "accuracy": 4
+ },
+ "structure": {
+ "organization": 4,
+ "formatting": 5,
+ "usability": 4
+ },
+ "content_score": 4.7,
+ "structure_score": 4.3,
+ "overall_score": 9.0
+ },
+ "B": {
+ "content": {
+ "correctness": 3,
+ "completeness": 2,
+ "accuracy": 3
+ },
+ "structure": {
+ "organization": 3,
+ "formatting": 2,
+ "usability": 3
+ },
+ "content_score": 2.7,
+ "structure_score": 2.7,
+ "overall_score": 5.4
+ }
+ },
+ "output_quality": {
+ "A": {
+ "score": 9,
+ "strengths": ["Complete solution", "Well-formatted", "All fields present"],
+ "weaknesses": ["Minor style inconsistency in header"]
+ },
+ "B": {
+ "score": 5,
+ "strengths": ["Readable output", "Correct basic structure"],
+ "weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"]
+ }
+ },
+ "expectation_results": {
+ "A": {
+ "passed": 4,
+ "total": 5,
+ "pass_rate": 0.80,
+ "details": [
+ {"text": "Output includes name", "passed": true}
+ ]
+ },
+ "B": {
+ "passed": 3,
+ "total": 5,
+ "pass_rate": 0.60,
+ "details": [
+ {"text": "Output includes name", "passed": true}
+ ]
+ }
+ }
+}
+```
+
+---
+
+## analysis.json
+
+Output from post-hoc analyzer. Located at `<grading-dir>/analysis.json`.
+
+```json
+{
+ "comparison_summary": {
+ "winner": "A",
+ "winner_skill": "path/to/winner/skill",
+ "loser_skill": "path/to/loser/skill",
+ "comparator_reasoning": "Brief summary of why comparator chose winner"
+ },
+ "winner_strengths": [
+ "Clear step-by-step instructions for handling multi-page documents",
+ "Included validation script that caught formatting errors"
+ ],
+ "loser_weaknesses": [
+ "Vague instruction 'process the document appropriately' led to inconsistent behavior",
+ "No script for validation, agent had to improvise"
+ ],
+ "instruction_following": {
+ "winner": {
+ "score": 9,
+ "issues": ["Minor: skipped optional logging step"]
+ },
+ "loser": {
+ "score": 6,
+ "issues": [
+ "Did not use the skill's formatting template",
+ "Invented own approach instead of following step 3"
+ ]
+ }
+ },
+ "improvement_suggestions": [
+ {
+ "priority": "high",
+ "category": "instructions",
+ "suggestion": "Replace 'process the document appropriately' with explicit steps",
+ "expected_impact": "Would eliminate ambiguity that caused inconsistent behavior"
+ }
+ ],
+ "transcript_insights": {
+ "winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script",
+ "loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods"
+ }
+}
+```
diff --git a/.agents/skills/skill-creator/scripts/__init__.py b/.agents/skills/skill-creator/scripts/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/.agents/skills/skill-creator/scripts/aggregate_benchmark.py b/.agents/skills/skill-creator/scripts/aggregate_benchmark.py
new file mode 100755
index 00000000..3e66e8c1
--- /dev/null
+++ b/.agents/skills/skill-creator/scripts/aggregate_benchmark.py
@@ -0,0 +1,401 @@
+#!/usr/bin/env python3
+"""
+Aggregate individual run results into benchmark summary statistics.
+
+Reads grading.json files from run directories and produces:
+- run_summary with mean, stddev, min, max for each metric
+- delta between with_skill and without_skill configurations
+
+Usage:
+ python aggregate_benchmark.py <benchmark_dir>
+
+Example:
+ python aggregate_benchmark.py benchmarks/2026-01-15T10-30-00/
+
+The script supports two directory layouts:
+
+ Workspace layout (from skill-creator iterations):
+ <benchmark_dir>/
+ └── eval-N/
+ ├── with_skill/
+ │ ├── run-1/grading.json
+ │ └── run-2/grading.json
+ └── without_skill/
+ ├── run-1/grading.json
+ └── run-2/grading.json
+
+ Legacy layout (with runs/ subdirectory):
+ <benchmark_dir>/
+ └── runs/
+ └── eval-N/
+ ├── with_skill/
+ │ └── run-1/grading.json
+ └── without_skill/
+ └── run-1/grading.json
+"""
+
+import argparse
+import json
+import math
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+
+def calculate_stats(values: list[float]) -> dict:
+ """Calculate mean, stddev, min, max for a list of values."""
+ if not values:
+ return {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}
+
+ n = len(values)
+ mean = sum(values) / n
+
+ if n > 1:
+ variance = sum((x - mean) ** 2 for x in values) / (n - 1)
+ stddev = math.sqrt(variance)
+ else:
+ stddev = 0.0
+
+ return {
+ "mean": round(mean, 4),
+ "stddev": round(stddev, 4),
+ "min": round(min(values), 4),
+ "max": round(max(values), 4)
+ }
+
+
+def load_run_results(benchmark_dir: Path) -> dict:
+ """
+ Load all run results from a benchmark directory.
+
+ Returns dict keyed by config name (e.g. "with_skill"/"without_skill",
+ or "new_skill"/"old_skill"), each containing a list of run results.
+ """
+ # Support both layouts: eval dirs directly under benchmark_dir, or under runs/
+ runs_dir = benchmark_dir / "runs"
+ if runs_dir.exists():
+ search_dir = runs_dir
+ elif list(benchmark_dir.glob("eval-*")):
+ search_dir = benchmark_dir
+ else:
+ print(f"No eval directories found in {benchmark_dir} or {benchmark_dir / 'runs'}")
+ return {}
+
+ results: dict[str, list] = {}
+
+ for eval_idx, eval_dir in enumerate(sorted(search_dir.glob("eval-*"))):
+ metadata_path = eval_dir / "eval_metadata.json"
+ if metadata_path.exists():
+ try:
+ with open(metadata_path) as mf:
+ eval_id = json.load(mf).get("eval_id", eval_idx)
+ except (json.JSONDecodeError, OSError):
+ eval_id = eval_idx
+ else:
+ try:
+ eval_id = int(eval_dir.name.split("-")[1])
+ except ValueError:
+ eval_id = eval_idx
+
+ # Discover config directories dynamically rather than hardcoding names
+ for config_dir in sorted(eval_dir.iterdir()):
+ if not config_dir.is_dir():
+ continue
+ # Skip non-config directories (inputs, outputs, etc.)
+ if not list(config_dir.glob("run-*")):
+ continue
+ config = config_dir.name
+ if config not in results:
+ results[config] = []
+
+ for run_dir in sorted(config_dir.glob("run-*")):
+ run_number = int(run_dir.name.split("-")[1])
+ grading_file = run_dir / "grading.json"
+
+ if not grading_file.exists():
+ print(f"Warning: grading.json not found in {run_dir}")
+ continue
+
+ try:
+ with open(grading_file) as f:
+ grading = json.load(f)
+ except json.JSONDecodeError as e:
+ print(f"Warning: Invalid JSON in {grading_file}: {e}")
+ continue
+
+ # Extract metrics
+ result = {
+ "eval_id": eval_id,
+ "run_number": run_number,
+ "pass_rate": grading.get("summary", {}).get("pass_rate", 0.0),
+ "passed": grading.get("summary", {}).get("passed", 0),
+ "failed": grading.get("summary", {}).get("failed", 0),
+ "total": grading.get("summary", {}).get("total", 0),
+ }
+
+ # Extract timing — check grading.json first, then sibling timing.json
+ timing = grading.get("timing", {})
+ result["time_seconds"] = timing.get("total_duration_seconds", 0.0)
+ timing_file = run_dir / "timing.json"
+ if result["time_seconds"] == 0.0 and timing_file.exists():
+ try:
+ with open(timing_file) as tf:
+ timing_data = json.load(tf)
+ result["time_seconds"] = timing_data.get("total_duration_seconds", 0.0)
+ result["tokens"] = timing_data.get("total_tokens", 0)
+ except json.JSONDecodeError:
+ pass
+
+ # Extract metrics if available
+ metrics = grading.get("execution_metrics", {})
+ result["tool_calls"] = metrics.get("total_tool_calls", 0)
+ if not result.get("tokens"):
+ result["tokens"] = metrics.get("output_chars", 0)
+ result["errors"] = metrics.get("errors_encountered", 0)
+
+ # Extract expectations — viewer requires fields: text, passed, evidence
+ raw_expectations = grading.get("expectations", [])
+ for exp in raw_expectations:
+ if "text" not in exp or "passed" not in exp:
+ print(f"Warning: expectation in {grading_file} missing required fields (text, passed, evidence): {exp}")
+ result["expectations"] = raw_expectations
+
+ # Extract notes from user_notes_summary
+ notes_summary = grading.get("user_notes_summary", {})
+ notes = []
+ notes.extend(notes_summary.get("uncertainties", []))
+ notes.extend(notes_summary.get("needs_review", []))
+ notes.extend(notes_summary.get("workarounds", []))
+ result["notes"] = notes
+
+ results[config].append(result)
+
+ return results
+
+
+def aggregate_results(results: dict) -> dict:
+ """
+ Aggregate run results into summary statistics.
+
+ Returns run_summary with stats for each configuration and delta.
+ """
+ run_summary = {}
+ configs = list(results.keys())
+
+ for config in configs:
+ runs = results.get(config, [])
+
+ if not runs:
+ run_summary[config] = {
+ "pass_rate": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0},
+ "time_seconds": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0},
+ "tokens": {"mean": 0, "stddev": 0, "min": 0, "max": 0}
+ }
+ continue
+
+ pass_rates = [r["pass_rate"] for r in runs]
+ times = [r["time_seconds"] for r in runs]
+ tokens = [r.get("tokens", 0) for r in runs]
+
+ run_summary[config] = {
+ "pass_rate": calculate_stats(pass_rates),
+ "time_seconds": calculate_stats(times),
+ "tokens": calculate_stats(tokens)
+ }
+
+ # Calculate delta between the first two configs (if two exist)
+ if len(configs) >= 2:
+ primary = run_summary.get(configs[0], {})
+ baseline = run_summary.get(configs[1], {})
+ else:
+ primary = run_summary.get(configs[0], {}) if configs else {}
+ baseline = {}
+
+ delta_pass_rate = primary.get("pass_rate", {}).get("mean", 0) - baseline.get("pass_rate", {}).get("mean", 0)
+ delta_time = primary.get("time_seconds", {}).get("mean", 0) - baseline.get("time_seconds", {}).get("mean", 0)
+ delta_tokens = primary.get("tokens", {}).get("mean", 0) - baseline.get("tokens", {}).get("mean", 0)
+
+ run_summary["delta"] = {
+ "pass_rate": f"{delta_pass_rate:+.2f}",
+ "time_seconds": f"{delta_time:+.1f}",
+ "tokens": f"{delta_tokens:+.0f}"
+ }
+
+ return run_summary
+
+
+def generate_benchmark(benchmark_dir: Path, skill_name: str = "", skill_path: str = "") -> dict:
+ """
+ Generate complete benchmark.json from run results.
+ """
+ results = load_run_results(benchmark_dir)
+ run_summary = aggregate_results(results)
+
+ # Build runs array for benchmark.json
+ runs = []
+ for config in results:
+ for result in results[config]:
+ runs.append({
+ "eval_id": result["eval_id"],
+ "configuration": config,
+ "run_number": result["run_number"],
+ "result": {
+ "pass_rate": result["pass_rate"],
+ "passed": result["passed"],
+ "failed": result["failed"],
+ "total": result["total"],
+ "time_seconds": result["time_seconds"],
+ "tokens": result.get("tokens", 0),
+ "tool_calls": result.get("tool_calls", 0),
+ "errors": result.get("errors", 0)
+ },
+ "expectations": result["expectations"],
+ "notes": result["notes"]
+ })
+
+ # Determine eval IDs from results
+ eval_ids = sorted(set(
+ r["eval_id"]
+ for config in results.values()
+ for r in config
+ ))
+
+ benchmark = {
+ "metadata": {
+ "skill_name": skill_name or "<skill-name>",
+ "skill_path": skill_path or "<path/to/skill>",
+ "executor_model": "<model-name>",
+ "analyzer_model": "<model-name>",
+ "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "evals_run": eval_ids,
+ "runs_per_configuration": 3
+ },
+ "runs": runs,
+ "run_summary": run_summary,
+ "notes": [] # To be filled by analyzer
+ }
+
+ return benchmark
+
+
+def generate_markdown(benchmark: dict) -> str:
+ """Generate human-readable benchmark.md from benchmark data."""
+ metadata = benchmark["metadata"]
+ run_summary = benchmark["run_summary"]
+
+ # Determine config names (excluding "delta")
+ configs = [k for k in run_summary if k != "delta"]
+ config_a = configs[0] if len(configs) >= 1 else "config_a"
+ config_b = configs[1] if len(configs) >= 2 else "config_b"
+ label_a = config_a.replace("_", " ").title()
+ label_b = config_b.replace("_", " ").title()
+
+ lines = [
+ f"# Skill Benchmark: {metadata['skill_name']}",
+ "",
+ f"**Model**: {metadata['executor_model']}",
+ f"**Date**: {metadata['timestamp']}",
+ f"**Evals**: {', '.join(map(str, metadata['evals_run']))} ({metadata['runs_per_configuration']} runs each per configuration)",
+ "",
+ "## Summary",
+ "",
+ f"| Metric | {label_a} | {label_b} | Delta |",
+ "|--------|------------|---------------|-------|",
+ ]
+
+ a_summary = run_summary.get(config_a, {})
+ b_summary = run_summary.get(config_b, {})
+ delta = run_summary.get("delta", {})
+
+ # Format pass rate
+ a_pr = a_summary.get("pass_rate", {})
+ b_pr = b_summary.get("pass_rate", {})
+ lines.append(f"| Pass Rate | {a_pr.get('mean', 0)*100:.0f}% ± {a_pr.get('stddev', 0)*100:.0f}% | {b_pr.get('mean', 0)*100:.0f}% ± {b_pr.get('stddev', 0)*100:.0f}% | {delta.get('pass_rate', '—')} |")
+
+ # Format time
+ a_time = a_summary.get("time_seconds", {})
+ b_time = b_summary.get("time_seconds", {})
+ lines.append(f"| Time | {a_time.get('mean', 0):.1f}s ± {a_time.get('stddev', 0):.1f}s | {b_time.get('mean', 0):.1f}s ± {b_time.get('stddev', 0):.1f}s | {delta.get('time_seconds', '—')}s |")
+
+ # Format tokens
+ a_tokens = a_summary.get("tokens", {})
+ b_tokens = b_summary.get("tokens", {})
+ lines.append(f"| Tokens | {a_tokens.get('mean', 0):.0f} ± {a_tokens.get('stddev', 0):.0f} | {b_tokens.get('mean', 0):.0f} ± {b_tokens.get('stddev', 0):.0f} | {delta.get('tokens', '—')} |")
+
+ # Notes section
+ if benchmark.get("notes"):
+ lines.extend([
+ "",
+ "## Notes",
+ ""
+ ])
+ for note in benchmark["notes"]:
+ lines.append(f"- {note}")
+
+ return "\n".join(lines)
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Aggregate benchmark run results into summary statistics"
+ )
+ parser.add_argument(
+ "benchmark_dir",
+ type=Path,
+ help="Path to the benchmark directory"
+ )
+ parser.add_argument(
+ "--skill-name",
+ default="",
+ help="Name of the skill being benchmarked"
+ )
+ parser.add_argument(
+ "--skill-path",
+ default="",
+ help="Path to the skill being benchmarked"
+ )
+ parser.add_argument(
+ "--output", "-o",
+ type=Path,
+ help="Output path for benchmark.json (default: <benchmark_dir>/benchmark.json)"
+ )
+
+ args = parser.parse_args()
+
+ if not args.benchmark_dir.exists():
+ print(f"Directory not found: {args.benchmark_dir}")
+ sys.exit(1)
+
+ # Generate benchmark
+ benchmark = generate_benchmark(args.benchmark_dir, args.skill_name, args.skill_path)
+
+ # Determine output paths
+ output_json = args.output or (args.benchmark_dir / "benchmark.json")
+ output_md = output_json.with_suffix(".md")
+
+ # Write benchmark.json
+ with open(output_json, "w") as f:
+ json.dump(benchmark, f, indent=2)
+ print(f"Generated: {output_json}")
+
+ # Write benchmark.md
+ markdown = generate_markdown(benchmark)
+ with open(output_md, "w") as f:
+ f.write(markdown)
+ print(f"Generated: {output_md}")
+
+ # Print summary
+ run_summary = benchmark["run_summary"]
+ configs = [k for k in run_summary if k != "delta"]
+ delta = run_summary.get("delta", {})
+
+ print(f"\nSummary:")
+ for config in configs:
+ pr = run_summary[config]["pass_rate"]["mean"]
+ label = config.replace("_", " ").title()
+ print(f" {label}: {pr*100:.1f}% pass rate")
+ print(f" Delta: {delta.get('pass_rate', '—')}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/skill-creator/scripts/generate_report.py b/.agents/skills/skill-creator/scripts/generate_report.py
new file mode 100755
index 00000000..959e30a0
--- /dev/null
+++ b/.agents/skills/skill-creator/scripts/generate_report.py
@@ -0,0 +1,326 @@
+#!/usr/bin/env python3
+"""Generate an HTML report from run_loop.py output.
+
+Takes the JSON output from run_loop.py and generates a visual HTML report
+showing each description attempt with check/x for each test case.
+Distinguishes between train and test queries.
+"""
+
+import argparse
+import html
+import json
+import sys
+from pathlib import Path
+
+
+def generate_html(data: dict, auto_refresh: bool = False, skill_name: str = "") -> str:
+ """Generate HTML report from loop output data. If auto_refresh is True, adds a meta refresh tag."""
+ history = data.get("history", [])
+ holdout = data.get("holdout", 0)
+ title_prefix = html.escape(skill_name + " \u2014 ") if skill_name else ""
+
+ # Get all unique queries from train and test sets, with should_trigger info
+ train_queries: list[dict] = []
+ test_queries: list[dict] = []
+ if history:
+ for r in history[0].get("train_results", history[0].get("results", [])):
+ train_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)})
+ if history[0].get("test_results"):
+ for r in history[0].get("test_results", []):
+ test_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)})
+
+ refresh_tag = ' <meta http-equiv="refresh" content="5">\n' if auto_refresh else ""
+
+ html_parts = ["""<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+""" + refresh_tag + """ <title>""" + title_prefix + """Skill Description Optimization</title>
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap" rel="stylesheet">
+ <style>
+ body {
+ font-family: 'Lora', Georgia, serif;
+ max-width: 100%;
+ margin: 0 auto;
+ padding: 20px;
+ background: #faf9f5;
+ color: #141413;
+ }
+ h1 { font-family: 'Poppins', sans-serif; color: #141413; }
+ .explainer {
+ background: white;
+ padding: 15px;
+ border-radius: 6px;
+ margin-bottom: 20px;
+ border: 1px solid #e8e6dc;
+ color: #b0aea5;
+ font-size: 0.875rem;
+ line-height: 1.6;
+ }
+ .summary {
+ background: white;
+ padding: 15px;
+ border-radius: 6px;
+ margin-bottom: 20px;
+ border: 1px solid #e8e6dc;
+ }
+ .summary p { margin: 5px 0; }
+ .best { color: #788c5d; font-weight: bold; }
+ .table-container {
+ overflow-x: auto;
+ width: 100%;
+ }
+ table {
+ border-collapse: collapse;
+ background: white;
+ border: 1px solid #e8e6dc;
+ border-radius: 6px;
+ font-size: 12px;
+ min-width: 100%;
+ }
+ th, td {
+ padding: 8px;
+ text-align: left;
+ border: 1px solid #e8e6dc;
+ white-space: normal;
+ word-wrap: break-word;
+ }
+ th {
+ font-family: 'Poppins', sans-serif;
+ background: #141413;
+ color: #faf9f5;
+ font-weight: 500;
+ }
+ th.test-col {
+ background: #6a9bcc;
+ }
+ th.query-col { min-width: 200px; }
+ td.description {
+ font-family: monospace;
+ font-size: 11px;
+ word-wrap: break-word;
+ max-width: 400px;
+ }
+ td.result {
+ text-align: center;
+ font-size: 16px;
+ min-width: 40px;
+ }
+ td.test-result {
+ background: #f0f6fc;
+ }
+ .pass { color: #788c5d; }
+ .fail { color: #c44; }
+ .rate {
+ font-size: 9px;
+ color: #b0aea5;
+ display: block;
+ }
+ tr:hover { background: #faf9f5; }
+ .score {
+ display: inline-block;
+ padding: 2px 6px;
+ border-radius: 4px;
+ font-weight: bold;
+ font-size: 11px;
+ }
+ .score-good { background: #eef2e8; color: #788c5d; }
+ .score-ok { background: #fef3c7; color: #d97706; }
+ .score-bad { background: #fceaea; color: #c44; }
+ .train-label { color: #b0aea5; font-size: 10px; }
+ .test-label { color: #6a9bcc; font-size: 10px; font-weight: bold; }
+ .best-row { background: #f5f8f2; }
+ th.positive-col { border-bottom: 3px solid #788c5d; }
+ th.negative-col { border-bottom: 3px solid #c44; }
+ th.test-col.positive-col { border-bottom: 3px solid #788c5d; }
+ th.test-col.negative-col { border-bottom: 3px solid #c44; }
+ .legend { font-family: 'Poppins', sans-serif; display: flex; gap: 20px; margin-bottom: 10px; font-size: 13px; align-items: center; }
+ .legend-item { display: flex; align-items: center; gap: 6px; }
+ .legend-swatch { width: 16px; height: 16px; border-radius: 3px; display: inline-block; }
+ .swatch-positive { background: #141413; border-bottom: 3px solid #788c5d; }
+ .swatch-negative { background: #141413; border-bottom: 3px solid #c44; }
+ .swatch-test { background: #6a9bcc; }
+ .swatch-train { background: #141413; }
+ </style>
+</head>
+<body>
+ <h1>""" + title_prefix + """Skill Description Optimization</h1>
+ <div class="explainer">
+ <strong>Optimizing your skill's description.</strong> This page updates automatically as Claude tests different versions of your skill's description. Each row is an iteration — a new description attempt. The columns show test queries: green checkmarks mean the skill triggered correctly (or correctly didn't trigger), red crosses mean it got it wrong. The "Train" score shows performance on queries used to improve the description; the "Test" score shows performance on held-out queries the optimizer hasn't seen. When it's done, Claude will apply the best-performing description to your skill.
+ </div>
+"""]
+
+ # Summary section
+ best_test_score = data.get('best_test_score')
+ best_train_score = data.get('best_train_score')
+ html_parts.append(f"""
+ <div class="summary">
+ <p><strong>Original:</strong> {html.escape(data.get('original_description', 'N/A'))}</p>
+ <p class="best"><strong>Best:</strong> {html.escape(data.get('best_description', 'N/A'))}</p>
+ <p><strong>Best Score:</strong> {data.get('best_score', 'N/A')} {'(test)' if best_test_score else '(train)'}</p>
+ <p><strong>Iterations:</strong> {data.get('iterations_run', 0)} | <strong>Train:</strong> {data.get('train_size', '?')} | <strong>Test:</strong> {data.get('test_size', '?')}</p>
+ </div>
+""")
+
+ # Legend
+ html_parts.append("""
+ <div class="legend">
+ <span style="font-weight:600">Query columns:</span>
+ <span class="legend-item"><span class="legend-swatch swatch-positive"></span> Should trigger</span>
+ <span class="legend-item"><span class="legend-swatch swatch-negative"></span> Should NOT trigger</span>
+ <span class="legend-item"><span class="legend-swatch swatch-train"></span> Train</span>
+ <span class="legend-item"><span class="legend-swatch swatch-test"></span> Test</span>
+ </div>
+""")
+
+ # Table header
+ html_parts.append("""
+ <div class="table-container">
+ <table>
+ <thead>
+ <tr>
+ <th>Iter</th>
+ <th>Train</th>
+ <th>Test</th>
+ <th class="query-col">Description</th>
+""")
+
+ # Add column headers for train queries
+ for qinfo in train_queries:
+ polarity = "positive-col" if qinfo["should_trigger"] else "negative-col"
+ html_parts.append(f' <th class="{polarity}">{html.escape(qinfo["query"])}</th>\n')
+
+ # Add column headers for test queries (different color)
+ for qinfo in test_queries:
+ polarity = "positive-col" if qinfo["should_trigger"] else "negative-col"
+ html_parts.append(f' <th class="test-col {polarity}">{html.escape(qinfo["query"])}</th>\n')
+
+ html_parts.append(""" </tr>
+ </thead>
+ <tbody>
+""")
+
+ # Find best iteration for highlighting
+ if test_queries:
+ best_iter = max(history, key=lambda h: h.get("test_passed") or 0).get("iteration")
+ else:
+ best_iter = max(history, key=lambda h: h.get("train_passed", h.get("passed", 0))).get("iteration")
+
+ # Add rows for each iteration
+ for h in history:
+ iteration = h.get("iteration", "?")
+ train_passed = h.get("train_passed", h.get("passed", 0))
+ train_total = h.get("train_total", h.get("total", 0))
+ test_passed = h.get("test_passed")
+ test_total = h.get("test_total")
+ description = h.get("description", "")
+ train_results = h.get("train_results", h.get("results", []))
+ test_results = h.get("test_results", [])
+
+ # Create lookups for results by query
+ train_by_query = {r["query"]: r for r in train_results}
+ test_by_query = {r["query"]: r for r in test_results} if test_results else {}
+
+ # Compute aggregate correct/total runs across all retries
+ def aggregate_runs(results: list[dict]) -> tuple[int, int]:
+ correct = 0
+ total = 0
+ for r in results:
+ runs = r.get("runs", 0)
+ triggers = r.get("triggers", 0)
+ total += runs
+ if r.get("should_trigger", True):
+ correct += triggers
+ else:
+ correct += runs - triggers
+ return correct, total
+
+ train_correct, train_runs = aggregate_runs(train_results)
+ test_correct, test_runs = aggregate_runs(test_results)
+
+ # Determine score classes
+ def score_class(correct: int, total: int) -> str:
+ if total > 0:
+ ratio = correct / total
+ if ratio >= 0.8:
+ return "score-good"
+ elif ratio >= 0.5:
+ return "score-ok"
+ return "score-bad"
+
+ train_class = score_class(train_correct, train_runs)
+ test_class = score_class(test_correct, test_runs)
+
+ row_class = "best-row" if iteration == best_iter else ""
+
+ html_parts.append(f""" <tr class="{row_class}">
+ <td>{iteration}</td>
+ <td><span class="score {train_class}">{train_correct}/{train_runs}</span></td>
+ <td><span class="score {test_class}">{test_correct}/{test_runs}</span></td>
+ <td class="description">{html.escape(description)}</td>
+""")
+
+ # Add result for each train query
+ for qinfo in train_queries:
+ r = train_by_query.get(qinfo["query"], {})
+ did_pass = r.get("pass", False)
+ triggers = r.get("triggers", 0)
+ runs = r.get("runs", 0)
+
+ icon = "✓" if did_pass else "✗"
+ css_class = "pass" if did_pass else "fail"
+
+ html_parts.append(f' <td class="result {css_class}">{icon}<span class="rate">{triggers}/{runs}</span></td>\n')
+
+ # Add result for each test query (with different background)
+ for qinfo in test_queries:
+ r = test_by_query.get(qinfo["query"], {})
+ did_pass = r.get("pass", False)
+ triggers = r.get("triggers", 0)
+ runs = r.get("runs", 0)
+
+ icon = "✓" if did_pass else "✗"
+ css_class = "pass" if did_pass else "fail"
+
+ html_parts.append(f' <td class="result test-result {css_class}">{icon}<span class="rate">{triggers}/{runs}</span></td>\n')
+
+ html_parts.append(" </tr>\n")
+
+ html_parts.append(""" </tbody>
+ </table>
+ </div>
+""")
+
+ html_parts.append("""
+</body>
+</html>
+""")
+
+ return "".join(html_parts)
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Generate HTML report from run_loop output")
+ parser.add_argument("input", help="Path to JSON output from run_loop.py (or - for stdin)")
+ parser.add_argument("-o", "--output", default=None, help="Output HTML file (default: stdout)")
+ parser.add_argument("--skill-name", default="", help="Skill name to include in the report title")
+ args = parser.parse_args()
+
+ if args.input == "-":
+ data = json.load(sys.stdin)
+ else:
+ data = json.loads(Path(args.input).read_text())
+
+ html_output = generate_html(data, skill_name=args.skill_name)
+
+ if args.output:
+ Path(args.output).write_text(html_output)
+ print(f"Report written to {args.output}", file=sys.stderr)
+ else:
+ print(html_output)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/skill-creator/scripts/improve_description.py b/.agents/skills/skill-creator/scripts/improve_description.py
new file mode 100755
index 00000000..06bcec76
--- /dev/null
+++ b/.agents/skills/skill-creator/scripts/improve_description.py
@@ -0,0 +1,247 @@
+#!/usr/bin/env python3
+"""Improve a skill description based on eval results.
+
+Takes eval results (from run_eval.py) and generates an improved description
+by calling `claude -p` as a subprocess (same auth pattern as run_eval.py —
+uses the session's Claude Code auth, no separate ANTHROPIC_API_KEY needed).
+"""
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+from scripts.utils import parse_skill_md
+
+
+def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str:
+ """Run `claude -p` with the prompt on stdin and return the text response.
+
+ Prompt goes over stdin (not argv) because it embeds the full SKILL.md
+ body and can easily exceed comfortable argv length.
+ """
+ cmd = ["claude", "-p", "--output-format", "text"]
+ if model:
+ cmd.extend(["--model", model])
+
+ # Remove CLAUDECODE env var to allow nesting claude -p inside a
+ # Claude Code session. The guard is for interactive terminal conflicts;
+ # programmatic subprocess usage is safe. Same pattern as run_eval.py.
+ env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"}
+
+ result = subprocess.run(
+ cmd,
+ input=prompt,
+ capture_output=True,
+ text=True,
+ env=env,
+ timeout=timeout,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(
+ f"claude -p exited {result.returncode}\nstderr: {result.stderr}"
+ )
+ return result.stdout
+
+
+def improve_description(
+ skill_name: str,
+ skill_content: str,
+ current_description: str,
+ eval_results: dict,
+ history: list[dict],
+ model: str,
+ test_results: dict | None = None,
+ log_dir: Path | None = None,
+ iteration: int | None = None,
+) -> str:
+ """Call Claude to improve the description based on eval results."""
+ failed_triggers = [
+ r for r in eval_results["results"]
+ if r["should_trigger"] and not r["pass"]
+ ]
+ false_triggers = [
+ r for r in eval_results["results"]
+ if not r["should_trigger"] and not r["pass"]
+ ]
+
+ # Build scores summary
+ train_score = f"{eval_results['summary']['passed']}/{eval_results['summary']['total']}"
+ if test_results:
+ test_score = f"{test_results['summary']['passed']}/{test_results['summary']['total']}"
+ scores_summary = f"Train: {train_score}, Test: {test_score}"
+ else:
+ scores_summary = f"Train: {train_score}"
+
+ prompt = f"""You are optimizing a skill description for a Claude Code skill called "{skill_name}". A "skill" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples.
+
+The description appears in Claude's "available_skills" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones.
+
+Here's the current description:
+<current_description>
+"{current_description}"
+</current_description>
+
+Current scores ({scores_summary}):
+<scores_summary>
+"""
+ if failed_triggers:
+ prompt += "FAILED TO TRIGGER (should have triggered but didn't):\n"
+ for r in failed_triggers:
+ prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n'
+ prompt += "\n"
+
+ if false_triggers:
+ prompt += "FALSE TRIGGERS (triggered but shouldn't have):\n"
+ for r in false_triggers:
+ prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n'
+ prompt += "\n"
+
+ if history:
+ prompt += "PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\n\n"
+ for h in history:
+ train_s = f"{h.get('train_passed', h.get('passed', 0))}/{h.get('train_total', h.get('total', 0))}"
+ test_s = f"{h.get('test_passed', '?')}/{h.get('test_total', '?')}" if h.get('test_passed') is not None else None
+ score_str = f"train={train_s}" + (f", test={test_s}" if test_s else "")
+ prompt += f'<attempt {score_str}>\n'
+ prompt += f'Description: "{h["description"]}"\n'
+ if "results" in h:
+ prompt += "Train results:\n"
+ for r in h["results"]:
+ status = "PASS" if r["pass"] else "FAIL"
+ prompt += f' [{status}] "{r["query"][:80]}" (triggered {r["triggers"]}/{r["runs"]})\n'
+ if h.get("note"):
+ prompt += f'Note: {h["note"]}\n'
+ prompt += "</attempt>\n\n"
+
+ prompt += f"""</scores_summary>
+
+Skill content (for context on what the skill does):
+<skill_content>
+{skill_content}
+</skill_content>
+
+Based on the failures, write a new and improved description that is more likely to trigger correctly. When I say "based on the failures", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold:
+
+1. Avoid overfitting
+2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description.
+
+Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. There is a hard limit of 1024 characters — descriptions over that will be truncated, so stay comfortably under it.
+
+Here are some tips that we've found to work well in writing these descriptions:
+- The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does"
+- The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works.
+- The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable.
+- If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings.
+
+I'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end.
+
+Please respond with only the new description text in <new_description> tags, nothing else."""
+
+ text = _call_claude(prompt, model)
+
+ match = re.search(r"<new_description>(.*?)</new_description>", text, re.DOTALL)
+ description = match.group(1).strip().strip('"') if match else text.strip().strip('"')
+
+ transcript: dict = {
+ "iteration": iteration,
+ "prompt": prompt,
+ "response": text,
+ "parsed_description": description,
+ "char_count": len(description),
+ "over_limit": len(description) > 1024,
+ }
+
+ # Safety net: the prompt already states the 1024-char hard limit, but if
+ # the model blew past it anyway, make one fresh single-turn call that
+ # quotes the too-long version and asks for a shorter rewrite. (The old
+ # SDK path did this as a true multi-turn; `claude -p` is one-shot, so we
+ # inline the prior output into the new prompt instead.)
+ if len(description) > 1024:
+ shorten_prompt = (
+ f"{prompt}\n\n"
+ f"---\n\n"
+ f"A previous attempt produced this description, which at "
+ f"{len(description)} characters is over the 1024-character hard limit:\n\n"
+ f'"{description}"\n\n'
+ f"Rewrite it to be under 1024 characters while keeping the most "
+ f"important trigger words and intent coverage. Respond with only "
+ f"the new description in <new_description> tags."
+ )
+ shorten_text = _call_claude(shorten_prompt, model)
+ match = re.search(r"<new_description>(.*?)</new_description>", shorten_text, re.DOTALL)
+ shortened = match.group(1).strip().strip('"') if match else shorten_text.strip().strip('"')
+
+ transcript["rewrite_prompt"] = shorten_prompt
+ transcript["rewrite_response"] = shorten_text
+ transcript["rewrite_description"] = shortened
+ transcript["rewrite_char_count"] = len(shortened)
+ description = shortened
+
+ transcript["final_description"] = description
+
+ if log_dir:
+ log_dir.mkdir(parents=True, exist_ok=True)
+ log_file = log_dir / f"improve_iter_{iteration or 'unknown'}.json"
+ log_file.write_text(json.dumps(transcript, indent=2))
+
+ return description
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Improve a skill description based on eval results")
+ parser.add_argument("--eval-results", required=True, help="Path to eval results JSON (from run_eval.py)")
+ parser.add_argument("--skill-path", required=True, help="Path to skill directory")
+ parser.add_argument("--history", default=None, help="Path to history JSON (previous attempts)")
+ parser.add_argument("--model", required=True, help="Model for improvement")
+ parser.add_argument("--verbose", action="store_true", help="Print thinking to stderr")
+ args = parser.parse_args()
+
+ skill_path = Path(args.skill_path)
+ if not (skill_path / "SKILL.md").exists():
+ print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
+ sys.exit(1)
+
+ eval_results = json.loads(Path(args.eval_results).read_text())
+ history = []
+ if args.history:
+ history = json.loads(Path(args.history).read_text())
+
+ name, _, content = parse_skill_md(skill_path)
+ current_description = eval_results["description"]
+
+ if args.verbose:
+ print(f"Current: {current_description}", file=sys.stderr)
+ print(f"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}", file=sys.stderr)
+
+ new_description = improve_description(
+ skill_name=name,
+ skill_content=content,
+ current_description=current_description,
+ eval_results=eval_results,
+ history=history,
+ model=args.model,
+ )
+
+ if args.verbose:
+ print(f"Improved: {new_description}", file=sys.stderr)
+
+ # Output as JSON with both the new description and updated history
+ output = {
+ "description": new_description,
+ "history": history + [{
+ "description": current_description,
+ "passed": eval_results["summary"]["passed"],
+ "failed": eval_results["summary"]["failed"],
+ "total": eval_results["summary"]["total"],
+ "results": eval_results["results"],
+ }],
+ }
+ print(json.dumps(output, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/skill-creator/scripts/package_skill.py b/.agents/skills/skill-creator/scripts/package_skill.py
new file mode 100755
index 00000000..f48eac44
--- /dev/null
+++ b/.agents/skills/skill-creator/scripts/package_skill.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""
+Skill Packager - Creates a distributable .skill file of a skill folder
+
+Usage:
+ python utils/package_skill.py <path/to/skill-folder> [output-directory]
+
+Example:
+ python utils/package_skill.py skills/public/my-skill
+ python utils/package_skill.py skills/public/my-skill ./dist
+"""
+
+import fnmatch
+import sys
+import zipfile
+from pathlib import Path
+from scripts.quick_validate import validate_skill
+
+# Patterns to exclude when packaging skills.
+EXCLUDE_DIRS = {"__pycache__", "node_modules"}
+EXCLUDE_GLOBS = {"*.pyc"}
+EXCLUDE_FILES = {".DS_Store"}
+# Directories excluded only at the skill root (not when nested deeper).
+ROOT_EXCLUDE_DIRS = {"evals"}
+
+
+def should_exclude(rel_path: Path) -> bool:
+ """Check if a path should be excluded from packaging."""
+ parts = rel_path.parts
+ if any(part in EXCLUDE_DIRS for part in parts):
+ return True
+ # rel_path is relative to skill_path.parent, so parts[0] is the skill
+ # folder name and parts[1] (if present) is the first subdir.
+ if len(parts) > 1 and parts[1] in ROOT_EXCLUDE_DIRS:
+ return True
+ name = rel_path.name
+ if name in EXCLUDE_FILES:
+ return True
+ return any(fnmatch.fnmatch(name, pat) for pat in EXCLUDE_GLOBS)
+
+
+def package_skill(skill_path, output_dir=None):
+ """
+ Package a skill folder into a .skill file.
+
+ Args:
+ skill_path: Path to the skill folder
+ output_dir: Optional output directory for the .skill file (defaults to current directory)
+
+ Returns:
+ Path to the created .skill file, or None if error
+ """
+ skill_path = Path(skill_path).resolve()
+
+ # Validate skill folder exists
+ if not skill_path.exists():
+ print(f"❌ Error: Skill folder not found: {skill_path}")
+ return None
+
+ if not skill_path.is_dir():
+ print(f"❌ Error: Path is not a directory: {skill_path}")
+ return None
+
+ # Validate SKILL.md exists
+ skill_md = skill_path / "SKILL.md"
+ if not skill_md.exists():
+ print(f"❌ Error: SKILL.md not found in {skill_path}")
+ return None
+
+ # Run validation before packaging
+ print("🔍 Validating skill...")
+ valid, message = validate_skill(skill_path)
+ if not valid:
+ print(f"❌ Validation failed: {message}")
+ print(" Please fix the validation errors before packaging.")
+ return None
+ print(f"✅ {message}\n")
+
+ # Determine output location
+ skill_name = skill_path.name
+ if output_dir:
+ output_path = Path(output_dir).resolve()
+ output_path.mkdir(parents=True, exist_ok=True)
+ else:
+ output_path = Path.cwd()
+
+ skill_filename = output_path / f"{skill_name}.skill"
+
+ # Create the .skill file (zip format)
+ try:
+ with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
+ # Walk through the skill directory, excluding build artifacts
+ for file_path in skill_path.rglob('*'):
+ if not file_path.is_file():
+ continue
+ arcname = file_path.relative_to(skill_path.parent)
+ if should_exclude(arcname):
+ print(f" Skipped: {arcname}")
+ continue
+ zipf.write(file_path, arcname)
+ print(f" Added: {arcname}")
+
+ print(f"\n✅ Successfully packaged skill to: {skill_filename}")
+ return skill_filename
+
+ except Exception as e:
+ print(f"❌ Error creating .skill file: {e}")
+ return None
+
+
+def main():
+ if len(sys.argv) < 2:
+ print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]")
+ print("\nExample:")
+ print(" python utils/package_skill.py skills/public/my-skill")
+ print(" python utils/package_skill.py skills/public/my-skill ./dist")
+ sys.exit(1)
+
+ skill_path = sys.argv[1]
+ output_dir = sys.argv[2] if len(sys.argv) > 2 else None
+
+ print(f"📦 Packaging skill: {skill_path}")
+ if output_dir:
+ print(f" Output directory: {output_dir}")
+ print()
+
+ result = package_skill(skill_path, output_dir)
+
+ if result:
+ sys.exit(0)
+ else:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/skill-creator/scripts/quick_validate.py b/.agents/skills/skill-creator/scripts/quick_validate.py
new file mode 100755
index 00000000..ed8e1ddd
--- /dev/null
+++ b/.agents/skills/skill-creator/scripts/quick_validate.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python3
+"""
+Quick validation script for skills - minimal version
+"""
+
+import sys
+import os
+import re
+import yaml
+from pathlib import Path
+
+def validate_skill(skill_path):
+ """Basic validation of a skill"""
+ skill_path = Path(skill_path)
+
+ # Check SKILL.md exists
+ skill_md = skill_path / 'SKILL.md'
+ if not skill_md.exists():
+ return False, "SKILL.md not found"
+
+ # Read and validate frontmatter
+ content = skill_md.read_text()
+ if not content.startswith('---'):
+ return False, "No YAML frontmatter found"
+
+ # Extract frontmatter
+ match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
+ if not match:
+ return False, "Invalid frontmatter format"
+
+ frontmatter_text = match.group(1)
+
+ # Parse YAML frontmatter
+ try:
+ frontmatter = yaml.safe_load(frontmatter_text)
+ if not isinstance(frontmatter, dict):
+ return False, "Frontmatter must be a YAML dictionary"
+ except yaml.YAMLError as e:
+ return False, f"Invalid YAML in frontmatter: {e}"
+
+ # Define allowed properties
+ ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata', 'compatibility'}
+
+ # Check for unexpected properties (excluding nested keys under metadata)
+ unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES
+ if unexpected_keys:
+ return False, (
+ f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. "
+ f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}"
+ )
+
+ # Check required fields
+ if 'name' not in frontmatter:
+ return False, "Missing 'name' in frontmatter"
+ if 'description' not in frontmatter:
+ return False, "Missing 'description' in frontmatter"
+
+ # Extract name for validation
+ name = frontmatter.get('name', '')
+ if not isinstance(name, str):
+ return False, f"Name must be a string, got {type(name).__name__}"
+ name = name.strip()
+ if name:
+ # Check naming convention (kebab-case: lowercase with hyphens)
+ if not re.match(r'^[a-z0-9-]+$', name):
+ return False, f"Name '{name}' should be kebab-case (lowercase letters, digits, and hyphens only)"
+ if name.startswith('-') or name.endswith('-') or '--' in name:
+ return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens"
+ # Check name length (max 64 characters per spec)
+ if len(name) > 64:
+ return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters."
+
+ # Extract and validate description
+ description = frontmatter.get('description', '')
+ if not isinstance(description, str):
+ return False, f"Description must be a string, got {type(description).__name__}"
+ description = description.strip()
+ if description:
+ # Check for angle brackets
+ if '<' in description or '>' in description:
+ return False, "Description cannot contain angle brackets (< or >)"
+ # Check description length (max 1024 characters per spec)
+ if len(description) > 1024:
+ return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters."
+
+ # Validate compatibility field if present (optional)
+ compatibility = frontmatter.get('compatibility', '')
+ if compatibility:
+ if not isinstance(compatibility, str):
+ return False, f"Compatibility must be a string, got {type(compatibility).__name__}"
+ if len(compatibility) > 500:
+ return False, f"Compatibility is too long ({len(compatibility)} characters). Maximum is 500 characters."
+
+ return True, "Skill is valid!"
+
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ print("Usage: python quick_validate.py <skill_directory>")
+ sys.exit(1)
+
+ valid, message = validate_skill(sys.argv[1])
+ print(message)
+ sys.exit(0 if valid else 1)
\ No newline at end of file
diff --git a/.agents/skills/skill-creator/scripts/run_eval.py b/.agents/skills/skill-creator/scripts/run_eval.py
new file mode 100755
index 00000000..e58c70be
--- /dev/null
+++ b/.agents/skills/skill-creator/scripts/run_eval.py
@@ -0,0 +1,310 @@
+#!/usr/bin/env python3
+"""Run trigger evaluation for a skill description.
+
+Tests whether a skill's description causes Claude to trigger (read the skill)
+for a set of queries. Outputs results as JSON.
+"""
+
+import argparse
+import json
+import os
+import select
+import subprocess
+import sys
+import time
+import uuid
+from concurrent.futures import ProcessPoolExecutor, as_completed
+from pathlib import Path
+
+from scripts.utils import parse_skill_md
+
+
+def find_project_root() -> Path:
+ """Find the project root by walking up from cwd looking for .claude/.
+
+ Mimics how Claude Code discovers its project root, so the command file
+ we create ends up where claude -p will look for it.
+ """
+ current = Path.cwd()
+ for parent in [current, *current.parents]:
+ if (parent / ".claude").is_dir():
+ return parent
+ return current
+
+
+def run_single_query(
+ query: str,
+ skill_name: str,
+ skill_description: str,
+ timeout: int,
+ project_root: str,
+ model: str | None = None,
+) -> bool:
+ """Run a single query and return whether the skill was triggered.
+
+ Creates a command file in .claude/commands/ so it appears in Claude's
+ available_skills list, then runs `claude -p` with the raw query.
+ Uses --include-partial-messages to detect triggering early from
+ stream events (content_block_start) rather than waiting for the
+ full assistant message, which only arrives after tool execution.
+ """
+ unique_id = uuid.uuid4().hex[:8]
+ clean_name = f"{skill_name}-skill-{unique_id}"
+ project_commands_dir = Path(project_root) / ".claude" / "commands"
+ command_file = project_commands_dir / f"{clean_name}.md"
+
+ try:
+ project_commands_dir.mkdir(parents=True, exist_ok=True)
+ # Use YAML block scalar to avoid breaking on quotes in description
+ indented_desc = "\n ".join(skill_description.split("\n"))
+ command_content = (
+ f"---\n"
+ f"description: |\n"
+ f" {indented_desc}\n"
+ f"---\n\n"
+ f"# {skill_name}\n\n"
+ f"This skill handles: {skill_description}\n"
+ )
+ command_file.write_text(command_content)
+
+ cmd = [
+ "claude",
+ "-p", query,
+ "--output-format", "stream-json",
+ "--verbose",
+ "--include-partial-messages",
+ ]
+ if model:
+ cmd.extend(["--model", model])
+
+ # Remove CLAUDECODE env var to allow nesting claude -p inside a
+ # Claude Code session. The guard is for interactive terminal conflicts;
+ # programmatic subprocess usage is safe.
+ env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"}
+
+ process = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ cwd=project_root,
+ env=env,
+ )
+
+ triggered = False
+ start_time = time.time()
+ buffer = ""
+ # Track state for stream event detection
+ pending_tool_name = None
+ accumulated_json = ""
+
+ try:
+ while time.time() - start_time < timeout:
+ if process.poll() is not None:
+ remaining = process.stdout.read()
+ if remaining:
+ buffer += remaining.decode("utf-8", errors="replace")
+ break
+
+ ready, _, _ = select.select([process.stdout], [], [], 1.0)
+ if not ready:
+ continue
+
+ chunk = os.read(process.stdout.fileno(), 8192)
+ if not chunk:
+ break
+ buffer += chunk.decode("utf-8", errors="replace")
+
+ while "\n" in buffer:
+ line, buffer = buffer.split("\n", 1)
+ line = line.strip()
+ if not line:
+ continue
+
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+
+ # Early detection via stream events
+ if event.get("type") == "stream_event":
+ se = event.get("event", {})
+ se_type = se.get("type", "")
+
+ if se_type == "content_block_start":
+ cb = se.get("content_block", {})
+ if cb.get("type") == "tool_use":
+ tool_name = cb.get("name", "")
+ if tool_name in ("Skill", "Read"):
+ pending_tool_name = tool_name
+ accumulated_json = ""
+ else:
+ return False
+
+ elif se_type == "content_block_delta" and pending_tool_name:
+ delta = se.get("delta", {})
+ if delta.get("type") == "input_json_delta":
+ accumulated_json += delta.get("partial_json", "")
+ if clean_name in accumulated_json:
+ return True
+
+ elif se_type in ("content_block_stop", "message_stop"):
+ if pending_tool_name:
+ return clean_name in accumulated_json
+ if se_type == "message_stop":
+ return False
+
+ # Fallback: full assistant message
+ elif event.get("type") == "assistant":
+ message = event.get("message", {})
+ for content_item in message.get("content", []):
+ if content_item.get("type") != "tool_use":
+ continue
+ tool_name = content_item.get("name", "")
+ tool_input = content_item.get("input", {})
+ if tool_name == "Skill" and clean_name in tool_input.get("skill", ""):
+ triggered = True
+ elif tool_name == "Read" and clean_name in tool_input.get("file_path", ""):
+ triggered = True
+ return triggered
+
+ elif event.get("type") == "result":
+ return triggered
+ finally:
+ # Clean up process on any exit path (return, exception, timeout)
+ if process.poll() is None:
+ process.kill()
+ process.wait()
+
+ return triggered
+ finally:
+ if command_file.exists():
+ command_file.unlink()
+
+
+def run_eval(
+ eval_set: list[dict],
+ skill_name: str,
+ description: str,
+ num_workers: int,
+ timeout: int,
+ project_root: Path,
+ runs_per_query: int = 1,
+ trigger_threshold: float = 0.5,
+ model: str | None = None,
+) -> dict:
+ """Run the full eval set and return results."""
+ results = []
+
+ with ProcessPoolExecutor(max_workers=num_workers) as executor:
+ future_to_info = {}
+ for item in eval_set:
+ for run_idx in range(runs_per_query):
+ future = executor.submit(
+ run_single_query,
+ item["query"],
+ skill_name,
+ description,
+ timeout,
+ str(project_root),
+ model,
+ )
+ future_to_info[future] = (item, run_idx)
+
+ query_triggers: dict[str, list[bool]] = {}
+ query_items: dict[str, dict] = {}
+ for future in as_completed(future_to_info):
+ item, _ = future_to_info[future]
+ query = item["query"]
+ query_items[query] = item
+ if query not in query_triggers:
+ query_triggers[query] = []
+ try:
+ query_triggers[query].append(future.result())
+ except Exception as e:
+ print(f"Warning: query failed: {e}", file=sys.stderr)
+ query_triggers[query].append(False)
+
+ for query, triggers in query_triggers.items():
+ item = query_items[query]
+ trigger_rate = sum(triggers) / len(triggers)
+ should_trigger = item["should_trigger"]
+ if should_trigger:
+ did_pass = trigger_rate >= trigger_threshold
+ else:
+ did_pass = trigger_rate < trigger_threshold
+ results.append({
+ "query": query,
+ "should_trigger": should_trigger,
+ "trigger_rate": trigger_rate,
+ "triggers": sum(triggers),
+ "runs": len(triggers),
+ "pass": did_pass,
+ })
+
+ passed = sum(1 for r in results if r["pass"])
+ total = len(results)
+
+ return {
+ "skill_name": skill_name,
+ "description": description,
+ "results": results,
+ "summary": {
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ },
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Run trigger evaluation for a skill description")
+ parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file")
+ parser.add_argument("--skill-path", required=True, help="Path to skill directory")
+ parser.add_argument("--description", default=None, help="Override description to test")
+ parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers")
+ parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds")
+ parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query")
+ parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold")
+ parser.add_argument("--model", default=None, help="Model to use for claude -p (default: user's configured model)")
+ parser.add_argument("--verbose", action="store_true", help="Print progress to stderr")
+ args = parser.parse_args()
+
+ eval_set = json.loads(Path(args.eval_set).read_text())
+ skill_path = Path(args.skill_path)
+
+ if not (skill_path / "SKILL.md").exists():
+ print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
+ sys.exit(1)
+
+ name, original_description, content = parse_skill_md(skill_path)
+ description = args.description or original_description
+ project_root = find_project_root()
+
+ if args.verbose:
+ print(f"Evaluating: {description}", file=sys.stderr)
+
+ output = run_eval(
+ eval_set=eval_set,
+ skill_name=name,
+ description=description,
+ num_workers=args.num_workers,
+ timeout=args.timeout,
+ project_root=project_root,
+ runs_per_query=args.runs_per_query,
+ trigger_threshold=args.trigger_threshold,
+ model=args.model,
+ )
+
+ if args.verbose:
+ summary = output["summary"]
+ print(f"Results: {summary['passed']}/{summary['total']} passed", file=sys.stderr)
+ for r in output["results"]:
+ status = "PASS" if r["pass"] else "FAIL"
+ rate_str = f"{r['triggers']}/{r['runs']}"
+ print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:70]}", file=sys.stderr)
+
+ print(json.dumps(output, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/skill-creator/scripts/run_loop.py b/.agents/skills/skill-creator/scripts/run_loop.py
new file mode 100755
index 00000000..30a263d6
--- /dev/null
+++ b/.agents/skills/skill-creator/scripts/run_loop.py
@@ -0,0 +1,328 @@
+#!/usr/bin/env python3
+"""Run the eval + improve loop until all pass or max iterations reached.
+
+Combines run_eval.py and improve_description.py in a loop, tracking history
+and returning the best description found. Supports train/test split to prevent
+overfitting.
+"""
+
+import argparse
+import json
+import random
+import sys
+import tempfile
+import time
+import webbrowser
+from pathlib import Path
+
+from scripts.generate_report import generate_html
+from scripts.improve_description import improve_description
+from scripts.run_eval import find_project_root, run_eval
+from scripts.utils import parse_skill_md
+
+
+def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]:
+ """Split eval set into train and test sets, stratified by should_trigger."""
+ random.seed(seed)
+
+ # Separate by should_trigger
+ trigger = [e for e in eval_set if e["should_trigger"]]
+ no_trigger = [e for e in eval_set if not e["should_trigger"]]
+
+ # Shuffle each group
+ random.shuffle(trigger)
+ random.shuffle(no_trigger)
+
+ # Calculate split points
+ n_trigger_test = max(1, int(len(trigger) * holdout))
+ n_no_trigger_test = max(1, int(len(no_trigger) * holdout))
+
+ # Split
+ test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test]
+ train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:]
+
+ return train_set, test_set
+
+
+def run_loop(
+ eval_set: list[dict],
+ skill_path: Path,
+ description_override: str | None,
+ num_workers: int,
+ timeout: int,
+ max_iterations: int,
+ runs_per_query: int,
+ trigger_threshold: float,
+ holdout: float,
+ model: str,
+ verbose: bool,
+ live_report_path: Path | None = None,
+ log_dir: Path | None = None,
+) -> dict:
+ """Run the eval + improvement loop."""
+ project_root = find_project_root()
+ name, original_description, content = parse_skill_md(skill_path)
+ current_description = description_override or original_description
+
+ # Split into train/test if holdout > 0
+ if holdout > 0:
+ train_set, test_set = split_eval_set(eval_set, holdout)
+ if verbose:
+ print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr)
+ else:
+ train_set = eval_set
+ test_set = []
+
+ history = []
+ exit_reason = "unknown"
+
+ for iteration in range(1, max_iterations + 1):
+ if verbose:
+ print(f"\n{'='*60}", file=sys.stderr)
+ print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr)
+ print(f"Description: {current_description}", file=sys.stderr)
+ print(f"{'='*60}", file=sys.stderr)
+
+ # Evaluate train + test together in one batch for parallelism
+ all_queries = train_set + test_set
+ t0 = time.time()
+ all_results = run_eval(
+ eval_set=all_queries,
+ skill_name=name,
+ description=current_description,
+ num_workers=num_workers,
+ timeout=timeout,
+ project_root=project_root,
+ runs_per_query=runs_per_query,
+ trigger_threshold=trigger_threshold,
+ model=model,
+ )
+ eval_elapsed = time.time() - t0
+
+ # Split results back into train/test by matching queries
+ train_queries_set = {q["query"] for q in train_set}
+ train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set]
+ test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set]
+
+ train_passed = sum(1 for r in train_result_list if r["pass"])
+ train_total = len(train_result_list)
+ train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total}
+ train_results = {"results": train_result_list, "summary": train_summary}
+
+ if test_set:
+ test_passed = sum(1 for r in test_result_list if r["pass"])
+ test_total = len(test_result_list)
+ test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total}
+ test_results = {"results": test_result_list, "summary": test_summary}
+ else:
+ test_results = None
+ test_summary = None
+
+ history.append({
+ "iteration": iteration,
+ "description": current_description,
+ "train_passed": train_summary["passed"],
+ "train_failed": train_summary["failed"],
+ "train_total": train_summary["total"],
+ "train_results": train_results["results"],
+ "test_passed": test_summary["passed"] if test_summary else None,
+ "test_failed": test_summary["failed"] if test_summary else None,
+ "test_total": test_summary["total"] if test_summary else None,
+ "test_results": test_results["results"] if test_results else None,
+ # For backward compat with report generator
+ "passed": train_summary["passed"],
+ "failed": train_summary["failed"],
+ "total": train_summary["total"],
+ "results": train_results["results"],
+ })
+
+ # Write live report if path provided
+ if live_report_path:
+ partial_output = {
+ "original_description": original_description,
+ "best_description": current_description,
+ "best_score": "in progress",
+ "iterations_run": len(history),
+ "holdout": holdout,
+ "train_size": len(train_set),
+ "test_size": len(test_set),
+ "history": history,
+ }
+ live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name))
+
+ if verbose:
+ def print_eval_stats(label, results, elapsed):
+ pos = [r for r in results if r["should_trigger"]]
+ neg = [r for r in results if not r["should_trigger"]]
+ tp = sum(r["triggers"] for r in pos)
+ pos_runs = sum(r["runs"] for r in pos)
+ fn = pos_runs - tp
+ fp = sum(r["triggers"] for r in neg)
+ neg_runs = sum(r["runs"] for r in neg)
+ tn = neg_runs - fp
+ total = tp + tn + fp + fn
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0
+ accuracy = (tp + tn) / total if total > 0 else 0.0
+ print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr)
+ for r in results:
+ status = "PASS" if r["pass"] else "FAIL"
+ rate_str = f"{r['triggers']}/{r['runs']}"
+ print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr)
+
+ print_eval_stats("Train", train_results["results"], eval_elapsed)
+ if test_summary:
+ print_eval_stats("Test ", test_results["results"], 0)
+
+ if train_summary["failed"] == 0:
+ exit_reason = f"all_passed (iteration {iteration})"
+ if verbose:
+ print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr)
+ break
+
+ if iteration == max_iterations:
+ exit_reason = f"max_iterations ({max_iterations})"
+ if verbose:
+ print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr)
+ break
+
+ # Improve the description based on train results
+ if verbose:
+ print(f"\nImproving description...", file=sys.stderr)
+
+ t0 = time.time()
+ # Strip test scores from history so improvement model can't see them
+ blinded_history = [
+ {k: v for k, v in h.items() if not k.startswith("test_")}
+ for h in history
+ ]
+ new_description = improve_description(
+ skill_name=name,
+ skill_content=content,
+ current_description=current_description,
+ eval_results=train_results,
+ history=blinded_history,
+ model=model,
+ log_dir=log_dir,
+ iteration=iteration,
+ )
+ improve_elapsed = time.time() - t0
+
+ if verbose:
+ print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr)
+
+ current_description = new_description
+
+ # Find the best iteration by TEST score (or train if no test set)
+ if test_set:
+ best = max(history, key=lambda h: h["test_passed"] or 0)
+ best_score = f"{best['test_passed']}/{best['test_total']}"
+ else:
+ best = max(history, key=lambda h: h["train_passed"])
+ best_score = f"{best['train_passed']}/{best['train_total']}"
+
+ if verbose:
+ print(f"\nExit reason: {exit_reason}", file=sys.stderr)
+ print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr)
+
+ return {
+ "exit_reason": exit_reason,
+ "original_description": original_description,
+ "best_description": best["description"],
+ "best_score": best_score,
+ "best_train_score": f"{best['train_passed']}/{best['train_total']}",
+ "best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None,
+ "final_description": current_description,
+ "iterations_run": len(history),
+ "holdout": holdout,
+ "train_size": len(train_set),
+ "test_size": len(test_set),
+ "history": history,
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Run eval + improve loop")
+ parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file")
+ parser.add_argument("--skill-path", required=True, help="Path to skill directory")
+ parser.add_argument("--description", default=None, help="Override starting description")
+ parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers")
+ parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds")
+ parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations")
+ parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query")
+ parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold")
+ parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)")
+ parser.add_argument("--model", required=True, help="Model for improvement")
+ parser.add_argument("--verbose", action="store_true", help="Print progress to stderr")
+ parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)")
+ parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here")
+ args = parser.parse_args()
+
+ eval_set = json.loads(Path(args.eval_set).read_text())
+ skill_path = Path(args.skill_path)
+
+ if not (skill_path / "SKILL.md").exists():
+ print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
+ sys.exit(1)
+
+ name, _, _ = parse_skill_md(skill_path)
+
+ # Set up live report path
+ if args.report != "none":
+ if args.report == "auto":
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html"
+ else:
+ live_report_path = Path(args.report)
+ # Open the report immediately so the user can watch
+ live_report_path.write_text("<html><body><h1>Starting optimization loop...</h1><meta http-equiv='refresh' content='5'></body></html>")
+ webbrowser.open(str(live_report_path))
+ else:
+ live_report_path = None
+
+ # Determine output directory (create before run_loop so logs can be written)
+ if args.results_dir:
+ timestamp = time.strftime("%Y-%m-%d_%H%M%S")
+ results_dir = Path(args.results_dir) / timestamp
+ results_dir.mkdir(parents=True, exist_ok=True)
+ else:
+ results_dir = None
+
+ log_dir = results_dir / "logs" if results_dir else None
+
+ output = run_loop(
+ eval_set=eval_set,
+ skill_path=skill_path,
+ description_override=args.description,
+ num_workers=args.num_workers,
+ timeout=args.timeout,
+ max_iterations=args.max_iterations,
+ runs_per_query=args.runs_per_query,
+ trigger_threshold=args.trigger_threshold,
+ holdout=args.holdout,
+ model=args.model,
+ verbose=args.verbose,
+ live_report_path=live_report_path,
+ log_dir=log_dir,
+ )
+
+ # Save JSON output
+ json_output = json.dumps(output, indent=2)
+ print(json_output)
+ if results_dir:
+ (results_dir / "results.json").write_text(json_output)
+
+ # Write final HTML report (without auto-refresh)
+ if live_report_path:
+ live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name))
+ print(f"\nReport: {live_report_path}", file=sys.stderr)
+
+ if results_dir and live_report_path:
+ (results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name))
+
+ if results_dir:
+ print(f"Results saved to: {results_dir}", file=sys.stderr)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/skill-creator/scripts/utils.py b/.agents/skills/skill-creator/scripts/utils.py
new file mode 100644
index 00000000..51b6a07d
--- /dev/null
+++ b/.agents/skills/skill-creator/scripts/utils.py
@@ -0,0 +1,47 @@
+"""Shared utilities for skill-creator scripts."""
+
+from pathlib import Path
+
+
+
+def parse_skill_md(skill_path: Path) -> tuple[str, str, str]:
+ """Parse a SKILL.md file, returning (name, description, full_content)."""
+ content = (skill_path / "SKILL.md").read_text()
+ lines = content.split("\n")
+
+ if lines[0].strip() != "---":
+ raise ValueError("SKILL.md missing frontmatter (no opening ---)")
+
+ end_idx = None
+ for i, line in enumerate(lines[1:], start=1):
+ if line.strip() == "---":
+ end_idx = i
+ break
+
+ if end_idx is None:
+ raise ValueError("SKILL.md missing frontmatter (no closing ---)")
+
+ name = ""
+ description = ""
+ frontmatter_lines = lines[1:end_idx]
+ i = 0
+ while i < len(frontmatter_lines):
+ line = frontmatter_lines[i]
+ if line.startswith("name:"):
+ name = line[len("name:"):].strip().strip('"').strip("'")
+ elif line.startswith("description:"):
+ value = line[len("description:"):].strip()
+ # Handle YAML multiline indicators (>, |, >-, |-)
+ if value in (">", "|", ">-", "|-"):
+ continuation_lines: list[str] = []
+ i += 1
+ while i < len(frontmatter_lines) and (frontmatter_lines[i].startswith(" ") or frontmatter_lines[i].startswith("\t")):
+ continuation_lines.append(frontmatter_lines[i].strip())
+ i += 1
+ description = " ".join(continuation_lines)
+ continue
+ else:
+ description = value.strip('"').strip("'")
+ i += 1
+
+ return name, description, content
diff --git a/.agents/skills/turborepo/SKILL.md b/.agents/skills/turborepo/SKILL.md
new file mode 100644
index 00000000..1568ddc6
--- /dev/null
+++ b/.agents/skills/turborepo/SKILL.md
@@ -0,0 +1,951 @@
+---
+name: turborepo
+description: |
+ Turborepo monorepo build system guidance. Triggers on: turbo.json, task pipelines,
+ dependsOn, caching, remote cache, the "turbo" CLI, --filter, --affected, CI optimization, environment
+ variables, internal packages, monorepo structure/best practices, and boundaries.
+
+ Use when user: configures tasks/workflows/pipelines, creates packages, sets up
+ monorepo, shares code between apps, runs changed/affected packages, debugs cache,
+ or has apps/packages directories.
+metadata:
+ version: 2.10.8-canary.4
+---
+
+# Turborepo Skill
+
+Build system for JavaScript/TypeScript monorepos. Turborepo caches task outputs and runs tasks in parallel based on dependency graph.
+
+## IMPORTANT: Package Tasks, Not Root Tasks
+
+**Prefer package tasks over Root Tasks.**
+
+When creating tasks/scripts/pipelines, you MUST default to package tasks:
+
+1. Add the script to each relevant package's `package.json`
+2. Register the task in root `turbo.json`
+3. Root `package.json` only delegates via `turbo run <task>`
+
+**DO NOT** put task logic in root `package.json` when it can live in packages. This defeats Turborepo's parallelization.
+
+```json
+// DO THIS: Scripts in each package
+// apps/web/package.json
+{ "scripts": { "build": "next build", "lint": "eslint .", "test": "vitest" } }
+
+// apps/api/package.json
+{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
+
+// packages/ui/package.json
+{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
+```
+
+```json
+// turbo.json - register tasks
+{
+ "tasks": {
+ "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] },
+ "lint": {},
+ "test": { "dependsOn": ["build"] }
+ }
+}
+```
+
+```json
+// Root package.json - ONLY delegates, no task logic
+{
+ "scripts": {
+ "build": "turbo run build",
+ "lint": "turbo run lint",
+ "test": "turbo run test"
+ }
+}
+```
+
+```json
+// DO NOT DO THIS - defeats parallelization
+// Root package.json
+{
+ "scripts": {
+ "build": "cd apps/web && next build && cd ../api && tsc",
+ "lint": "eslint apps/ packages/",
+ "test": "vitest"
+ }
+}
+```
+
+Root Tasks (`//#taskname`) are ONLY for tasks that truly cannot exist in packages, such as Vitest Projects' `//#test`, repo-wide release scripts, or tooling that does not invoke `turbo` itself.
+
+## Secondary Rule: `turbo run` vs `turbo`
+
+**Always use `turbo run` when the command is written into code:**
+
+```json
+// package.json - ALWAYS "turbo run"
+{
+ "scripts": {
+ "build": "turbo run build"
+ }
+}
+```
+
+```yaml
+# CI workflows - ALWAYS "turbo run"
+- run: turbo run build --affected
+```
+
+**The shorthand `turbo <tasks>` is ONLY for one-off terminal commands** typed directly by humans or agents. Never write `turbo build` into package.json, CI, or scripts.
+
+## Quick Decision Trees
+
+### "I need to configure a task"
+
+```
+Configure a task?
+├─ Define task dependencies → references/configuration/tasks.md
+├─ Lint/check-types (parallel + caching) → Use Transit Nodes pattern (see below)
+├─ Specify build outputs → references/configuration/tasks.md#outputs
+├─ Handle environment variables → references/environment/RULE.md
+├─ Set up dev/watch tasks → references/configuration/tasks.md#persistent
+├─ Package-specific config → references/configuration/RULE.md#package-configurations
+└─ Global settings (cacheDir, daemon) → references/configuration/global-options.md
+```
+
+### "My cache isn't working"
+
+```
+Cache problems?
+├─ Tasks run but outputs not restored → Missing `outputs` key
+├─ Cache misses unexpectedly → references/caching/gotchas.md
+├─ Need to debug hash inputs → Use --summarize or --dry
+├─ Want to skip cache entirely → Use --force or cache: false
+├─ Remote cache not working → references/caching/remote-cache.md
+└─ Environment causing misses → references/environment/gotchas.md
+```
+
+### "I want to run only changed packages"
+
+```
+Run only what changed?
+├─ Changed packages + dependents (RECOMMENDED) → turbo run build --affected
+├─ Custom base branch → --affected --affected-base=origin/develop
+├─ Manual git comparison → --filter=...[origin/main]
+└─ See all filter options → references/filtering/RULE.md
+```
+
+**`--affected` is the primary way to run only changed packages.** It automatically compares against the default branch and includes dependents.
+
+### "I want to filter packages"
+
+```
+Filter packages?
+├─ Only changed packages → --affected (see above)
+├─ By package name → --filter=web
+├─ By directory → --filter=./apps/*
+├─ Package + dependencies → --filter=web...
+├─ Package + dependents → --filter=...web
+└─ Complex combinations → references/filtering/patterns.md
+```
+
+### "Environment variables aren't working"
+
+```
+Environment issues?
+├─ Vars not available at runtime → Strict mode filtering (default)
+├─ Cache hits with wrong env → Var not in `env` key
+├─ .env changes not causing rebuilds → .env not in `inputs`
+├─ CI variables missing → references/environment/gotchas.md
+└─ Framework vars (NEXT_PUBLIC_*) → Auto-included via inference
+```
+
+### "I need to set up CI"
+
+```
+CI setup?
+├─ GitHub Actions → references/ci/github-actions.md
+├─ Vercel deployment → references/ci/vercel.md
+├─ Remote cache in CI → references/caching/remote-cache.md
+├─ Only build changed packages → --affected flag
+├─ Skip unnecessary builds → turbo-ignore (references/cli/commands.md)
+└─ Skip container setup when no changes → turbo-ignore
+```
+
+### "I want to watch for changes during development"
+
+```
+Watch mode?
+├─ Re-run tasks on change → turbo watch (references/watch/RULE.md)
+├─ Dev servers with dependencies → Use `with` key (references/configuration/tasks.md#with)
+├─ Restart dev server on dep change → Use `interruptible: true`
+└─ Persistent dev tasks → Use `persistent: true`
+```
+
+### "I need to create/structure a package"
+
+```
+Package creation/structure?
+├─ Create an internal package → references/best-practices/packages.md
+├─ Repository structure → references/best-practices/structure.md
+├─ Dependency management → references/best-practices/dependencies.md
+├─ Best practices overview → references/best-practices/RULE.md
+├─ JIT vs Compiled packages → references/best-practices/packages.md#compilation-strategies
+└─ Sharing code between apps → references/best-practices/RULE.md#package-types
+```
+
+### "How should I structure my monorepo?"
+
+```
+Monorepo structure?
+├─ Standard layout (apps/, packages/) → references/best-practices/RULE.md
+├─ Package types (apps vs libraries) → references/best-practices/RULE.md#package-types
+├─ Creating internal packages → references/best-practices/packages.md
+├─ TypeScript configuration → references/best-practices/structure.md#typescript-configuration
+├─ ESLint configuration → references/best-practices/structure.md#eslint-configuration
+├─ Dependency management → references/best-practices/dependencies.md
+└─ Enforce package boundaries → references/boundaries/RULE.md
+```
+
+### "I want to enforce architectural boundaries"
+
+```
+Enforce boundaries?
+├─ Check for violations → turbo boundaries
+├─ Tag packages → references/boundaries/RULE.md#tags
+├─ Restrict which packages can import others → references/boundaries/RULE.md#rule-types
+└─ Prevent cross-package file imports → references/boundaries/RULE.md
+```
+
+## Critical Anti-Patterns
+
+### Using `turbo` Shorthand in Code
+
+**`turbo run` is recommended in package.json scripts and CI pipelines.** The shorthand `turbo <task>` is intended for interactive terminal use.
+
+```json
+// WRONG - using shorthand in package.json
+{
+ "scripts": {
+ "build": "turbo build",
+ "dev": "turbo dev"
+ }
+}
+
+// CORRECT
+{
+ "scripts": {
+ "build": "turbo run build",
+ "dev": "turbo run dev"
+ }
+}
+```
+
+```yaml
+# WRONG - using shorthand in CI
+- run: turbo build --affected
+
+# CORRECT
+- run: turbo run build --affected
+```
+
+### Root Scripts Bypassing Turbo
+
+Root `package.json` scripts MUST delegate to `turbo run`, not run tasks directly.
+
+```json
+// WRONG - bypasses turbo entirely
+{
+ "scripts": {
+ "build": "bun build",
+ "dev": "bun dev"
+ }
+}
+
+// CORRECT - delegates to turbo
+{
+ "scripts": {
+ "build": "turbo run build",
+ "dev": "turbo run dev"
+ }
+}
+```
+
+### Using `&&` to Chain Turbo Tasks
+
+Don't chain turbo tasks with `&&`. Let turbo orchestrate.
+
+```json
+// WRONG - turbo task not using turbo run
+{
+ "scripts": {
+ "changeset:publish": "bun build && changeset publish"
+ }
+}
+
+// CORRECT
+{
+ "scripts": {
+ "changeset:publish": "turbo run build && changeset publish"
+ }
+}
+```
+
+### `prebuild` Scripts That Manually Build Dependencies
+
+Scripts like `prebuild` that manually build other packages bypass Turborepo's dependency graph.
+
+```json
+// WRONG - manually building dependencies
+{
+ "scripts": {
+ "prebuild": "cd ../../packages/types && bun run build && cd ../utils && bun run build",
+ "build": "next build"
+ }
+}
+```
+
+**However, the fix depends on whether workspace dependencies are declared:**
+
+1. **If dependencies ARE declared** (e.g., `"@repo/types": "workspace:*"` in package.json), remove the `prebuild` script. Turbo's `dependsOn: ["^build"]` handles this automatically.
+
+2. **If dependencies are NOT declared**, the `prebuild` exists because `^build` won't trigger without a dependency relationship. The fix is to:
+ - Add the dependency to package.json: `"@repo/types": "workspace:*"`
+ - Then remove the `prebuild` script
+
+```json
+// CORRECT - declare dependency, let turbo handle build order
+// package.json
+{
+ "dependencies": {
+ "@repo/types": "workspace:*",
+ "@repo/utils": "workspace:*"
+ },
+ "scripts": {
+ "build": "next build"
+ }
+}
+
+// turbo.json
+{
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"]
+ }
+ }
+}
+```
+
+**Key insight:** `^build` only runs build in packages listed as dependencies. No dependency declaration = no automatic build ordering.
+
+### Overly Broad `globalDependencies`
+
+`globalDependencies` affects ALL tasks in ALL packages via the **global hash** — tasks cannot opt out of specific files, even with negation globs in `inputs`. Be specific.
+
+```json
+// WRONG - heavy hammer, affects all hashes
+{
+ "globalDependencies": ["**/.env.*local"]
+}
+
+// BETTER - move to task-level inputs
+{
+ "globalDependencies": [".env"],
+ "tasks": {
+ "build": {
+ "inputs": ["$TURBO_DEFAULT$", ".env*"],
+ "outputs": ["dist/**"]
+ }
+ }
+}
+```
+
+With `futureFlags.globalConfiguration`, this problem is reduced because `global.inputs` files are folded into each task's inputs (not the global hash). Tasks can exclude specific files:
+
+```json
+// BEST - global.inputs with per-task exclusion
+{
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "inputs": [".env"]
+ },
+ "tasks": {
+ "build": { "outputs": ["dist/**"] },
+ "lint": {
+ "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/.env"]
+ }
+ }
+}
+```
+
+### Repetitive Task Configuration
+
+Look for repeated configuration across tasks that can be collapsed. Turborepo supports shared configuration patterns.
+
+```json
+// WRONG - repetitive env and inputs across tasks
+{
+ "tasks": {
+ "build": {
+ "env": ["API_URL", "DATABASE_URL"],
+ "inputs": ["$TURBO_DEFAULT$", ".env*"]
+ },
+ "test": {
+ "env": ["API_URL", "DATABASE_URL"],
+ "inputs": ["$TURBO_DEFAULT$", ".env*"]
+ },
+ "dev": {
+ "env": ["API_URL", "DATABASE_URL"],
+ "inputs": ["$TURBO_DEFAULT$", ".env*"],
+ "cache": false,
+ "persistent": true
+ }
+ }
+}
+
+// BETTER - use globalEnv and globalDependencies for shared config
+{
+ "globalEnv": ["API_URL", "DATABASE_URL"],
+ "globalDependencies": [".env*"],
+ "tasks": {
+ "build": {},
+ "test": {},
+ "dev": {
+ "cache": false,
+ "persistent": true
+ }
+ }
+}
+```
+
+**When to use global vs task-level:**
+
+- `globalEnv` / `globalDependencies` - affects ALL tasks, use for truly shared config
+- Task-level `env` / `inputs` - use when only specific tasks need it
+
+### NOT an Anti-Pattern: Large `env` Arrays
+
+A large `env` array (even 50+ variables) is **not** a problem. It usually means the user was thorough about declaring their build's environment dependencies. Do not flag this as an issue.
+
+### Using `--parallel` Flag
+
+The `--parallel` flag bypasses Turborepo's dependency graph. If tasks need parallel execution, configure `dependsOn` correctly instead.
+
+```bash
+# WRONG - bypasses dependency graph
+turbo run lint --parallel
+
+# CORRECT - configure tasks to allow parallel execution
+# In turbo.json, set dependsOn appropriately (or use transit nodes)
+turbo run lint
+```
+
+### Package-Specific Task Overrides in Root turbo.json
+
+When multiple packages need different task configurations, use **Package Configurations** (`turbo.json` in each package) instead of cluttering root `turbo.json` with `package#task` overrides.
+
+```json
+// WRONG - root turbo.json with many package-specific overrides
+{
+ "tasks": {
+ "test": { "dependsOn": ["build"] },
+ "@repo/web#test": { "outputs": ["coverage/**"] },
+ "@repo/api#test": { "outputs": ["coverage/**"] },
+ "@repo/utils#test": { "outputs": [] },
+ "@repo/cli#test": { "outputs": [] },
+ "@repo/core#test": { "outputs": [] }
+ }
+}
+
+// CORRECT - use Package Configurations
+// Root turbo.json - base config only
+{
+ "tasks": {
+ "test": { "dependsOn": ["build"] }
+ }
+}
+
+// packages/web/turbo.json - package-specific override
+{
+ "extends": ["//"],
+ "tasks": {
+ "test": { "outputs": ["coverage/**"] }
+ }
+}
+
+// packages/api/turbo.json
+{
+ "extends": ["//"],
+ "tasks": {
+ "test": { "outputs": ["coverage/**"] }
+ }
+}
+```
+
+**Benefits of Package Configurations:**
+
+- Keeps configuration close to the code it affects
+- Root turbo.json stays clean and focused on base patterns
+- Easier to understand what's special about each package
+- Works with `$TURBO_EXTENDS$` to inherit + extend arrays
+
+**When to use `package#task` in root:**
+
+- Single package needs a unique dependency (e.g., `"deploy": { "dependsOn": ["web#build"] }`)
+- Temporary override while migrating
+
+See `references/configuration/RULE.md#package-configurations` for full details.
+
+### Using `../` to Traverse Out of Package in `inputs`
+
+Don't use relative paths like `../` to reference files outside the package. Use `$TURBO_ROOT$` instead.
+
+```json
+// WRONG - traversing out of package
+{
+ "tasks": {
+ "build": {
+ "inputs": ["$TURBO_DEFAULT$", "../shared-config.json"]
+ }
+ }
+}
+
+// CORRECT - use $TURBO_ROOT$ for repo root
+{
+ "tasks": {
+ "build": {
+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/shared-config.json"]
+ }
+ }
+}
+```
+
+### Missing `outputs` for File-Producing Tasks
+
+**Before flagging missing `outputs`, check what the task actually produces:**
+
+1. Read the package's script (e.g., `"build": "tsc"`, `"test": "vitest"`)
+2. Determine if it writes files to disk or only outputs to stdout
+3. Only flag if the task produces files that should be cached
+
+```json
+// WRONG: build produces files but they're not cached
+{
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"]
+ }
+ }
+}
+
+// CORRECT: build outputs are cached
+{
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**"]
+ }
+ }
+}
+```
+
+Common outputs by framework:
+
+- Next.js: `[".next/**", "!.next/cache/**", "!.next/dev/**"]`
+- Vite/Rollup: `["dist/**"]`
+- tsc: `["dist/**"]` or custom `outDir`
+
+**TypeScript `--noEmit` can still produce cache files:**
+
+When `incremental: true` in tsconfig.json, `tsc --noEmit` writes `.tsbuildinfo` files even without emitting JS. Check the tsconfig before assuming no outputs:
+
+```json
+// If tsconfig has incremental: true, tsc --noEmit produces cache files
+{
+ "tasks": {
+ "typecheck": {
+ "outputs": ["node_modules/.cache/tsbuildinfo.json"] // or wherever tsBuildInfoFile points
+ }
+ }
+}
+```
+
+To determine correct outputs for TypeScript tasks:
+
+1. Check if `incremental` or `composite` is enabled in tsconfig
+2. Check `tsBuildInfoFile` for custom cache location (default: alongside `outDir` or in project root)
+3. If no incremental mode, `tsc --noEmit` produces no files
+
+### `^build` vs `build` Confusion
+
+```json
+{
+ "tasks": {
+ // ^build = run build in DEPENDENCIES first (other packages this one imports)
+ "build": {
+ "dependsOn": ["^build"]
+ },
+ // build (no ^) = run build in SAME PACKAGE first
+ "test": {
+ "dependsOn": ["build"]
+ },
+ // pkg#task = specific package's task
+ "deploy": {
+ "dependsOn": ["web#build"]
+ }
+ }
+}
+```
+
+### Environment Variables Not Hashed
+
+```json
+// WRONG: API_URL changes won't cause rebuilds
+{
+ "tasks": {
+ "build": {
+ "outputs": ["dist/**"]
+ }
+ }
+}
+
+// CORRECT: API_URL changes invalidate cache
+{
+ "tasks": {
+ "build": {
+ "outputs": ["dist/**"],
+ "env": ["API_URL", "API_KEY"]
+ }
+ }
+}
+```
+
+### `.env` Files Not in Inputs
+
+Turbo does NOT load `.env` files - your framework does. But Turbo needs to know about changes:
+
+```json
+// WRONG: .env changes don't invalidate cache
+{
+ "tasks": {
+ "build": {
+ "env": ["API_URL"]
+ }
+ }
+}
+
+// CORRECT: .env file changes invalidate cache
+{
+ "tasks": {
+ "build": {
+ "env": ["API_URL"],
+ "inputs": ["$TURBO_DEFAULT$", ".env", ".env.*"]
+ }
+ }
+}
+```
+
+### Root `.env` File in Monorepo
+
+A `.env` file at the repo root is an anti-pattern — even for small monorepos or starter templates. It creates implicit coupling between packages and makes it unclear which packages depend on which variables.
+
+```
+// WRONG - root .env affects all packages implicitly
+my-monorepo/
+├── .env # Which packages use this?
+├── apps/
+│ ├── web/
+│ └── api/
+└── packages/
+
+// CORRECT - .env files in packages that need them
+my-monorepo/
+├── apps/
+│ ├── web/
+│ │ └── .env # Clear: web needs DATABASE_URL
+│ └── api/
+│ └── .env # Clear: api needs API_KEY
+└── packages/
+```
+
+**Problems with root `.env`:**
+
+- Unclear which packages consume which variables
+- All packages get all variables (even ones they don't need)
+- Cache invalidation is coarse-grained (root .env change invalidates everything)
+- Security risk: packages may accidentally access sensitive vars meant for others
+- Bad habits start small — starter templates should model correct patterns
+
+**If you must share variables**, use `globalEnv` to be explicit about what's shared, and document why.
+
+### Strict Mode Filtering CI Variables
+
+By default, Turborepo filters environment variables to only those in `env`/`globalEnv`. CI variables may be missing:
+
+```json
+// If CI scripts need GITHUB_TOKEN but it's not in env:
+{
+ "globalPassThroughEnv": ["GITHUB_TOKEN", "CI"],
+ "tasks": { ... }
+}
+```
+
+Or use `--env-mode=loose` (not recommended for production).
+
+### Shared Code in Apps (Should Be a Package)
+
+```
+// WRONG: Shared code inside an app
+apps/
+ web/
+ shared/ # This breaks monorepo principles!
+ utils.ts
+
+// CORRECT: Extract to a package
+packages/
+ utils/
+ src/utils.ts
+```
+
+### Accessing Files Across Package Boundaries
+
+```typescript
+// WRONG: Reaching into another package's internals
+import { Button } from "../../packages/ui/src/button";
+
+// CORRECT: Install and import properly
+import { Button } from "@repo/ui/button";
+```
+
+### Too Many Root Dependencies
+
+```json
+// WRONG: App dependencies in root
+{
+ "dependencies": {
+ "react": "^18",
+ "next": "^14"
+ }
+}
+
+// CORRECT: Only repo tools in root
+{
+ "devDependencies": {
+ "turbo": "latest"
+ }
+}
+```
+
+## Common Task Configurations
+
+### Standard Build Pipeline
+
+```json
+{
+ "$schema": "https://v2-10-8-canary-4.turborepo.dev/schema.json",
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**", ".next/**", "!.next/cache/**", "!.next/dev/**"]
+ },
+ "dev": {
+ "cache": false,
+ "persistent": true
+ }
+ }
+}
+```
+
+Add a `transit` task if you have tasks that need parallel execution with cache invalidation (see below).
+
+### Dev Task with `^dev` Pattern (for `turbo watch`)
+
+A `dev` task with `dependsOn: ["^dev"]` and `persistent: false` in root turbo.json may look unusual but is **correct for `turbo watch` workflows**:
+
+```json
+// Root turbo.json
+{
+ "tasks": {
+ "dev": {
+ "dependsOn": ["^dev"],
+ "cache": false,
+ "persistent": false // Packages have one-shot dev scripts
+ }
+ }
+}
+
+// Package turbo.json (apps/web/turbo.json)
+{
+ "extends": ["//"],
+ "tasks": {
+ "dev": {
+ "persistent": true // Apps run long-running dev servers
+ }
+ }
+}
+```
+
+**Why this works:**
+
+- **Packages** (e.g., `@acme/db`, `@acme/validators`) have `"dev": "tsc"` — one-shot type generation that completes quickly
+- **Apps** override with `persistent: true` for actual dev servers (Next.js, etc.)
+- **`turbo watch`** re-runs the one-shot package `dev` scripts when source files change, keeping types in sync
+
+**Intended usage:** Run `turbo watch dev` (not `turbo run dev`). Watch mode re-executes one-shot tasks on file changes while keeping persistent tasks running.
+
+**Alternative pattern:** Use a separate task name like `prepare` or `generate` for one-shot dependency builds to make the intent clearer:
+
+```json
+{
+ "tasks": {
+ "prepare": {
+ "dependsOn": ["^prepare"],
+ "outputs": ["dist/**"]
+ },
+ "dev": {
+ "dependsOn": ["prepare"],
+ "cache": false,
+ "persistent": true
+ }
+ }
+}
+```
+
+### Transit Nodes for Parallel Tasks with Cache Invalidation
+
+Some tasks can run in parallel (don't need built output from dependencies) but must invalidate cache when dependency source code changes.
+
+**The problem with `dependsOn: ["^taskname"]`:**
+
+- Forces sequential execution (slow)
+
+**The problem with `dependsOn: []` (no dependencies):**
+
+- Allows parallel execution (fast)
+- But cache is INCORRECT - changing dependency source won't invalidate cache
+
+**Transit Nodes solve both:**
+
+```json
+{
+ "tasks": {
+ "transit": { "dependsOn": ["^transit"] },
+ "my-task": { "dependsOn": ["transit"] }
+ }
+}
+```
+
+The `transit` task creates dependency relationships without matching any actual script, so tasks run in parallel with correct cache invalidation.
+
+**How to identify tasks that need this pattern:** Look for tasks that read source files from dependencies but don't need their build outputs.
+
+### With Environment Variables
+
+```json
+{
+ "globalEnv": ["NODE_ENV"],
+ "globalDependencies": [".env"],
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**"],
+ "env": ["API_URL", "DATABASE_URL"]
+ }
+ }
+}
+```
+
+With `futureFlags.globalConfiguration`, the same config moves global settings under `global` — and `.env` becomes a per-task input instead of a global hash input:
+
+```json
+{
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "env": ["NODE_ENV"],
+ "inputs": [".env"]
+ },
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**"],
+ "env": ["API_URL", "DATABASE_URL"]
+ }
+ }
+}
+```
+
+## Reference Index
+
+### Configuration
+
+| File | Purpose |
+| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
+| [configuration/RULE.md](./references/configuration/RULE.md) | turbo.json overview, Package Configurations |
+| [configuration/tasks.md](./references/configuration/tasks.md) | dependsOn, outputs, inputs, env, cache, persistent |
+| [configuration/global-options.md](./references/configuration/global-options.md) | globalEnv, globalDependencies, global key, futureFlags, cacheDir, envMode |
+| [configuration/gotchas.md](./references/configuration/gotchas.md) | Common configuration mistakes |
+
+### Caching
+
+| File | Purpose |
+| --------------------------------------------------------------- | -------------------------------------------- |
+| [caching/RULE.md](./references/caching/RULE.md) | How caching works, hash inputs |
+| [caching/remote-cache.md](./references/caching/remote-cache.md) | Vercel Remote Cache, self-hosted, login/link |
+| [caching/gotchas.md](./references/caching/gotchas.md) | Debugging cache misses, --summarize, --dry |
+
+### Environment Variables
+
+| File | Purpose |
+| ------------------------------------------------------------- | ----------------------------------------- |
+| [environment/RULE.md](./references/environment/RULE.md) | env, globalEnv, passThroughEnv |
+| [environment/modes.md](./references/environment/modes.md) | Strict vs Loose mode, framework inference |
+| [environment/gotchas.md](./references/environment/gotchas.md) | .env files, CI issues |
+
+### Filtering
+
+| File | Purpose |
+| ----------------------------------------------------------- | ------------------------ |
+| [filtering/RULE.md](./references/filtering/RULE.md) | --filter syntax overview |
+| [filtering/patterns.md](./references/filtering/patterns.md) | Common filter patterns |
+
+### CI/CD
+
+| File | Purpose |
+| --------------------------------------------------------- | ------------------------------- |
+| [ci/RULE.md](./references/ci/RULE.md) | General CI principles |
+| [ci/github-actions.md](./references/ci/github-actions.md) | Complete GitHub Actions setup |
+| [ci/vercel.md](./references/ci/vercel.md) | Vercel deployment, turbo-ignore |
+| [ci/patterns.md](./references/ci/patterns.md) | --affected, caching strategies |
+
+### CLI
+
+| File | Purpose |
+| ----------------------------------------------- | --------------------------------------------- |
+| [cli/RULE.md](./references/cli/RULE.md) | turbo run basics |
+| [cli/commands.md](./references/cli/commands.md) | turbo run flags, turbo-ignore, other commands |
+
+### Best Practices
+
+| File | Purpose |
+| ----------------------------------------------------------------------------- | --------------------------------------------------------------- |
+| [best-practices/RULE.md](./references/best-practices/RULE.md) | Monorepo best practices overview |
+| [best-practices/structure.md](./references/best-practices/structure.md) | Repository structure, workspace config, TypeScript/ESLint setup |
+| [best-practices/packages.md](./references/best-practices/packages.md) | Creating internal packages, JIT vs Compiled, exports |
+| [best-practices/dependencies.md](./references/best-practices/dependencies.md) | Dependency management, installing, version sync |
+
+### Watch Mode
+
+| File | Purpose |
+| ------------------------------------------- | ----------------------------------------------- |
+| [watch/RULE.md](./references/watch/RULE.md) | turbo watch, interruptible tasks, dev workflows |
+
+### Boundaries (Experimental)
+
+| File | Purpose |
+| ----------------------------------------------------- | ----------------------------------------------------- |
+| [boundaries/RULE.md](./references/boundaries/RULE.md) | Enforce package isolation, tag-based dependency rules |
+
+## Source Documentation
+
+This skill is based on the official Turborepo documentation at:
+
+- Source: `apps/docs/content/docs/` in the Turborepo repository
+- Live: https://turborepo.dev/docs
diff --git a/.agents/skills/turborepo/command/turborepo.md b/.agents/skills/turborepo/command/turborepo.md
new file mode 100644
index 00000000..f1673076
--- /dev/null
+++ b/.agents/skills/turborepo/command/turborepo.md
@@ -0,0 +1,70 @@
+---
+description: Load Turborepo skill for creating workflows, tasks, and pipelines in monorepos. Use when users ask to "create a workflow", "make a task", "generate a pipeline", or set up build orchestration.
+---
+
+Load the Turborepo skill and help with monorepo task orchestration: creating workflows, configuring tasks, setting up pipelines, and optimizing builds.
+
+## Workflow
+
+### Step 1: Load turborepo skill
+
+```
+skill({ name: 'turborepo' })
+```
+
+### Step 2: Identify task type from user request
+
+Analyze $ARGUMENTS to determine:
+
+- **Topic**: configuration, caching, filtering, environment, CI, or CLI
+- **Task type**: new setup, debugging, optimization, or implementation
+
+Use decision trees in SKILL.md to select the relevant reference files.
+
+### Step 3: Read relevant reference files
+
+Based on task type, read from `references/<topic>/`:
+
+| Task | Files to Read |
+| -------------------- | ------------------------------------------------------- |
+| Configure turbo.json | `configuration/RULE.md` + `configuration/tasks.md` |
+| Debug cache issues | `caching/gotchas.md` |
+| Set up remote cache | `caching/remote-cache.md` |
+| Filter packages | `filtering/RULE.md` + `filtering/patterns.md` |
+| Environment problems | `environment/gotchas.md` + `environment/modes.md` |
+| Set up CI | `ci/RULE.md` + `ci/github-actions.md` or `ci/vercel.md` |
+| CLI usage | `cli/commands.md` |
+
+### Step 4: Execute task
+
+Apply Turborepo-specific patterns from references to complete the user's request.
+
+**CRITICAL - When creating tasks/scripts/pipelines:**
+
+1. **Prefer package tasks over Root Tasks.** Root Tasks (`//#taskname`) are only for tasks that truly cannot exist in packages, such as Vitest Projects' `//#test`, repo-wide release scripts, or tooling that does not invoke `turbo` itself.
+2. Add scripts to each relevant package's `package.json` (e.g., `apps/web/package.json`, `packages/ui/package.json`)
+3. Register the task in root `turbo.json`
+4. Root `package.json` only contains `turbo run <task>` - never actual task logic, unless defining a valid Root Task exception
+
+**Other things to verify:**
+
+- `outputs` defined for cacheable tasks
+- `dependsOn` uses correct syntax (`^task` vs `task`)
+- Environment variables in `env` key
+- `.env` files in `inputs` if used
+- Use `turbo run` (not `turbo`) in package.json and CI
+
+### Step 5: Summarize
+
+```
+=== Turborepo Task Complete ===
+
+Topic: <configuration|caching|filtering|environment|ci|cli>
+Files referenced: <reference files consulted>
+
+<brief summary of what was done>
+```
+
+<user-request>
+$ARGUMENTS
+</user-request>
diff --git a/.agents/skills/turborepo/references/best-practices/RULE.md b/.agents/skills/turborepo/references/best-practices/RULE.md
new file mode 100644
index 00000000..4870784d
--- /dev/null
+++ b/.agents/skills/turborepo/references/best-practices/RULE.md
@@ -0,0 +1,241 @@
+# Monorepo Best Practices
+
+Essential patterns for structuring and maintaining a healthy Turborepo monorepo.
+
+## Repository Structure
+
+### Standard Layout
+
+```
+my-monorepo/
+├── apps/ # Application packages (deployable)
+│ ├── web/
+│ ├── docs/
+│ └── api/
+├── packages/ # Library packages (shared code)
+│ ├── ui/
+│ ├── utils/
+│ └── config-*/ # Shared configs (eslint, typescript, etc.)
+├── package.json # Root package.json (minimal deps)
+├── turbo.json # Turborepo configuration
+├── pnpm-workspace.yaml # (pnpm) or workspaces in package.json
+└── pnpm-lock.yaml # Lockfile (required)
+```
+
+### Key Principles
+
+1. **`apps/` for deployables**: Next.js sites, APIs, CLIs - things that get deployed
+2. **`packages/` for libraries**: Shared code consumed by apps or other packages
+3. **One purpose per package**: Each package should do one thing well
+4. **No nested packages**: Don't put packages inside packages
+
+## Package Types
+
+### Application Packages (`apps/`)
+
+- **Deployable**: These are the "endpoints" of your package graph
+- **Not installed by other packages**: Apps shouldn't be dependencies of other packages
+- **No shared code**: If code needs sharing, extract to `packages/`
+
+```json
+// apps/web/package.json
+{
+ "name": "web",
+ "private": true,
+ "dependencies": {
+ "@repo/ui": "workspace:*",
+ "next": "latest"
+ }
+}
+```
+
+### Library Packages (`packages/`)
+
+- **Shared code**: Utilities, components, configs
+- **Namespaced names**: Use `@repo/` or `@yourorg/` prefix
+- **Clear exports**: Define what the package exposes
+
+```json
+// packages/ui/package.json
+{
+ "name": "@repo/ui",
+ "exports": {
+ "./button": "./src/button.tsx",
+ "./card": "./src/card.tsx"
+ }
+}
+```
+
+## Package Compilation Strategies
+
+### Just-in-Time (Simplest)
+
+Export TypeScript directly; let the app's bundler compile it.
+
+```json
+{
+ "name": "@repo/ui",
+ "exports": {
+ "./button": "./src/button.tsx"
+ }
+}
+```
+
+**Pros**: Zero build config, instant changes
+**Cons**: Can't cache builds, requires app bundler support
+
+### Compiled (Recommended for Libraries)
+
+Package compiles itself with `tsc` or bundler.
+
+```json
+{
+ "name": "@repo/ui",
+ "exports": {
+ "./button": {
+ "types": "./src/button.tsx",
+ "default": "./dist/button.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc"
+ }
+}
+```
+
+**Pros**: Cacheable by Turborepo, works everywhere
+**Cons**: More configuration
+
+## Dependency Management
+
+### Install Where Used
+
+Install dependencies in the package that uses them, not the root.
+
+```bash
+# Good: Install in the package that needs it
+pnpm add lodash --filter=@repo/utils
+
+# Avoid: Installing everything at root
+pnpm add lodash -w # Only for repo-level tools
+```
+
+### Root Dependencies
+
+Only these belong in root `package.json`:
+
+- `turbo` - The build system
+- `husky`, `lint-staged` - Git hooks
+- Repository-level tooling
+
+### Internal Dependencies
+
+Use workspace protocol for internal packages:
+
+```json
+// pnpm/bun
+{ "@repo/ui": "workspace:*" }
+
+// npm/yarn
+{ "@repo/ui": "*" }
+```
+
+## Exports Best Practices
+
+### Use `exports` Field (Not `main`)
+
+```json
+{
+ "exports": {
+ ".": "./src/index.ts",
+ "./button": "./src/button.tsx",
+ "./utils": "./src/utils.ts"
+ }
+}
+```
+
+### Avoid Barrel Files
+
+Don't create `index.ts` files that re-export everything:
+
+```typescript
+// BAD: packages/ui/src/index.ts
+export * from './button';
+export * from './card';
+export * from './modal';
+// ... imports everything even if you need one thing
+
+// GOOD: Direct exports in package.json
+{
+ "exports": {
+ "./button": "./src/button.tsx",
+ "./card": "./src/card.tsx"
+ }
+}
+```
+
+### Namespace Your Packages
+
+```json
+// Good
+{ "name": "@repo/ui" }
+{ "name": "@acme/utils" }
+
+// Avoid (conflicts with npm registry)
+{ "name": "ui" }
+{ "name": "utils" }
+```
+
+## Common Anti-Patterns
+
+### Accessing Files Across Package Boundaries
+
+```typescript
+// BAD: Reaching into another package
+import { Button } from "../../packages/ui/src/button";
+
+// GOOD: Install and import properly
+import { Button } from "@repo/ui/button";
+```
+
+### Shared Code in Apps
+
+```
+// BAD
+apps/
+ web/
+ shared/ # This should be a package!
+ utils.ts
+
+// GOOD
+packages/
+ utils/ # Proper shared package
+ src/utils.ts
+```
+
+### Too Many Root Dependencies
+
+```json
+// BAD: Root has app dependencies
+{
+ "dependencies": {
+ "react": "^18",
+ "next": "^14",
+ "lodash": "^4"
+ }
+}
+
+// GOOD: Root only has repo tools
+{
+ "devDependencies": {
+ "turbo": "latest",
+ "husky": "latest"
+ }
+}
+```
+
+## See Also
+
+- [structure.md](./structure.md) - Detailed repository structure patterns
+- [packages.md](./packages.md) - Creating and managing internal packages
+- [dependencies.md](./dependencies.md) - Dependency management strategies
diff --git a/.agents/skills/turborepo/references/best-practices/dependencies.md b/.agents/skills/turborepo/references/best-practices/dependencies.md
new file mode 100644
index 00000000..90902e29
--- /dev/null
+++ b/.agents/skills/turborepo/references/best-practices/dependencies.md
@@ -0,0 +1,246 @@
+# Dependency Management
+
+Best practices for managing dependencies in a Turborepo monorepo.
+
+## Core Principle: Install Where Used
+
+Dependencies belong in the package that uses them, not the root.
+
+```bash
+# Good: Install in specific package
+pnpm add react --filter=@repo/ui
+pnpm add next --filter=web
+
+# Avoid: Installing in root
+pnpm add react -w # Only for repo-level tools!
+```
+
+## Benefits of Local Installation
+
+### 1. Clarity
+
+Each package's `package.json` lists exactly what it needs:
+
+```json
+// packages/ui/package.json
+{
+ "dependencies": {
+ "react": "^18.0.0",
+ "class-variance-authority": "^0.7.0"
+ }
+}
+```
+
+### 2. Flexibility
+
+Different packages can use different versions when needed:
+
+```json
+// packages/legacy-ui/package.json
+{ "dependencies": { "react": "^17.0.0" } }
+
+// packages/ui/package.json
+{ "dependencies": { "react": "^18.0.0" } }
+```
+
+### 3. Better Caching
+
+Installing in root changes workspace lockfile, invalidating all caches.
+
+### 4. Pruning Support
+
+`turbo prune` can remove unused dependencies for Docker images.
+
+## What Belongs in Root
+
+Only repository-level tools:
+
+```json
+// Root package.json
+{
+ "devDependencies": {
+ "turbo": "latest",
+ "husky": "^8.0.0",
+ "lint-staged": "^15.0.0"
+ }
+}
+```
+
+**NOT** application dependencies:
+
+- react, next, express
+- lodash, axios, zod
+- Testing libraries (unless truly repo-wide)
+
+## Installing Dependencies
+
+### Single Package
+
+```bash
+# pnpm
+pnpm add lodash --filter=@repo/utils
+
+# npm
+npm install lodash --workspace=@repo/utils
+
+# yarn
+yarn workspace @repo/utils add lodash
+
+# bun
+cd packages/utils && bun add lodash
+```
+
+### Multiple Packages
+
+```bash
+# pnpm
+pnpm add jest --save-dev --filter=web --filter=@repo/ui
+
+# npm
+npm install jest --save-dev --workspace=web --workspace=@repo/ui
+
+# yarn (v2+)
+yarn workspaces foreach -R --from '{web,@repo/ui}' add jest --dev
+```
+
+### Internal Packages
+
+```bash
+# pnpm
+pnpm add @repo/ui --filter=web
+
+# This updates package.json:
+{
+ "dependencies": {
+ "@repo/ui": "workspace:*"
+ }
+}
+```
+
+## Keeping Versions in Sync
+
+### Option 1: Tooling
+
+```bash
+# syncpack - Check and fix version mismatches
+npx syncpack list-mismatches
+npx syncpack fix-mismatches
+
+# manypkg - Similar functionality
+npx @manypkg/cli check
+npx @manypkg/cli fix
+
+# sherif - Rust-based, very fast
+npx sherif
+```
+
+### Option 2: Package Manager Commands
+
+```bash
+# pnpm - Update everywhere
+pnpm up --recursive typescript@latest
+
+# npm - Update in all workspaces
+npm install typescript@latest --workspaces
+```
+
+### Option 3: pnpm Catalogs (pnpm 9.5+)
+
+```yaml
+# pnpm-workspace.yaml
+packages:
+ - "apps/*"
+ - "packages/*"
+
+catalog:
+ react: ^18.2.0
+ typescript: ^5.3.0
+```
+
+```json
+// Any package.json
+{
+ "dependencies": {
+ "react": "catalog:" // Uses version from catalog
+ }
+}
+```
+
+## Internal vs External Dependencies
+
+### Internal (Workspace)
+
+```json
+// pnpm/bun
+{ "@repo/ui": "workspace:*" }
+
+// npm/yarn
+{ "@repo/ui": "*" }
+```
+
+Turborepo understands these relationships and orders builds accordingly.
+
+### External (npm Registry)
+
+```json
+{ "lodash": "^4.17.21" }
+```
+
+Standard semver versioning from npm.
+
+## Peer Dependencies
+
+For library packages that expect the consumer to provide dependencies:
+
+```json
+// packages/ui/package.json
+{
+ "peerDependencies": {
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0"
+ },
+ "devDependencies": {
+ "react": "^18.0.0", // For development/testing
+ "react-dom": "^18.0.0"
+ }
+}
+```
+
+## Common Issues
+
+### "Module not found"
+
+1. Check the dependency is installed in the right package
+2. Run `pnpm install` / `npm install` to update lockfile
+3. Check exports are defined in the package
+
+### Version Conflicts
+
+Packages can use different versions - this is a feature, not a bug. But if you need consistency:
+
+1. Use tooling (syncpack, manypkg)
+2. Use pnpm catalogs
+3. Create a lint rule
+
+### Hoisting Issues
+
+Some tools expect dependencies in specific locations. Use package manager config:
+
+```yaml
+# .npmrc (pnpm)
+public-hoist-pattern[]=*eslint*
+public-hoist-pattern[]=*prettier*
+```
+
+## Lockfile
+
+**Required** for:
+
+- Reproducible builds
+- Turborepo dependency analysis
+- Cache correctness
+
+```bash
+# Commit your lockfile!
+git add pnpm-lock.yaml # or package-lock.json, yarn.lock
+```
diff --git a/.agents/skills/turborepo/references/best-practices/packages.md b/.agents/skills/turborepo/references/best-practices/packages.md
new file mode 100644
index 00000000..85cdf040
--- /dev/null
+++ b/.agents/skills/turborepo/references/best-practices/packages.md
@@ -0,0 +1,335 @@
+# Creating Internal Packages
+
+How to create and structure internal packages in your monorepo.
+
+## Package Creation Checklist
+
+1. Create directory in `packages/`
+2. Add `package.json` with name and exports
+3. Add source code in `src/`
+4. Add `tsconfig.json` if using TypeScript
+5. Install as dependency in consuming packages
+6. Run package manager install to update lockfile
+
+## Package Compilation Strategies
+
+### Just-in-Time (JIT)
+
+Export TypeScript directly. The consuming app's bundler compiles it.
+
+```json
+// packages/ui/package.json
+{
+ "name": "@repo/ui",
+ "exports": {
+ "./button": "./src/button.tsx",
+ "./card": "./src/card.tsx"
+ },
+ "scripts": {
+ "lint": "eslint .",
+ "check-types": "tsc --noEmit"
+ }
+}
+```
+
+**When to use:**
+
+- Apps use modern bundlers (Turbopack, webpack, Vite)
+- You want minimal configuration
+- Build times are acceptable without caching
+
+**Limitations:**
+
+- No Turborepo cache for the package itself
+- Consumer must support TypeScript compilation
+- Can't use TypeScript `paths` (use Node.js subpath imports instead)
+
+### Compiled
+
+Package handles its own compilation.
+
+```json
+// packages/ui/package.json
+{
+ "name": "@repo/ui",
+ "exports": {
+ "./button": {
+ "types": "./src/button.tsx",
+ "default": "./dist/button.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc",
+ "dev": "tsc --watch"
+ }
+}
+```
+
+```json
+// packages/ui/tsconfig.json
+{
+ "extends": "@repo/typescript-config/library.json",
+ "compilerOptions": {
+ "outDir": "dist",
+ "rootDir": "src"
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist"]
+}
+```
+
+**When to use:**
+
+- You want Turborepo to cache builds
+- Package will be used by non-bundler tools
+- You need maximum compatibility
+
+**Remember:** Add `dist/**` to turbo.json outputs!
+
+## Defining Exports
+
+### Multiple Entrypoints
+
+```json
+{
+ "exports": {
+ ".": "./src/index.ts", // @repo/ui
+ "./button": "./src/button.tsx", // @repo/ui/button
+ "./card": "./src/card.tsx", // @repo/ui/card
+ "./hooks": "./src/hooks/index.ts" // @repo/ui/hooks
+ }
+}
+```
+
+### Conditional Exports (Compiled)
+
+```json
+{
+ "exports": {
+ "./button": {
+ "types": "./src/button.tsx",
+ "import": "./dist/button.mjs",
+ "require": "./dist/button.cjs",
+ "default": "./dist/button.js"
+ }
+ }
+}
+```
+
+## Installing Internal Packages
+
+### Add to Consuming Package
+
+```json
+// apps/web/package.json
+{
+ "dependencies": {
+ "@repo/ui": "workspace:*" // pnpm/bun
+ // "@repo/ui": "*" // npm/yarn
+ }
+}
+```
+
+### Run Install
+
+```bash
+pnpm install # Updates lockfile with new dependency
+```
+
+### Import and Use
+
+```typescript
+// apps/web/src/page.tsx
+import { Button } from '@repo/ui/button';
+
+export default function Page() {
+ return <Button>Click me</Button>;
+}
+```
+
+## One Purpose Per Package
+
+### Good Examples
+
+```
+packages/
+├── ui/ # Shared UI components
+├── utils/ # General utilities
+├── auth/ # Authentication logic
+├── database/ # Database client/schemas
+├── eslint-config/ # ESLint configuration
+├── typescript-config/ # TypeScript configuration
+└── api-client/ # Generated API client
+```
+
+### Avoid Mega-Packages
+
+```
+// BAD: One package for everything
+packages/
+└── shared/
+ ├── components/
+ ├── utils/
+ ├── hooks/
+ ├── types/
+ └── api/
+
+// GOOD: Separate by purpose
+packages/
+├── ui/ # Components
+├── utils/ # Utilities
+├── hooks/ # React hooks
+├── types/ # Shared TypeScript types
+└── api-client/ # API utilities
+```
+
+## Config Packages
+
+### TypeScript Config
+
+```json
+// packages/typescript-config/package.json
+{
+ "name": "@repo/typescript-config",
+ "exports": {
+ "./base.json": "./base.json",
+ "./nextjs.json": "./nextjs.json",
+ "./library.json": "./library.json"
+ }
+}
+```
+
+### ESLint Config
+
+```json
+// packages/eslint-config/package.json
+{
+ "name": "@repo/eslint-config",
+ "exports": {
+ "./base": "./base.js",
+ "./next": "./next.js"
+ },
+ "dependencies": {
+ "eslint": "^8.0.0",
+ "eslint-config-next": "latest"
+ }
+}
+```
+
+## Common Mistakes
+
+### Forgetting to Export
+
+```json
+// BAD: No exports defined
+{
+ "name": "@repo/ui"
+}
+
+// GOOD: Clear exports
+{
+ "name": "@repo/ui",
+ "exports": {
+ "./button": "./src/button.tsx"
+ }
+}
+```
+
+### Wrong Workspace Syntax
+
+```json
+// pnpm/bun
+{ "@repo/ui": "workspace:*" } // Correct
+
+// npm/yarn
+{ "@repo/ui": "*" } // Correct
+{ "@repo/ui": "workspace:*" } // Wrong for npm/yarn!
+```
+
+### Missing from turbo.json Outputs
+
+```json
+// Package builds to dist/, but turbo.json doesn't know
+{
+ "tasks": {
+ "build": {
+ "outputs": [".next/**"] // Missing dist/**!
+ }
+ }
+}
+
+// Correct
+{
+ "tasks": {
+ "build": {
+ "outputs": [".next/**", "dist/**"]
+ }
+ }
+}
+```
+
+## TypeScript Best Practices
+
+### Use Node.js Subpath Imports (Not `paths`)
+
+TypeScript `compilerOptions.paths` breaks with JIT packages. Use Node.js subpath imports instead (TypeScript 5.4+).
+
+**JIT Package:**
+
+```json
+// packages/ui/package.json
+{
+ "imports": {
+ "#*": "./src/*"
+ }
+}
+```
+
+```typescript
+// packages/ui/button.tsx
+import { MY_STRING } from "#utils.ts"; // Uses .ts extension
+```
+
+**Compiled Package:**
+
+```json
+// packages/ui/package.json
+{
+ "imports": {
+ "#*": "./dist/*"
+ }
+}
+```
+
+```typescript
+// packages/ui/button.tsx
+import { MY_STRING } from "#utils.js"; // Uses .js extension
+```
+
+### Use `tsc` for Internal Packages
+
+For internal packages, prefer `tsc` over bundlers. Bundlers can mangle code before it reaches your app's bundler, causing hard-to-debug issues.
+
+### Enable Go-to-Definition
+
+For Compiled Packages, enable declaration maps:
+
+```json
+// tsconfig.json
+{
+ "compilerOptions": {
+ "declaration": true,
+ "declarationMap": true
+ }
+}
+```
+
+This creates `.d.ts` and `.d.ts.map` files for IDE navigation.
+
+### No Root tsconfig.json Needed
+
+Each package should have its own `tsconfig.json`. A root one causes all tasks to miss cache when changed. Only use root `tsconfig.json` for non-package scripts.
+
+### Avoid TypeScript Project References
+
+They add complexity and another caching layer. Turborepo handles dependencies better.
diff --git a/.agents/skills/turborepo/references/best-practices/structure.md b/.agents/skills/turborepo/references/best-practices/structure.md
new file mode 100644
index 00000000..0e96f186
--- /dev/null
+++ b/.agents/skills/turborepo/references/best-practices/structure.md
@@ -0,0 +1,297 @@
+# Repository Structure
+
+Detailed guidance on structuring a Turborepo monorepo.
+
+## Workspace Configuration
+
+### pnpm (Recommended)
+
+```yaml
+# pnpm-workspace.yaml
+packages:
+ - "apps/*"
+ - "packages/*"
+```
+
+### npm/yarn/bun
+
+```json
+// package.json
+{
+ "workspaces": ["apps/*", "packages/*"]
+}
+```
+
+## Root package.json
+
+```json
+{
+ "name": "my-monorepo",
+ "private": true,
+ "packageManager": "[email protected]",
+ "scripts": {
+ "build": "turbo run build",
+ "dev": "turbo run dev",
+ "lint": "turbo run lint",
+ "test": "turbo run test"
+ },
+ "devDependencies": {
+ "turbo": "latest"
+ }
+}
+```
+
+Key points:
+
+- `private: true` - Prevents accidental publishing
+- `packageManager` - Enforces consistent package manager version
+- **Scripts only delegate to `turbo run`** - No actual build logic here!
+- Minimal devDependencies (just turbo and repo tools)
+
+## Always Prefer Package Tasks
+
+**Always use package tasks. Only use Root Tasks if you cannot succeed with package tasks.**
+
+```json
+// packages/web/package.json
+{
+ "scripts": {
+ "build": "next build",
+ "lint": "eslint .",
+ "test": "vitest",
+ "typecheck": "tsc --noEmit"
+ }
+}
+
+// packages/api/package.json
+{
+ "scripts": {
+ "build": "tsc",
+ "lint": "eslint .",
+ "test": "vitest",
+ "typecheck": "tsc --noEmit"
+ }
+}
+```
+
+Package tasks enable Turborepo to:
+
+1. **Parallelize** - Run `web#lint` and `api#lint` simultaneously
+2. **Cache individually** - Each package's task output is cached separately
+3. **Filter precisely** - Run `turbo run test --filter=web` for just one package
+
+**Root Tasks are a fallback** for tasks that truly cannot run per-package:
+
+```json
+// AVOID unless necessary - sequential, not parallelized, can't filter
+{
+ "scripts": {
+ "lint": "eslint apps/web && eslint apps/api && eslint packages/ui"
+ }
+}
+```
+
+## Root turbo.json
+
+```json
+{
+ "$schema": "https://v2-10-8-canary-4.turborepo.dev/schema.json",
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**", ".next/**", "!.next/cache/**", "!.next/dev/**"]
+ },
+ "lint": {},
+ "test": {
+ "dependsOn": ["build"]
+ },
+ "dev": {
+ "cache": false,
+ "persistent": true
+ }
+ }
+}
+```
+
+With `futureFlags.globalConfiguration`, global settings move under a `global` key:
+
+```json
+{
+ "$schema": "https://v2-10-8-canary-4.turborepo.dev/schema.json",
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "inputs": ["tsconfig.json"],
+ "env": ["CI"]
+ },
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**", ".next/**", "!.next/cache/**", "!.next/dev/**"]
+ },
+ "lint": {},
+ "test": {
+ "dependsOn": ["build"]
+ },
+ "dev": {
+ "cache": false,
+ "persistent": true
+ }
+ }
+}
+```
+
+## Directory Organization
+
+### Grouping Packages
+
+You can group packages by adding more workspace paths:
+
+```yaml
+# pnpm-workspace.yaml
+packages:
+ - "apps/*"
+ - "packages/*"
+ - "packages/config/*" # Grouped configs
+ - "packages/features/*" # Feature packages
+```
+
+This allows:
+
+```
+packages/
+├── ui/
+├── utils/
+├── config/
+│ ├── eslint/
+│ ├── typescript/
+│ └── tailwind/
+└── features/
+ ├── auth/
+ └── payments/
+```
+
+### What NOT to Do
+
+```yaml
+# BAD: Nested wildcards cause ambiguous behavior
+packages:
+ - "packages/**" # Don't do this!
+```
+
+## Package Anatomy
+
+### Minimum Required Files
+
+```
+packages/ui/
+├── package.json # Required: Makes it a package
+├── src/ # Source code
+│ └── button.tsx
+└── tsconfig.json # TypeScript config (if using TS)
+```
+
+### package.json Requirements
+
+```json
+{
+ "name": "@repo/ui", // Unique, namespaced name
+ "version": "0.0.0", // Version (can be 0.0.0 for internal)
+ "private": true, // Prevents accidental publishing
+ "exports": {
+ // Entry points
+ "./button": "./src/button.tsx"
+ }
+}
+```
+
+## TypeScript Configuration
+
+### Shared Base Config
+
+Create a shared TypeScript config package:
+
+```
+packages/
+└── typescript-config/
+ ├── package.json
+ ├── base.json
+ ├── nextjs.json
+ └── library.json
+```
+
+```json
+// packages/typescript-config/base.json
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "moduleResolution": "bundler",
+ "module": "ESNext",
+ "target": "ES2022"
+ }
+}
+```
+
+### Extending in Packages
+
+```json
+// packages/ui/tsconfig.json
+{
+ "extends": "@repo/typescript-config/library.json",
+ "compilerOptions": {
+ "outDir": "dist",
+ "rootDir": "src"
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist"]
+}
+```
+
+### No Root tsconfig.json
+
+You likely don't need a `tsconfig.json` in the workspace root. Each package should have its own config extending from the shared config package.
+
+## ESLint Configuration
+
+### Shared Config Package
+
+```
+packages/
+└── eslint-config/
+ ├── package.json
+ ├── base.js
+ ├── next.js
+ └── library.js
+```
+
+```json
+// packages/eslint-config/package.json
+{
+ "name": "@repo/eslint-config",
+ "exports": {
+ "./base": "./base.js",
+ "./next": "./next.js",
+ "./library": "./library.js"
+ }
+}
+```
+
+### Using in Packages
+
+```js
+// apps/web/.eslintrc.js
+module.exports = {
+ extends: ["@repo/eslint-config/next"]
+};
+```
+
+## Lockfile
+
+A lockfile is **required** for:
+
+- Reproducible builds
+- Turborepo to understand package dependencies
+- Cache correctness
+
+Without a lockfile, you'll see unpredictable behavior.
diff --git a/.agents/skills/turborepo/references/boundaries/RULE.md b/.agents/skills/turborepo/references/boundaries/RULE.md
new file mode 100644
index 00000000..3deb0a41
--- /dev/null
+++ b/.agents/skills/turborepo/references/boundaries/RULE.md
@@ -0,0 +1,126 @@
+# Boundaries
+
+**Experimental feature** - See [RFC](https://github.com/vercel/turborepo/discussions/9435)
+
+Full docs: https://turborepo.dev/docs/reference/boundaries
+
+Boundaries enforce package isolation by detecting:
+
+1. Imports of files outside the package's directory
+2. Imports of packages not declared in `package.json` dependencies
+
+## Usage
+
+```bash
+turbo boundaries
+```
+
+Run this to check for workspace violations across your monorepo.
+
+## Tags
+
+Tags allow you to create rules for which packages can depend on each other.
+
+### Adding Tags to a Package
+
+```json
+// packages/ui/turbo.json
+{
+ "tags": ["internal"]
+}
+```
+
+### Configuring Tag Rules
+
+Rules go in root `turbo.json`:
+
+```json
+// turbo.json
+{
+ "boundaries": {
+ "tags": {
+ "public": {
+ "dependencies": {
+ "deny": ["internal"]
+ }
+ }
+ }
+ }
+}
+```
+
+This prevents `public`-tagged packages from importing `internal`-tagged packages.
+
+### Rule Types
+
+**Allow-list approach** (only allow specific tags):
+
+```json
+{
+ "boundaries": {
+ "tags": {
+ "public": {
+ "dependencies": {
+ "allow": ["public"]
+ }
+ }
+ }
+ }
+}
+```
+
+**Deny-list approach** (block specific tags):
+
+```json
+{
+ "boundaries": {
+ "tags": {
+ "public": {
+ "dependencies": {
+ "deny": ["internal"]
+ }
+ }
+ }
+ }
+}
+```
+
+**Restrict dependents** (who can import this package):
+
+```json
+{
+ "boundaries": {
+ "tags": {
+ "private": {
+ "dependents": {
+ "deny": ["public"]
+ }
+ }
+ }
+ }
+}
+```
+
+### Using Package Names
+
+Package names work in place of tags:
+
+```json
+{
+ "boundaries": {
+ "tags": {
+ "private": {
+ "dependents": {
+ "deny": ["@repo/my-pkg"]
+ }
+ }
+ }
+ }
+}
+```
+
+## Key Points
+
+- Rules apply transitively (dependencies of dependencies)
+- Helps enforce architectural boundaries at scale
+- Catches violations before runtime/build errors
diff --git a/.agents/skills/turborepo/references/caching/RULE.md b/.agents/skills/turborepo/references/caching/RULE.md
new file mode 100644
index 00000000..80ec53bc
--- /dev/null
+++ b/.agents/skills/turborepo/references/caching/RULE.md
@@ -0,0 +1,153 @@
+# How Turborepo Caching Works
+
+Turborepo's core principle: **never do the same work twice**.
+
+## The Cache Equation
+
+```
+fingerprint(inputs) → stored outputs
+```
+
+If inputs haven't changed, restore outputs from cache instead of re-running the task.
+
+## What Determines the Cache Key
+
+### Global Hash Inputs
+
+These affect ALL tasks in the repo:
+
+- `package-lock.json` / `yarn.lock` / `pnpm-lock.yaml`
+- Files listed in `globalDependencies` (or `global.env` when using `globalConfiguration`)
+- Environment variables in `globalEnv` (or `global.env`)
+- `turbo.json` configuration
+
+```json
+{
+ "globalDependencies": [".env", "tsconfig.base.json"],
+ "globalEnv": ["CI", "NODE_ENV"]
+}
+```
+
+### Task Hash Inputs
+
+These affect specific tasks:
+
+- All files in the package (unless filtered by `inputs`)
+- `package.json` contents
+- Environment variables in task's `env` key
+- Task configuration (command, outputs, dependencies)
+- Hashes of dependent tasks (`dependsOn`)
+- Files from `global.inputs` (when using `futureFlags.globalConfiguration` — see below)
+
+```json
+{
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "inputs": ["src/**", "package.json", "tsconfig.json"],
+ "env": ["API_URL"]
+ }
+ }
+}
+```
+
+### How `global.inputs` Changes the Hash Equation
+
+When `futureFlags.globalConfiguration` is enabled, `global.inputs` files are **not** part of the global hash. Instead, they are prepended to every task's `inputs` and folded into the **task hash**. This is a fundamental change from `globalDependencies`.
+
+**With `globalDependencies` (default):**
+
+```
+task cache key = hash(global hash, task hash)
+ ↑ includes globalDependencies file hashes
+```
+
+Changing a `globalDependencies` file invalidates **every** task, regardless of task-level `inputs`. There is no way for a task to opt out.
+
+**With `global.inputs` (`futureFlags.globalConfiguration`):**
+
+```
+task cache key = hash(global hash, task hash)
+ ↑ includes global.inputs file hashes (merged with task inputs)
+```
+
+`global.inputs` files are merged into each task's input globs. This means:
+
+- Tasks can **exclude** specific global files with negation globs: `"inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/tsconfig.json"]`
+- The global hash is smaller (it still includes lockfile, engines, `global.env`, etc. — but not file hashes from `global.inputs`)
+- The task hash correctly includes the global input file hashes alongside the task's own inputs
+
+```json
+{
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "inputs": ["tsconfig.json", ".env"]
+ },
+ "tasks": {
+ "build": {
+ "outputs": ["dist/**"]
+ },
+ "lint": {
+ "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/tsconfig.json"]
+ }
+ }
+}
+```
+
+In this example, changing `tsconfig.json` invalidates `build` (it's in the task's inputs) but **not** `lint` (which explicitly excludes it). With `globalDependencies`, both would have been invalidated.
+
+## What Gets Cached
+
+1. **File outputs** - files/directories specified in `outputs`
+2. **Task logs** - stdout/stderr for replay on cache hit
+
+```json
+{
+ "tasks": {
+ "build": {
+ "outputs": ["dist/**", ".next/**"]
+ }
+ }
+}
+```
+
+## Local Cache Location
+
+```
+.turbo/cache/
+├── <hash1>.tar.zst # compressed outputs
+├── <hash2>.tar.zst
+└── ...
+```
+
+Add `.turbo` to `.gitignore`.
+
+## Cache Restoration
+
+On cache hit, Turborepo:
+
+1. Extracts archived outputs to their original locations
+2. Replays the logged stdout/stderr
+3. Reports the task as cached (shows `FULL TURBO` in output)
+
+## Example Flow
+
+```bash
+# First run - executes build, caches result
+turbo build
+# → packages/ui: cache miss, executing...
+# → packages/web: cache miss, executing...
+
+# Second run - same inputs, restores from cache
+turbo build
+# → packages/ui: cache hit, replaying output
+# → packages/web: cache hit, replaying output
+# → FULL TURBO
+```
+
+## Key Points
+
+- Cache is content-addressed (based on input hash, not timestamps)
+- Empty `outputs` array means task runs but nothing is cached
+- Tasks without `outputs` key cache nothing (use `"outputs": []` to be explicit)
+- Cache is invalidated when ANY input changes
diff --git a/.agents/skills/turborepo/references/caching/gotchas.md b/.agents/skills/turborepo/references/caching/gotchas.md
new file mode 100644
index 00000000..e5f99770
--- /dev/null
+++ b/.agents/skills/turborepo/references/caching/gotchas.md
@@ -0,0 +1,190 @@
+# Debugging Cache Issues
+
+## Diagnostic Tools
+
+### `--summarize`
+
+Generates a JSON file with all hash inputs. Compare two runs to find differences.
+
+```bash
+turbo build --summarize
+# Creates .turbo/runs/<run-id>.json
+```
+
+The summary includes:
+
+- Global hash and its inputs
+- Per-task hashes and their inputs
+- Environment variables that affected the hash
+
+**Comparing runs:**
+
+```bash
+# Run twice, compare the summaries
+diff .turbo/runs/<first-run>.json .turbo/runs/<second-run>.json
+```
+
+### `--dry` / `--dry=json`
+
+See what would run without executing anything:
+
+```bash
+turbo build --dry
+turbo build --dry=json # machine-readable output
+```
+
+Shows cache status for each task without running them.
+
+### `--force`
+
+Skip reading cache, re-execute all tasks:
+
+```bash
+turbo build --force
+```
+
+Useful to verify tasks actually work (not just cached results).
+
+## Unexpected Cache Misses
+
+**Symptom:** Task runs when you expected a cache hit.
+
+### Environment Variable Changed
+
+Check if an env var in the `env` key changed:
+
+```json
+{
+ "tasks": {
+ "build": {
+ "env": ["API_URL", "NODE_ENV"]
+ }
+ }
+}
+```
+
+Different `API_URL` between runs = cache miss.
+
+### .env File Changed
+
+`.env` files aren't tracked by default. Add to `inputs`:
+
+```json
+{
+ "tasks": {
+ "build": {
+ "inputs": ["$TURBO_DEFAULT$", ".env", ".env.local"]
+ }
+ }
+}
+```
+
+Or use `globalDependencies` for repo-wide env files:
+
+```json
+{
+ "globalDependencies": [".env"]
+}
+```
+
+With `futureFlags.globalConfiguration`, use `global.inputs` instead. The key difference: `global.inputs` files are folded into each task's hash individually (not the global hash), so tasks can exclude specific files with negation globs.
+
+```json
+{
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "inputs": [".env"]
+ }
+}
+```
+
+### Lockfile Changed
+
+Installing/updating packages changes the global hash.
+
+### Source Files Changed
+
+Any file in the package (or in `inputs`) triggers a miss.
+
+### turbo.json Changed
+
+Config changes invalidate the global hash.
+
+## Incorrect Cache Hits
+
+**Symptom:** Cached output is stale/wrong.
+
+### Missing Environment Variable
+
+Task uses an env var not listed in `env`:
+
+```javascript
+// build.js
+const apiUrl = process.env.API_URL; // not tracked!
+```
+
+Fix: add to task config:
+
+```json
+{
+ "tasks": {
+ "build": {
+ "env": ["API_URL"]
+ }
+ }
+}
+```
+
+### Missing File in Inputs
+
+Task reads a file outside default inputs:
+
+```json
+{
+ "tasks": {
+ "build": {
+ "inputs": [
+ "$TURBO_DEFAULT$",
+ "../../shared-config.json" // file outside package
+ ]
+ }
+ }
+}
+```
+
+## Useful Flags
+
+```bash
+# Only show output for cache misses
+turbo build --output-logs=new-only
+
+# Show output for everything (debugging)
+turbo build --output-logs=full
+
+# See why tasks are running
+turbo build --verbosity=2
+```
+
+## Debugging with `globalConfiguration` Enabled
+
+When `futureFlags.globalConfiguration` is on, `global.inputs` files appear in per-task hash inputs (not the global hash). If you're getting unexpected cache misses:
+
+1. Check `--summarize` output — global input files will show up in the **task inputs** section, not the global hash section
+2. Verify tasks aren't accidentally excluding global inputs via negation globs in `inputs`
+3. Remember that toggling the `globalConfiguration` flag itself invalidates all caches (the flag value is part of the global hash)
+
+If you're getting unexpected cache **hits** after changing a global input file, the task may be excluding that file with a negation glob. Check the task's `inputs` for `!$TURBO_ROOT$/...` patterns.
+
+## Quick Checklist
+
+Cache miss when expected hit:
+
+1. Run with `--summarize`, compare with previous run
+2. Check env vars with `--dry=json`
+3. Look for lockfile/config changes in git
+
+Cache hit when expected miss:
+
+1. Verify env var is in `env` array
+2. Verify file is in `inputs` array
+3. Check if file is outside package directory
diff --git a/.agents/skills/turborepo/references/caching/remote-cache.md b/.agents/skills/turborepo/references/caching/remote-cache.md
new file mode 100644
index 00000000..da76458b
--- /dev/null
+++ b/.agents/skills/turborepo/references/caching/remote-cache.md
@@ -0,0 +1,127 @@
+# Remote Caching
+
+Share cache artifacts across your team and CI pipelines.
+
+## Benefits
+
+- Team members get cache hits from each other's work
+- CI gets cache hits from local development (and vice versa)
+- Dramatically faster CI runs after first build
+- No more "works on my machine" rebuilds
+
+## Vercel Remote Cache
+
+Free, zero-config when deploying on Vercel. For local dev and other CI:
+
+### Local Development Setup
+
+```bash
+# Authenticate with Vercel
+npx turbo login
+
+# Link repo to your Vercel team
+npx turbo link
+```
+
+This creates `.turbo/config.json` with your team info (gitignored by default).
+
+### CI Setup
+
+Set these environment variables:
+
+```bash
+TURBO_TOKEN=<your-token>
+TURBO_TEAM=<your-team-slug>
+```
+
+Get your token from Vercel dashboard → Settings → Tokens.
+
+**GitHub Actions example:**
+
+```yaml
+- name: Build
+ run: npx turbo build
+ env:
+ TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
+ TURBO_TEAM: ${{ vars.TURBO_TEAM }}
+```
+
+## Configuration in turbo.json
+
+```json
+{
+ "remoteCache": {
+ "enabled": true,
+ "signature": false
+ }
+}
+```
+
+Options:
+
+- `enabled`: toggle remote cache (default: true when authenticated)
+- `signature`: require artifact signing (default: false)
+
+## Artifact Signing
+
+Verify cache artifacts haven't been tampered with:
+
+```bash
+# Set a secret key (use same key across all environments)
+export TURBO_REMOTE_CACHE_SIGNATURE_KEY="your-secret-key"
+```
+
+Enable in config:
+
+```json
+{
+ "remoteCache": {
+ "signature": true
+ }
+}
+```
+
+Signed artifacts can only be restored if the signature matches.
+
+## Self-Hosted Options
+
+Community implementations for running your own cache server:
+
+- **turbo-remote-cache** (Node.js) - supports S3, GCS, Azure
+- **turborepo-remote-cache** (Go) - lightweight, S3-compatible
+- **ducktape** (Rust) - high-performance option
+
+Configure with environment variables:
+
+```bash
+TURBO_API=https://your-cache-server.com
+TURBO_TOKEN=your-auth-token
+TURBO_TEAM=your-team
+```
+
+## Cache Behavior Control
+
+```bash
+# Disable remote cache for a run
+turbo build --remote-cache-read-only # read but don't write
+turbo build --no-cache # skip cache entirely
+
+# Environment variable alternative
+TURBO_REMOTE_ONLY=true # only use remote, skip local
+```
+
+## Debugging Remote Cache
+
+```bash
+# Verbose output shows cache operations
+turbo build --verbosity=2
+
+# Check if remote cache is configured
+turbo config
+```
+
+Look for:
+
+- "Remote caching enabled" in output
+- Upload/download messages during runs
+- "cache hit, replaying output" with remote cache indicator
diff --git a/.agents/skills/turborepo/references/ci/RULE.md b/.agents/skills/turborepo/references/ci/RULE.md
new file mode 100644
index 00000000..f331c2cf
--- /dev/null
+++ b/.agents/skills/turborepo/references/ci/RULE.md
@@ -0,0 +1,79 @@
+# CI/CD with Turborepo
+
+General principles for running Turborepo in continuous integration environments.
+
+## Core Principles
+
+### Always Use `turbo run` in CI
+
+**Never use the `turbo <tasks>` shorthand in CI or scripts.** Always use `turbo run`:
+
+```bash
+# CORRECT - Always use in CI, package.json, scripts
+turbo run build test lint
+
+# WRONG - Shorthand is only for one-off terminal commands
+turbo build test lint
+```
+
+The shorthand `turbo <tasks>` is only for one-off invocations typed directly in terminal by humans or agents. Anywhere the command is written into code (CI, package.json, scripts), use `turbo run`.
+
+### Enable Remote Caching
+
+Remote caching dramatically speeds up CI by sharing cached artifacts across runs.
+
+Required environment variables:
+
+```bash
+TURBO_TOKEN=your_vercel_token
+TURBO_TEAM=your_team_slug
+```
+
+### Use --affected for PR Builds
+
+The `--affected` flag only runs tasks for packages changed since the base branch:
+
+```bash
+turbo run build test --affected
+```
+
+This requires Git history to compute what changed.
+
+## Git History Requirements
+
+### Fetch Depth
+
+`--affected` needs access to the merge base. Shallow clones break this.
+
+```yaml
+# GitHub Actions
+- uses: actions/checkout@v4
+ with:
+ fetch-depth: 2 # Minimum for --affected
+ # Use 0 for full history if merge base is far
+```
+
+### Why Shallow Clones Break --affected
+
+Turborepo compares the current HEAD to the merge base with `main`. If that commit isn't fetched, `--affected` falls back to running everything.
+
+For PRs with many commits, consider:
+
+```yaml
+fetch-depth: 0 # Full history
+```
+
+## Environment Variables Reference
+
+| Variable | Purpose |
+| ------------------- | ------------------------------------ |
+| `TURBO_TOKEN` | Vercel access token for remote cache |
+| `TURBO_TEAM` | Your Vercel team slug |
+| `TURBO_REMOTE_ONLY` | Skip local cache, use remote only |
+| `TURBO_LOG_ORDER` | Set to `grouped` for cleaner CI logs |
+
+## See Also
+
+- [github-actions.md](./github-actions.md) - GitHub Actions setup
+- [vercel.md](./vercel.md) - Vercel deployment
+- [patterns.md](./patterns.md) - CI optimization patterns
diff --git a/.agents/skills/turborepo/references/ci/github-actions.md b/.agents/skills/turborepo/references/ci/github-actions.md
new file mode 100644
index 00000000..1cdb34f3
--- /dev/null
+++ b/.agents/skills/turborepo/references/ci/github-actions.md
@@ -0,0 +1,162 @@
+# GitHub Actions
+
+Complete setup guide for Turborepo with GitHub Actions.
+
+## Basic Workflow Structure
+
+```yaml
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 2
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Build and Test
+ run: turbo run build test lint
+```
+
+## Package Manager Setup
+
+### pnpm
+
+```yaml
+- uses: pnpm/action-setup@v3
+ with:
+ version: 9
+
+- uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: "pnpm"
+
+- run: pnpm install --frozen-lockfile
+```
+
+### Yarn
+
+```yaml
+- uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: "yarn"
+
+- run: yarn install --frozen-lockfile
+```
+
+### Bun
+
+```yaml
+- uses: oven-sh/setup-bun@v1
+ with:
+ bun-version: latest
+
+- run: bun install --frozen-lockfile
+```
+
+## Remote Cache Setup
+
+### 1. Create Vercel Access Token
+
+1. Go to [Vercel Dashboard](https://vercel.com/account/tokens)
+2. Create a new token with appropriate scope
+3. Copy the token value
+
+### 2. Add Secrets and Variables
+
+In your GitHub repository settings:
+
+**Secrets** (Settings > Secrets and variables > Actions > Secrets):
+
+- `TURBO_TOKEN`: Your Vercel access token
+
+**Variables** (Settings > Secrets and variables > Actions > Variables):
+
+- `TURBO_TEAM`: Your Vercel team slug
+
+### 3. Add to Workflow
+
+```yaml
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ env:
+ TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
+ TURBO_TEAM: ${{ vars.TURBO_TEAM }}
+```
+
+## Alternative: actions/cache
+
+If you can't use remote cache, cache Turborepo's local cache directory:
+
+```yaml
+- uses: actions/cache@v4
+ with:
+ path: .turbo
+ key: turbo-${{ runner.os }}-${{ hashFiles('**/turbo.json', '**/package-lock.json') }}
+ restore-keys: |
+ turbo-${{ runner.os }}-
+```
+
+Note: This is less effective than remote cache since it's per-branch.
+
+## Complete Example
+
+```yaml
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ env:
+ TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
+ TURBO_TEAM: ${{ vars.TURBO_TEAM }}
+
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 2
+
+ - uses: pnpm/action-setup@v3
+ with:
+ version: 9
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: "pnpm"
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Build
+ run: turbo run build --affected
+
+ - name: Test
+ run: turbo run test --affected
+
+ - name: Lint
+ run: turbo run lint --affected
+```
diff --git a/.agents/skills/turborepo/references/ci/patterns.md b/.agents/skills/turborepo/references/ci/patterns.md
new file mode 100644
index 00000000..447509a1
--- /dev/null
+++ b/.agents/skills/turborepo/references/ci/patterns.md
@@ -0,0 +1,145 @@
+# CI Optimization Patterns
+
+Strategies for efficient CI/CD with Turborepo.
+
+## PR vs Main Branch Builds
+
+### PR Builds: Only Affected
+
+Test only what changed in the PR:
+
+```yaml
+- name: Test (PR)
+ if: github.event_name == 'pull_request'
+ run: turbo run build test --affected
+```
+
+### Main Branch: Full Build
+
+Ensure complete validation on merge:
+
+```yaml
+- name: Test (Main)
+ if: github.ref == 'refs/heads/main'
+ run: turbo run build test
+```
+
+## Custom Git Ranges with --filter
+
+For advanced scenarios, use `--filter` with git refs:
+
+```bash
+# Changes since specific commit
+turbo run test --filter="...[abc123]"
+
+# Changes between refs
+turbo run test --filter="...[main...HEAD]"
+
+# Changes in last 3 commits
+turbo run test --filter="...[HEAD~3]"
+```
+
+## Caching Strategies
+
+### Remote Cache (Recommended)
+
+Best performance - shared across all CI runs and developers:
+
+```yaml
+env:
+ TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
+ TURBO_TEAM: ${{ vars.TURBO_TEAM }}
+```
+
+### actions/cache Fallback
+
+When remote cache isn't available:
+
+```yaml
+- uses: actions/cache@v4
+ with:
+ path: .turbo
+ key: turbo-${{ runner.os }}-${{ github.sha }}
+ restore-keys: |
+ turbo-${{ runner.os }}-${{ github.ref }}-
+ turbo-${{ runner.os }}-
+```
+
+Limitations:
+
+- Cache is branch-scoped
+- PRs restore from base branch cache
+- Less efficient than remote cache
+
+## Matrix Builds
+
+Test across Node versions:
+
+```yaml
+strategy:
+ matrix:
+ node: [18, 20, 22]
+
+steps:
+ - uses: actions/setup-node@v4
+ with:
+ node-version: ${{ matrix.node }}
+
+ - run: turbo run test
+```
+
+## Parallelizing Across Jobs
+
+Split tasks into separate jobs:
+
+```yaml
+jobs:
+ lint:
+ runs-on: ubuntu-latest
+ steps:
+ - run: turbo run lint --affected
+
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - run: turbo run test --affected
+
+ build:
+ runs-on: ubuntu-latest
+ needs: [lint, test]
+ steps:
+ - run: turbo run build
+```
+
+### Cache Considerations
+
+When parallelizing:
+
+- Each job has separate cache writes
+- Remote cache handles this automatically
+- With actions/cache, use unique keys per job to avoid conflicts
+
+```yaml
+- uses: actions/cache@v4
+ with:
+ path: .turbo
+ key: turbo-${{ runner.os }}-${{ github.job }}-${{ github.sha }}
+```
+
+## Conditional Tasks
+
+Skip expensive tasks on draft PRs:
+
+```yaml
+- name: E2E Tests
+ if: github.event.pull_request.draft == false
+ run: turbo run test:e2e --affected
+```
+
+Or require label for full test:
+
+```yaml
+- name: Full Test Suite
+ if: contains(github.event.pull_request.labels.*.name, 'full-test')
+ run: turbo run test
+```
diff --git a/.agents/skills/turborepo/references/ci/vercel.md b/.agents/skills/turborepo/references/ci/vercel.md
new file mode 100644
index 00000000..f21d41ac
--- /dev/null
+++ b/.agents/skills/turborepo/references/ci/vercel.md
@@ -0,0 +1,103 @@
+# Vercel Deployment
+
+Turborepo integrates seamlessly with Vercel for monorepo deployments.
+
+## Remote Cache
+
+Remote caching is **automatically enabled** when deploying to Vercel. No configuration needed - Vercel detects Turborepo and enables caching.
+
+This means:
+
+- No `TURBO_TOKEN` or `TURBO_TEAM` setup required on Vercel
+- Cache is shared across all deployments
+- Preview and production builds benefit from cache
+
+## turbo-ignore
+
+Skip unnecessary builds when a package hasn't changed using `turbo-ignore`.
+
+### Installation
+
+```bash
+npx turbo-ignore
+```
+
+Or install globally in your project:
+
+```bash
+pnpm add -D turbo-ignore
+```
+
+### Setup in Vercel
+
+1. Go to your project in Vercel Dashboard
+2. Navigate to Settings > Git > Ignored Build Step
+3. Select "Custom" and enter:
+
+```bash
+npx turbo-ignore
+```
+
+### How It Works
+
+`turbo-ignore` checks if the current package (or its dependencies) changed since the last successful deployment:
+
+1. Compares current commit to last deployed commit
+2. Uses Turborepo's dependency graph
+3. Returns exit code 0 (skip) if no changes
+4. Returns exit code 1 (build) if changes detected
+
+### Options
+
+```bash
+# Check specific package
+npx turbo-ignore web
+
+# Use specific comparison ref
+npx turbo-ignore --fallback=HEAD~1
+
+# Verbose output
+npx turbo-ignore --verbose
+```
+
+## Environment Variables
+
+Set environment variables in Vercel Dashboard:
+
+1. Go to Project Settings > Environment Variables
+2. Add variables for each environment (Production, Preview, Development)
+
+Common variables:
+
+- `DATABASE_URL`
+- `API_KEY`
+- Package-specific config
+
+## Monorepo Root Directory
+
+For monorepos, set the root directory in Vercel:
+
+1. Project Settings > General > Root Directory
+2. Set to the package path (e.g., `apps/web`)
+
+Vercel automatically:
+
+- Installs dependencies from monorepo root
+- Runs build from the package directory
+- Detects framework settings
+
+## Build Command
+
+Vercel auto-detects `turbo run build` when `turbo.json` exists at root.
+
+Override if needed:
+
+```bash
+turbo run build --filter=web
+```
+
+Or for production-only optimizations:
+
+```bash
+turbo run build --filter=web --env-mode=strict
+```
diff --git a/.agents/skills/turborepo/references/cli/RULE.md b/.agents/skills/turborepo/references/cli/RULE.md
new file mode 100644
index 00000000..63f6f34d
--- /dev/null
+++ b/.agents/skills/turborepo/references/cli/RULE.md
@@ -0,0 +1,100 @@
+# turbo run
+
+The primary command for executing tasks across your monorepo.
+
+## Basic Usage
+
+```bash
+# Full form (use in CI, package.json, scripts)
+turbo run <tasks>
+
+# Shorthand (only for one-off terminal invocations)
+turbo <tasks>
+```
+
+## When to Use `turbo run` vs `turbo`
+
+**Always use `turbo run` when the command is written into code:**
+
+- `package.json` scripts
+- CI/CD workflows (GitHub Actions, etc.)
+- Shell scripts
+- Documentation
+- Any static/committed configuration
+
+**Only use `turbo` (shorthand) for:**
+
+- One-off commands typed directly in terminal
+- Ad-hoc invocations by humans or agents
+
+```json
+// package.json - ALWAYS use "turbo run"
+{
+ "scripts": {
+ "build": "turbo run build",
+ "dev": "turbo run dev",
+ "lint": "turbo run lint",
+ "test": "turbo run test"
+ }
+}
+```
+
+```yaml
+# CI workflow - ALWAYS use "turbo run"
+- run: turbo run build --affected
+- run: turbo run test --affected
+```
+
+```bash
+# Terminal one-off - shorthand OK
+turbo build --filter=web
+```
+
+## Running Tasks
+
+Tasks must be defined in `turbo.json` before running.
+
+```bash
+# Single task
+turbo build
+
+# Multiple tasks
+turbo run build lint test
+
+# See available tasks (run without arguments)
+turbo run
+```
+
+## Passing Arguments to Scripts
+
+Use `--` to pass arguments through to the underlying package scripts:
+
+```bash
+turbo run build -- --sourcemap
+turbo test -- --watch
+turbo lint -- --fix
+```
+
+Everything after `--` goes directly to the task's script.
+
+## Package Selection
+
+By default, turbo runs tasks in all packages. Use `--filter` to narrow scope:
+
+```bash
+turbo build --filter=web
+turbo test --filter=./apps/*
+```
+
+See `filtering/` for complete filter syntax.
+
+## Quick Reference
+
+| Goal | Command |
+| ------------------- | -------------------------- |
+| Build everything | `turbo build` |
+| Build one package | `turbo build --filter=web` |
+| Multiple tasks | `turbo build lint test` |
+| Pass args to script | `turbo build -- --arg` |
+| Preview run | `turbo build --dry` |
+| Force rebuild | `turbo build --force` |
diff --git a/.agents/skills/turborepo/references/cli/commands.md b/.agents/skills/turborepo/references/cli/commands.md
new file mode 100644
index 00000000..1e872d12
--- /dev/null
+++ b/.agents/skills/turborepo/references/cli/commands.md
@@ -0,0 +1,297 @@
+# turbo run Flags Reference
+
+Full docs: https://turborepo.dev/docs/reference/run
+
+## Package Selection
+
+### `--filter` / `-F`
+
+Select specific packages to run tasks in.
+
+```bash
+turbo build --filter=web
+turbo build -F=@repo/ui -F=@repo/utils
+turbo test --filter=./apps/*
+```
+
+See `filtering/` for complete syntax (globs, dependencies, git ranges).
+
+### Task Identifier Syntax (v2.2.4+)
+
+Run specific package tasks directly:
+
+```bash
+turbo run web#build # Build web package
+turbo run web#build docs#lint # Multiple specific tasks
+```
+
+### `--affected`
+
+Run only in packages changed since the base branch.
+
+```bash
+turbo build --affected
+turbo test --affected --filter=./apps/* # combine with filter
+```
+
+**How it works:**
+
+- Default: compares `main...HEAD`
+- In GitHub Actions: auto-detects `GITHUB_BASE_REF`
+- Override base: `TURBO_SCM_BASE=development turbo build --affected`
+- Override head: `TURBO_SCM_HEAD=your-branch turbo build --affected`
+
+**Requires git history** - shallow clones may fall back to running all tasks.
+
+## Execution Control
+
+### `--dry` / `--dry=json`
+
+Preview what would run without executing.
+
+```bash
+turbo build --dry # human-readable
+turbo build --dry=json # machine-readable
+```
+
+### `--force`
+
+Ignore all cached artifacts, re-run everything.
+
+```bash
+turbo build --force
+```
+
+### `--concurrency`
+
+Limit parallel task execution.
+
+```bash
+turbo build --concurrency=4 # max 4 tasks
+turbo build --concurrency=50% # 50% of CPU cores
+```
+
+### `--continue`
+
+Keep running other tasks when one fails.
+
+```bash
+turbo build test --continue
+```
+
+### `--only`
+
+Run only the specified task, skip its dependencies.
+
+```bash
+turbo build --only # skip running dependsOn tasks
+```
+
+### `--parallel` (Discouraged)
+
+Ignores task graph dependencies, runs all tasks simultaneously. **Avoid using this flag**—if tasks need to run in parallel, configure `dependsOn` correctly instead. Using `--parallel` bypasses Turborepo's dependency graph, which can cause race conditions and incorrect builds.
+
+## Cache Control
+
+### `--cache`
+
+Fine-grained cache behavior control.
+
+```bash
+# Default: read/write both local and remote
+turbo build --cache=local:rw,remote:rw
+
+# Read-only local, no remote
+turbo build --cache=local:r,remote:
+
+# Disable local, read-only remote
+turbo build --cache=local:,remote:r
+
+# Disable all caching
+turbo build --cache=local:,remote:
+```
+
+## Output & Debugging
+
+### `--graph`
+
+Generate task graph visualization.
+
+```bash
+turbo build --graph # opens in browser
+turbo build --graph=graph.svg # SVG file
+turbo build --graph=graph.png # PNG file
+turbo build --graph=graph.json # JSON data
+turbo build --graph=graph.mermaid # Mermaid diagram
+```
+
+### `--summarize`
+
+Generate JSON run summary for debugging.
+
+```bash
+turbo build --summarize
+# creates .turbo/runs/<run-id>.json
+```
+
+### `--output-logs`
+
+Control log output verbosity.
+
+```bash
+turbo build --output-logs=full # all logs (default)
+turbo build --output-logs=new-only # only cache misses
+turbo build --output-logs=errors-only # only failures
+turbo build --output-logs=none # silent
+```
+
+### `--profile`
+
+Generate Chrome tracing profile for performance analysis.
+
+```bash
+turbo build --profile=profile.json
+# open chrome://tracing and load the file
+```
+
+### `--verbosity` / `-v`
+
+Control turbo's own log level.
+
+```bash
+turbo build -v # verbose
+turbo build -vv # more verbose
+turbo build -vvv # maximum verbosity
+```
+
+## Environment
+
+### `--env-mode`
+
+Control environment variable handling.
+
+```bash
+turbo build --env-mode=strict # only declared env vars (default)
+turbo build --env-mode=loose # include all env vars in hash
+```
+
+## UI
+
+### `--ui`
+
+Select output interface.
+
+```bash
+turbo build --ui=tui # interactive terminal UI (default in TTY)
+turbo build --ui=stream # streaming logs (default in CI)
+```
+
+---
+
+# turbo-ignore
+
+Full docs: https://turborepo.dev/docs/reference/turbo-ignore
+
+Skip CI work when nothing relevant changed. Useful for skipping container setup.
+
+## Basic Usage
+
+```bash
+# Check if build is needed for current package (uses Automatic Package Scoping)
+npx turbo-ignore
+
+# Check specific package
+npx turbo-ignore web
+
+# Check specific task
+npx turbo-ignore --task=test
+```
+
+## Exit Codes
+
+- `0`: No changes detected - skip CI work
+- `1`: Changes detected - proceed with CI
+
+## CI Integration Example
+
+```yaml
+# GitHub Actions
+- name: Check for changes
+ id: turbo-ignore
+ run: npx turbo-ignore web
+ continue-on-error: true
+
+- name: Build
+ if: steps.turbo-ignore.outcome == 'failure' # changes detected
+ run: pnpm build
+```
+
+## Comparison Depth
+
+Default: compares to parent commit (`HEAD^1`).
+
+```bash
+# Compare to specific commit
+npx turbo-ignore --fallback=abc123
+
+# Compare to branch
+npx turbo-ignore --fallback=main
+```
+
+---
+
+# Other Commands
+
+## turbo boundaries
+
+Check workspace violations (experimental).
+
+```bash
+turbo boundaries
+```
+
+See `references/boundaries/` for configuration.
+
+## turbo watch
+
+Re-run tasks on file changes.
+
+```bash
+turbo watch build test
+```
+
+See `references/watch/` for details.
+
+## turbo prune
+
+Create sparse checkout for Docker.
+
+```bash
+turbo prune web --docker
+```
+
+## turbo link / unlink
+
+Connect/disconnect Remote Cache.
+
+```bash
+turbo link # connect to Vercel Remote Cache
+turbo unlink # disconnect
+```
+
+## turbo login / logout
+
+Authenticate with Remote Cache provider.
+
+```bash
+turbo login # authenticate
+turbo logout # log out
+```
+
+## turbo generate
+
+Scaffold new packages.
+
+```bash
+turbo generate
+```
diff --git a/.agents/skills/turborepo/references/configuration/RULE.md b/.agents/skills/turborepo/references/configuration/RULE.md
new file mode 100644
index 00000000..32a72353
--- /dev/null
+++ b/.agents/skills/turborepo/references/configuration/RULE.md
@@ -0,0 +1,240 @@
+# turbo.json Configuration Overview
+
+Configuration reference for Turborepo. Full docs: https://turborepo.dev/docs/reference/configuration
+
+## File Location
+
+Root `turbo.json` lives at repo root, sibling to root `package.json`:
+
+```
+my-monorepo/
+├── turbo.json # Root configuration
+├── package.json
+└── packages/
+ └── web/
+ ├── turbo.json # Package Configuration (optional)
+ └── package.json
+```
+
+## Always Prefer Package Tasks Over Root Tasks
+
+**Always use package tasks. Only use Root Tasks if you cannot succeed with package tasks.**
+
+Package tasks enable parallelization, individual caching, and filtering. Define scripts in each package's `package.json`:
+
+```json
+// packages/web/package.json
+{
+ "scripts": {
+ "build": "next build",
+ "lint": "eslint .",
+ "test": "vitest",
+ "typecheck": "tsc --noEmit"
+ }
+}
+
+// packages/api/package.json
+{
+ "scripts": {
+ "build": "tsc",
+ "lint": "eslint .",
+ "test": "vitest",
+ "typecheck": "tsc --noEmit"
+ }
+}
+```
+
+```json
+// Root package.json - delegates to turbo
+{
+ "scripts": {
+ "build": "turbo run build",
+ "lint": "turbo run lint",
+ "test": "turbo run test",
+ "typecheck": "turbo run typecheck"
+ }
+}
+```
+
+When you run `turbo run lint`, Turborepo finds all packages with a `lint` script and runs them **in parallel**.
+
+**Root Tasks are a fallback**, not the default. Only use them for tasks that truly cannot run per-package (e.g., repo-level CI scripts, workspace-wide config generation).
+
+```json
+// AVOID: Task logic in root defeats parallelization
+{
+ "scripts": {
+ "lint": "eslint apps/web && eslint apps/api && eslint packages/ui"
+ }
+}
+```
+
+## Basic Structure
+
+```json
+{
+ "$schema": "https://v2-10-8-canary-4.turborepo.dev/schema.json",
+ "globalEnv": ["CI"],
+ "globalDependencies": ["tsconfig.json"],
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**"]
+ },
+ "dev": {
+ "cache": false,
+ "persistent": true
+ }
+ }
+}
+```
+
+The `$schema` key enables IDE autocompletion and validation.
+
+### With `futureFlags.globalConfiguration`
+
+When the `globalConfiguration` future flag is enabled, global options move under a `global` key with cleaner names:
+
+```json
+{
+ "$schema": "https://v2-10-8-canary-4.turborepo.dev/schema.json",
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "inputs": ["tsconfig.json"],
+ "env": ["CI"],
+ "ui": "tui"
+ },
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**"]
+ }
+ }
+}
+```
+
+See the [global options reference](./global-options.md) for the full rename mapping and behavior changes.
+
+## Configuration Sections
+
+**Global options** - Settings affecting all tasks:
+
+- Without flag: `globalEnv`, `globalDependencies`, `globalPassThroughEnv`, `cacheDir`, `daemon`, `envMode`, `ui`, `remoteCache`
+- With `globalConfiguration` flag: all of the above move under the `global` key (see [global options](./global-options.md))
+
+**Task definitions** - Per-task settings in `tasks` object:
+
+- `dependsOn`, `outputs`, `inputs`, `env`
+- `cache`, `persistent`, `interactive`, `outputLogs`
+
+## Package Configurations
+
+Use `turbo.json` in individual packages to override root settings:
+
+```json
+// packages/web/turbo.json
+{
+ "extends": ["//"],
+ "tasks": {
+ "build": {
+ "outputs": [".next/**", "!.next/cache/**", "!.next/dev/**"]
+ }
+ }
+}
+```
+
+The `"extends": ["//"]` is required - it references the root configuration.
+
+**When to use Package Configurations:**
+
+- Framework-specific outputs (Next.js, Vite, etc.)
+- Package-specific env vars
+- Different caching rules for specific packages
+- Keeping framework config close to the framework code
+
+### Extending from Other Packages
+
+You can extend from config packages instead of just root:
+
+```json
+// packages/web/turbo.json
+{
+ "extends": ["//", "@repo/turbo-config"]
+}
+```
+
+### Adding to Inherited Arrays with `$TURBO_EXTENDS$`
+
+By default, array fields in Package Configurations **replace** root values. Use `$TURBO_EXTENDS$` to **append** instead:
+
+```json
+// Root turbo.json
+{
+ "tasks": {
+ "build": {
+ "outputs": ["dist/**"]
+ }
+ }
+}
+```
+
+```json
+// packages/web/turbo.json
+{
+ "extends": ["//"],
+ "tasks": {
+ "build": {
+ // Inherits "dist/**" from root, adds ".next/**"
+ "outputs": [
+ "$TURBO_EXTENDS$",
+ ".next/**",
+ "!.next/cache/**",
+ "!.next/dev/**"
+ ]
+ }
+ }
+}
+```
+
+Without `$TURBO_EXTENDS$`, outputs would only be `[".next/**", "!.next/cache/**", "!.next/dev/**"]`.
+
+**Works with:**
+
+- `dependsOn`
+- `env`
+- `inputs`
+- `outputs`
+- `passThroughEnv`
+- `with`
+
+### Excluding Tasks from Packages
+
+Use `extends: false` to exclude a task from a package:
+
+```json
+// packages/ui/turbo.json
+{
+ "extends": ["//"],
+ "tasks": {
+ "e2e": {
+ "extends": false // UI package doesn't have e2e tests
+ }
+ }
+}
+```
+
+## `turbo.jsonc` for Comments
+
+Use `turbo.jsonc` extension to add comments with IDE support:
+
+```jsonc
+// turbo.jsonc
+{
+ "tasks": {
+ "build": {
+ // Next.js outputs
+ "outputs": [".next/**", "!.next/cache/**", "!.next/dev/**"]
+ }
+ }
+}
+```
diff --git a/.agents/skills/turborepo/references/configuration/global-options.md b/.agents/skills/turborepo/references/configuration/global-options.md
new file mode 100644
index 00000000..62ffef95
--- /dev/null
+++ b/.agents/skills/turborepo/references/configuration/global-options.md
@@ -0,0 +1,239 @@
+# Global Options Reference
+
+Options that affect all tasks. Full docs: https://turborepo.dev/docs/reference/configuration
+
+## globalEnv
+
+Environment variables affecting all task hashes.
+
+```json
+{
+ "globalEnv": ["CI", "NODE_ENV", "VERCEL_*"]
+}
+```
+
+Use for variables that should invalidate all caches when changed.
+
+## globalDependencies
+
+Files that affect all task hashes.
+
+```json
+{
+ "globalDependencies": ["tsconfig.json", ".env", "pnpm-lock.yaml"]
+}
+```
+
+Lockfile is included by default. Add shared configs here.
+
+## globalPassThroughEnv
+
+Variables available to tasks but not included in hash.
+
+```json
+{
+ "globalPassThroughEnv": ["AWS_SECRET_KEY", "GITHUB_TOKEN"]
+}
+```
+
+Use for credentials that shouldn't affect cache keys.
+
+## cacheDir
+
+Custom cache location. Default: `node_modules/.cache/turbo`.
+
+```json
+{
+ "cacheDir": ".turbo/cache"
+}
+```
+
+## daemon
+
+**Deprecated**: The daemon is no longer used for `turbo run` and this option will be removed in version 3.0. The daemon is still used by `turbo watch` and the Turborepo LSP.
+
+## envMode
+
+How unspecified env vars are handled. Default: `"strict"`.
+
+```json
+{
+ "envMode": "strict" // Only specified vars available
+ // or
+ "envMode": "loose" // All vars pass through
+}
+```
+
+Strict mode catches missing env declarations.
+
+## ui
+
+Terminal UI mode. Default: `"stream"`.
+
+```json
+{
+ "ui": "tui" // Interactive terminal UI
+ // or
+ "ui": "stream" // Traditional streaming logs
+}
+```
+
+TUI provides better UX for parallel tasks.
+
+## remoteCache
+
+Configure remote caching.
+
+```json
+{
+ "remoteCache": {
+ "enabled": true,
+ "signature": true,
+ "timeout": 30,
+ "uploadTimeout": 60
+ }
+}
+```
+
+| Option | Default | Description |
+| --------------- | ---------------------- | ------------------------------------------------------ |
+| `enabled` | `true` | Enable/disable remote caching |
+| `signature` | `false` | Sign artifacts with `TURBO_REMOTE_CACHE_SIGNATURE_KEY` |
+| `preflight` | `false` | Send OPTIONS request before cache requests |
+| `timeout` | `30` | Timeout in seconds for cache operations |
+| `uploadTimeout` | `60` | Timeout in seconds for uploads |
+| `apiUrl` | `"https://vercel.com"` | Remote cache API endpoint |
+| `loginUrl` | `"https://vercel.com"` | Login endpoint |
+| `teamId` | - | Team ID (must start with `team_`) |
+| `teamSlug` | - | Team slug for querystring |
+
+See https://turborepo.dev/docs/core-concepts/remote-caching for setup.
+
+## concurrency
+
+Default: `"10"`
+
+Limit parallel task execution.
+
+```json
+{
+ "concurrency": "4" // Max 4 tasks at once
+ // or
+ "concurrency": "50%" // 50% of available CPUs
+}
+```
+
+## futureFlags
+
+Enable experimental features that will become default in future versions.
+
+```json
+{
+ "futureFlags": {
+ "errorsOnlyShowHash": true
+ }
+}
+```
+
+### `errorsOnlyShowHash`
+
+When using `outputLogs: "errors-only"`, show task hashes on start/completion:
+
+- Cache miss: `cache miss, executing <hash> (only logging errors)`
+- Cache hit: `cache hit, replaying logs (no errors) <hash>`
+
+### `longerSignatureKey`
+
+Enforce a minimum key length of 32 bytes for `TURBO_REMOTE_CACHE_SIGNATURE_KEY` when `remoteCache.signature` is enabled. Short keys weaken HMAC-SHA256 signatures. Fails the run immediately if the key is too short.
+
+### `globalConfiguration`
+
+Moves global configuration keys under a top-level `global` key for clarity and changes how `global.inputs` (formerly `globalDependencies`) affects task hashing.
+
+When enabled:
+
+- Global config keys move under `global` with cleaner names
+- `global.inputs` files are **prepended to every task's inputs** instead of being folded into the global hash — tasks can opt out of specific global inputs using negation globs
+
+```json
+{
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "inputs": ["tsconfig.json", ".env"],
+ "env": ["CI", "NODE_ENV"],
+ "passThroughEnv": ["AWS_SECRET_KEY"],
+ "ui": "tui",
+ "envMode": "strict",
+ "cacheDir": ".turbo/cache",
+ "remoteCache": { "enabled": true },
+ "concurrency": "50%"
+ },
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**"]
+ }
+ }
+}
+```
+
+**Key rename mapping:**
+
+| Old (top-level) | New (`global.`) |
+| -------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
+| `globalDependencies` | `inputs` |
+| `globalEnv` | `env` |
+| `globalPassThroughEnv` | `passThroughEnv` |
+| `ui`, `envMode`, `cacheDir`, `daemon`, `concurrency`, `noUpdateNotifier`, `dangerouslyDisablePackageManagerCheck`, `remoteCache` | Same names under `global` |
+
+**Behavior change for `global.inputs`:**
+
+With `globalDependencies` (old): files are hashed into the **global hash**, which is embedded in every task's cache key. Changing any of these files invalidates all tasks — there is no opt-out.
+
+With `global.inputs` (new): files are treated as **implicit task inputs** prepended to each task's `inputs` globs. This means:
+
+- Tasks can exclude specific global files: `"inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/tsconfig.json"]`
+- The global hash no longer includes these file hashes (it still includes lockfile, engines, global env, etc.)
+- Tasks with no explicit `inputs` still hash all package files plus the global inputs
+
+See the [gotchas doc](./gotchas.md) for guidance on using `$TURBO_DEFAULT$` with `global.inputs`.
+
+## noUpdateNotifier
+
+Disable update notifications when new turbo versions are available.
+
+```json
+{
+ "noUpdateNotifier": true
+}
+```
+
+## dangerouslyDisablePackageManagerCheck
+
+Bypass the `packageManager` field requirement. Use for incremental migration.
+
+```json
+{
+ "dangerouslyDisablePackageManagerCheck": true
+}
+```
+
+**Warning**: Unstable lockfiles can cause unpredictable behavior.
+
+## Git Worktree Cache Sharing
+
+When working in Git worktrees, Turborepo automatically shares local cache between the main worktree and linked worktrees.
+
+**How it works:**
+
+- Detects worktree configuration
+- Redirects cache to main worktree's `.turbo/cache`
+- Works alongside Remote Cache
+
+**Benefits:**
+
+- Cache hits across branches
+- Reduced disk usage
+- Faster branch switching
+
+**Disabled by**: Setting explicit `cacheDir` in turbo.json.
diff --git a/.agents/skills/turborepo/references/configuration/gotchas.md b/.agents/skills/turborepo/references/configuration/gotchas.md
new file mode 100644
index 00000000..3bd88ead
--- /dev/null
+++ b/.agents/skills/turborepo/references/configuration/gotchas.md
@@ -0,0 +1,368 @@
+# Configuration Gotchas
+
+Common mistakes and how to fix them.
+
+## #1 Root Scripts Not Using `turbo run`
+
+Root `package.json` scripts for turbo tasks MUST use `turbo run`, not direct commands.
+
+```json
+// WRONG - bypasses turbo, no parallelization or caching
+{
+ "scripts": {
+ "build": "bun build",
+ "dev": "bun dev"
+ }
+}
+
+// CORRECT - delegates to turbo
+{
+ "scripts": {
+ "build": "turbo run build",
+ "dev": "turbo run dev"
+ }
+}
+```
+
+**Why this matters:** Running `bun build` or `npm run build` at root bypasses Turborepo entirely - no parallelization, no caching, no dependency graph awareness.
+
+## #2 Using `&&` to Chain Turbo Tasks
+
+Don't use `&&` to chain tasks that turbo should orchestrate.
+
+```json
+// WRONG - changeset:publish chains turbo task with non-turbo command
+{
+ "scripts": {
+ "changeset:publish": "bun build && changeset publish"
+ }
+}
+
+// CORRECT - use turbo run, let turbo handle dependencies
+{
+ "scripts": {
+ "changeset:publish": "turbo run build && changeset publish"
+ }
+}
+```
+
+If the second command (`changeset publish`) depends on build outputs, the turbo task should run through turbo to get caching and parallelization benefits.
+
+## #3 Overly Broad globalDependencies
+
+`globalDependencies` affects hash for ALL tasks in ALL packages. Be specific.
+
+```json
+// WRONG - affects all hashes
+{
+ "globalDependencies": ["**/.env.*local"]
+}
+
+// CORRECT - move to specific tasks that need it
+{
+ "globalDependencies": [".env"],
+ "tasks": {
+ "build": {
+ "inputs": ["$TURBO_DEFAULT$", ".env*"],
+ "outputs": ["dist/**"]
+ }
+ }
+}
+```
+
+**Why this matters:** `**/.env.*local` matches .env files in ALL packages, causing unnecessary cache invalidation. Instead:
+
+- Use `globalDependencies` only for truly global files (root `.env`)
+- Use task-level `inputs` for package-specific .env files with `$TURBO_DEFAULT$` to preserve default behavior
+
+With `futureFlags.globalConfiguration`, this is less of a concern because `global.inputs` acts as implicit task inputs — tasks can opt out of specific files with negation globs. But keeping the list focused is still good practice.
+
+## #4 Repetitive Task Configuration
+
+Look for repeated configuration across tasks that can be collapsed.
+
+```json
+// WRONG - repetitive env and inputs across tasks
+{
+ "tasks": {
+ "build": {
+ "env": ["API_URL", "DATABASE_URL"],
+ "inputs": ["$TURBO_DEFAULT$", ".env*"]
+ },
+ "test": {
+ "env": ["API_URL", "DATABASE_URL"],
+ "inputs": ["$TURBO_DEFAULT$", ".env*"]
+ }
+ }
+}
+
+// BETTER - use globalEnv and globalDependencies
+{
+ "globalEnv": ["API_URL", "DATABASE_URL"],
+ "globalDependencies": [".env*"],
+ "tasks": {
+ "build": {},
+ "test": {}
+ }
+}
+```
+
+**When to use global vs task-level:**
+
+- `globalEnv` / `globalDependencies` - affects ALL tasks, use for truly shared config
+- Task-level `env` / `inputs` - use when only specific tasks need it
+
+## #5 Using `../` to Traverse Out of Package in `inputs`
+
+Don't use relative paths like `../` to reference files outside the package. Use `$TURBO_ROOT$` instead.
+
+```json
+// WRONG - traversing out of package
+{
+ "tasks": {
+ "build": {
+ "inputs": ["$TURBO_DEFAULT$", "../shared-config.json"]
+ }
+ }
+}
+
+// CORRECT - use $TURBO_ROOT$ for repo root
+{
+ "tasks": {
+ "build": {
+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/shared-config.json"]
+ }
+ }
+}
+```
+
+## #6 MOST COMMON MISTAKE: Creating Root Tasks
+
+**Prefer package tasks over Root Tasks.**
+
+When you need to create a task (build, lint, test, typecheck, etc.), default to package tasks:
+
+1. Add the script to **each relevant package's** `package.json`
+2. Register the task in root `turbo.json`
+3. Root `package.json` only contains `turbo run <task>`
+
+```json
+// WRONG - DO NOT DO THIS
+// Root package.json with task logic
+{
+ "scripts": {
+ "build": "cd apps/web && next build && cd ../api && tsc",
+ "lint": "eslint apps/ packages/",
+ "test": "vitest"
+ }
+}
+
+// CORRECT - DO THIS
+// apps/web/package.json
+{ "scripts": { "build": "next build", "lint": "eslint .", "test": "vitest" } }
+
+// apps/api/package.json
+{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
+
+// packages/ui/package.json
+{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
+
+// Root package.json - ONLY delegates
+{ "scripts": { "build": "turbo run build", "lint": "turbo run lint", "test": "turbo run test" } }
+
+// turbo.json - register tasks
+{
+ "tasks": {
+ "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] },
+ "lint": {},
+ "test": {}
+ }
+}
+```
+
+**Why this matters:**
+
+- Package tasks run in **parallel** across all packages
+- Each package's output is cached **individually**
+- You can **filter** to specific packages: `turbo run test --filter=web`
+
+Root Tasks (`//#taskname`) defeat all these benefits when a task can live in packages. Only use them for tasks that truly cannot exist in any package, such as Vitest Projects' `//#test`, repo-wide release scripts, or tooling that does not invoke `turbo` itself.
+
+## #7 Tasks That Need Parallel Execution + Cache Invalidation
+
+Some tasks can run in parallel (don't need built output from dependencies) but must still invalidate cache when dependency source code changes. Using `dependsOn: ["^taskname"]` forces sequential execution. Using no dependencies breaks cache invalidation.
+
+**Use Transit Nodes for these tasks:**
+
+```json
+// WRONG - forces sequential execution (SLOW)
+"my-task": {
+ "dependsOn": ["^my-task"]
+}
+
+// ALSO WRONG - no dependency awareness (INCORRECT CACHING)
+"my-task": {}
+
+// CORRECT - use Transit Nodes for parallel + correct caching
+{
+ "tasks": {
+ "transit": { "dependsOn": ["^transit"] },
+ "my-task": { "dependsOn": ["transit"] }
+ }
+}
+```
+
+**Why Transit Nodes work:**
+
+- `transit` creates dependency relationships without matching any actual script
+- Tasks that depend on `transit` gain dependency awareness
+- Since `transit` completes instantly (no script), tasks run in parallel
+- Cache correctly invalidates when dependency source code changes
+
+**How to identify tasks that need this pattern:** Look for tasks that read source files from dependencies but don't need their build outputs.
+
+## Missing outputs for File-Producing Tasks
+
+**Before flagging missing `outputs`, check what the task actually produces:**
+
+1. Read the package's script (e.g., `"build": "tsc"`, `"test": "vitest"`)
+2. Determine if it writes files to disk or only outputs to stdout
+3. Only flag if the task produces files that should be cached
+
+```json
+// WRONG - build produces files but they're not cached
+"build": {
+ "dependsOn": ["^build"]
+}
+
+// CORRECT - outputs are cached
+"build": {
+ "dependsOn": ["^build"],
+ "outputs": ["dist/**"]
+}
+```
+
+No `outputs` key is fine for stdout-only tasks. For file-producing tasks, missing `outputs` means Turbo has nothing to cache.
+
+## Forgetting ^ in dependsOn
+
+```json
+// WRONG - looks for "build" in SAME package (infinite loop or missing)
+"build": {
+ "dependsOn": ["build"]
+}
+
+// CORRECT - runs dependencies' build first
+"build": {
+ "dependsOn": ["^build"]
+}
+```
+
+The `^` means "in dependency packages", not "in this package".
+
+## Missing persistent on Dev Tasks
+
+```json
+// WRONG - dependent tasks hang waiting for dev to "finish"
+"dev": {
+ "cache": false
+}
+
+// CORRECT
+"dev": {
+ "cache": false,
+ "persistent": true
+}
+```
+
+## Package Config Missing extends
+
+```json
+// WRONG - packages/web/turbo.json
+{
+ "tasks": {
+ "build": { "outputs": [".next/**"] }
+ }
+}
+
+// CORRECT
+{
+ "extends": ["//"],
+ "tasks": {
+ "build": { "outputs": [".next/**"] }
+ }
+}
+```
+
+Without `"extends": ["//"]`, Package Configurations are invalid.
+
+## Root Tasks Need Special Syntax
+
+To run a task defined only in root `package.json`:
+
+```bash
+# WRONG
+turbo run format
+
+# CORRECT
+turbo run //#format
+```
+
+And in dependsOn:
+
+```json
+"build": {
+ "dependsOn": ["//#codegen"] // Root package's codegen
+}
+```
+
+## Overwriting Default Inputs
+
+```json
+// WRONG - only watches test files, ignores source changes
+"test": {
+ "inputs": ["tests/**"]
+}
+
+// CORRECT - extends defaults, adds test files
+"test": {
+ "inputs": ["$TURBO_DEFAULT$", "tests/**"]
+}
+```
+
+Without `$TURBO_DEFAULT$`, you replace all default file watching.
+
+## Excluding `global.inputs` Without `$TURBO_DEFAULT$`
+
+When using `futureFlags.globalConfiguration`, `global.inputs` values are prepended to every task's inputs. If you want to exclude a global input from a specific task, you **must** include `$TURBO_DEFAULT$` to preserve default file hashing.
+
+```json
+// WRONG - task hashes NO files at all (global input cancelled, no defaults)
+"build": {
+ "inputs": ["!$TURBO_ROOT$/config.txt"]
+}
+
+// CORRECT - task hashes all package files, minus config.txt
+"build": {
+ "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/config.txt"]
+}
+```
+
+Without `$TURBO_DEFAULT$`, the only inclusion glob comes from `global.inputs`, which the negation cancels out. The task ends up with no inclusions and no default file hashing, so it hashes nothing. Changes to source files won't cause cache misses.
+
+## Caching Tasks with Side Effects
+
+```json
+// WRONG - deploy might be skipped on cache hit
+"deploy": {
+ "dependsOn": ["build"]
+}
+
+// CORRECT
+"deploy": {
+ "dependsOn": ["build"],
+ "cache": false
+}
+```
+
+Always disable cache for deploy, publish, or mutation tasks.
diff --git a/.agents/skills/turborepo/references/configuration/tasks.md b/.agents/skills/turborepo/references/configuration/tasks.md
new file mode 100644
index 00000000..dffe71f7
--- /dev/null
+++ b/.agents/skills/turborepo/references/configuration/tasks.md
@@ -0,0 +1,325 @@
+# Task Configuration Reference
+
+Full docs: https://turborepo.dev/docs/reference/configuration#tasks
+
+## dependsOn
+
+Controls task execution order.
+
+```json
+{
+ "tasks": {
+ "build": {
+ "dependsOn": [
+ "^build", // Dependencies' build tasks first
+ "codegen", // Same package's codegen task first
+ "shared#build" // Specific package's build task
+ ]
+ }
+ }
+}
+```
+
+| Syntax | Meaning |
+| ---------- | ------------------------------------ |
+| `^task` | Run `task` in all dependencies first |
+| `task` | Run `task` in same package first |
+| `pkg#task` | Run specific package's task first |
+
+The `^` prefix is crucial - without it, you're referencing the same package.
+
+### Transit Nodes for Parallel Tasks
+
+For tasks like `lint` and `check-types` that can run in parallel but need dependency-aware caching:
+
+```json
+{
+ "tasks": {
+ "transit": { "dependsOn": ["^transit"] },
+ "lint": { "dependsOn": ["transit"] },
+ "check-types": { "dependsOn": ["transit"] }
+ }
+}
+```
+
+**DO NOT use `dependsOn: ["^lint"]`** - this forces sequential execution.
+**DO NOT use `dependsOn: []`** - this breaks cache invalidation.
+
+The `transit` task creates dependency relationships without running anything (no matching script), so tasks run in parallel with correct caching.
+
+## outputs
+
+Glob patterns for files to cache. **If omitted, nothing is cached.**
+
+```json
+{
+ "tasks": {
+ "build": {
+ "outputs": ["dist/**", "build/**"]
+ }
+ }
+}
+```
+
+**Framework examples:**
+
+```json
+// Next.js
+"outputs": [".next/**", "!.next/cache/**", "!.next/dev/**"]
+
+// Vite
+"outputs": ["dist/**"]
+
+// TypeScript (tsc)
+"outputs": ["dist/**", "*.tsbuildinfo"]
+
+// No file outputs (lint, typecheck)
+"outputs": []
+```
+
+Use `!` prefix to exclude patterns from caching.
+
+## inputs
+
+Files considered when calculating task hash. Defaults to all tracked files in package.
+
+```json
+{
+ "tasks": {
+ "test": {
+ "inputs": ["src/**", "tests/**", "vitest.config.ts"]
+ }
+ }
+}
+```
+
+**Special values:**
+
+| Value | Meaning |
+| --------------------- | --------------------------------------- |
+| `$TURBO_DEFAULT$` | Include default inputs, then add/remove |
+| `$TURBO_ROOT$/<path>` | Reference files from repo root |
+
+```json
+{
+ "tasks": {
+ "build": {
+ "inputs": [
+ "$TURBO_DEFAULT$",
+ "!README.md",
+ "$TURBO_ROOT$/tsconfig.base.json"
+ ]
+ }
+ }
+}
+```
+
+### Interaction with `global.inputs`
+
+When `futureFlags.globalConfiguration` is enabled, files listed in `global.inputs` are prepended to every task's `inputs`. The combined list is then used to compute the task hash.
+
+This is different from `globalDependencies`, where files were hashed into the **global** hash and could not be influenced by task-level `inputs`.
+
+**With `globalDependencies` (old behavior):**
+
+- `globalDependencies` files contribute to the global hash
+- Task `inputs` only control which **package** files are hashed
+- There is no way for a task to "opt out" of a `globalDependencies` file
+
+**With `global.inputs` (new behavior):**
+
+- `global.inputs` files are merged into each task's `inputs` globs
+- Task `inputs` and `global.inputs` are combined, then the full list is hashed into the **task** hash
+- Tasks can exclude specific global files with negation globs
+
+```json
+{
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "inputs": ["tsconfig.json", ".env"]
+ },
+ "tasks": {
+ "build": {},
+ "lint": {
+ "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/.env"]
+ }
+ }
+}
+```
+
+In this example:
+
+- `build` hashes all package files + `tsconfig.json` + `.env` (from `global.inputs`)
+- `lint` hashes all package files + `tsconfig.json`, but **excludes** `.env` because of the negation glob
+
+Tasks with no explicit `inputs` key still hash all package files (the default behavior) plus the `global.inputs` files.
+
+## env
+
+Environment variables to include in task hash.
+
+```json
+{
+ "tasks": {
+ "build": {
+ "env": [
+ "API_URL",
+ "NEXT_PUBLIC_*", // Wildcard matching
+ "!DEBUG" // Exclude from hash
+ ]
+ }
+ }
+}
+```
+
+Variables listed here affect cache hits - changing the value invalidates cache.
+
+## cache
+
+Enable/disable caching for a task. Default: `true`.
+
+```json
+{
+ "tasks": {
+ "dev": { "cache": false },
+ "deploy": { "cache": false }
+ }
+}
+```
+
+Disable for: dev servers, deploy commands, tasks with side effects.
+
+## persistent
+
+Mark long-running tasks that don't exit. Default: `false`.
+
+```json
+{
+ "tasks": {
+ "dev": {
+ "cache": false,
+ "persistent": true
+ }
+ }
+}
+```
+
+Required for dev servers - without it, dependent tasks wait forever.
+
+## interactive
+
+Allow task to receive stdin input. Default: `false`.
+
+```json
+{
+ "tasks": {
+ "login": {
+ "cache": false,
+ "interactive": true
+ }
+ }
+}
+```
+
+## outputLogs
+
+Control when logs are shown. Options: `full`, `hash-only`, `new-only`, `errors-only`, `none`.
+
+```json
+{
+ "tasks": {
+ "build": {
+ "outputLogs": "new-only" // Only show logs on cache miss
+ }
+ }
+}
+```
+
+## with
+
+Run tasks alongside this task. For long-running tasks that need runtime dependencies.
+
+```json
+{
+ "tasks": {
+ "dev": {
+ "with": ["api#dev"],
+ "persistent": true,
+ "cache": false
+ }
+ }
+}
+```
+
+Unlike `dependsOn`, `with` runs tasks concurrently (not sequentially). Use for dev servers that need other services running.
+
+## interruptible
+
+Allow `turbo watch` to restart the task on changes. Default: `false`.
+
+```json
+{
+ "tasks": {
+ "dev": {
+ "persistent": true,
+ "interruptible": true,
+ "cache": false
+ }
+ }
+}
+```
+
+Use for dev servers that don't automatically detect dependency changes.
+
+## description
+
+Human-readable description of the task.
+
+```json
+{
+ "tasks": {
+ "build": {
+ "description": "Compiles the application for production deployment"
+ }
+ }
+}
+```
+
+For documentation only - doesn't affect execution or caching.
+
+## passThroughEnv
+
+Environment variables available at runtime but NOT included in cache hash.
+
+```json
+{
+ "tasks": {
+ "build": {
+ "passThroughEnv": ["AWS_SECRET_KEY", "GITHUB_TOKEN"]
+ }
+ }
+}
+```
+
+**Warning**: Changes to these vars won't cause cache misses. Use `env` if changes should invalidate cache.
+
+## extends (Package Configuration only)
+
+Control task inheritance in Package Configurations.
+
+```json
+// packages/ui/turbo.json
+{
+ "extends": ["//"],
+ "tasks": {
+ "lint": {
+ "extends": false // Exclude from this package
+ }
+ }
+}
+```
+
+| Value | Behavior |
+| ---------------- | -------------------------------------------------------------- |
+| `true` (default) | Inherit from root turbo.json |
+| `false` | Exclude task from package, or define fresh without inheritance |
diff --git a/.agents/skills/turborepo/references/environment/RULE.md b/.agents/skills/turborepo/references/environment/RULE.md
new file mode 100644
index 00000000..be94a93a
--- /dev/null
+++ b/.agents/skills/turborepo/references/environment/RULE.md
@@ -0,0 +1,123 @@
+# Environment Variables in Turborepo
+
+Turborepo provides fine-grained control over which environment variables affect task hashing and runtime availability.
+
+## Configuration Keys
+
+### `env` - Task-Specific Variables
+
+Variables that affect a specific task's hash. When these change, only that task rebuilds.
+
+```json
+{
+ "tasks": {
+ "build": {
+ "env": ["DATABASE_URL", "API_KEY"]
+ }
+ }
+}
+```
+
+### `globalEnv` - Variables Affecting All Tasks
+
+Variables that affect EVERY task's hash. When these change, all tasks rebuild.
+
+```json
+{
+ "globalEnv": ["CI", "NODE_ENV"]
+}
+```
+
+### `passThroughEnv` - Runtime-Only Variables (Not Hashed)
+
+Variables available at runtime but NOT included in hash. **Use with caution** - changes won't trigger rebuilds.
+
+```json
+{
+ "tasks": {
+ "deploy": {
+ "passThroughEnv": ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"]
+ }
+ }
+}
+```
+
+### `globalPassThroughEnv` - Global Runtime Variables
+
+Same as `passThroughEnv` but for all tasks.
+
+```json
+{
+ "globalPassThroughEnv": ["GITHUB_TOKEN"]
+}
+```
+
+## Wildcards and Negation
+
+### Wildcards
+
+Match multiple variables with `*`:
+
+```json
+{
+ "env": ["MY_API_*", "FEATURE_FLAG_*"]
+}
+```
+
+This matches `MY_API_URL`, `MY_API_KEY`, `FEATURE_FLAG_DARK_MODE`, etc.
+
+### Negation
+
+Exclude variables (useful with framework inference):
+
+```json
+{
+ "env": ["!NEXT_PUBLIC_ANALYTICS_ID"]
+}
+```
+
+## With `futureFlags.globalConfiguration`
+
+When the `globalConfiguration` future flag is enabled, global environment keys move under the `global` key with cleaner names:
+
+| Old (top-level) | New (`global.`) |
+| ---------------------- | ---------------- |
+| `globalEnv` | `env` |
+| `globalPassThroughEnv` | `passThroughEnv` |
+
+`global.env` and `global.passThroughEnv` behave identically to their top-level counterparts — they affect the global hash and all tasks, respectively. The rename is purely organizational.
+
+```json
+{
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "env": ["CI", "NODE_ENV"],
+ "passThroughEnv": ["GITHUB_TOKEN", "NPM_TOKEN"]
+ },
+ "tasks": {
+ "build": {
+ "env": ["DATABASE_URL", "API_*"],
+ "passThroughEnv": ["SENTRY_AUTH_TOKEN"]
+ }
+ }
+}
+```
+
+## Complete Example
+
+```json
+{
+ "$schema": "https://v2-10-8-canary-4.turborepo.dev/schema.json",
+ "globalEnv": ["CI", "NODE_ENV"],
+ "globalPassThroughEnv": ["GITHUB_TOKEN", "NPM_TOKEN"],
+ "tasks": {
+ "build": {
+ "env": ["DATABASE_URL", "API_*"],
+ "passThroughEnv": ["SENTRY_AUTH_TOKEN"]
+ },
+ "test": {
+ "env": ["TEST_DATABASE_URL"]
+ }
+ }
+}
+```
diff --git a/.agents/skills/turborepo/references/environment/gotchas.md b/.agents/skills/turborepo/references/environment/gotchas.md
new file mode 100644
index 00000000..8190341f
--- /dev/null
+++ b/.agents/skills/turborepo/references/environment/gotchas.md
@@ -0,0 +1,175 @@
+# Environment Variable Gotchas
+
+Common mistakes and how to fix them.
+
+## .env Files Must Be in `inputs`
+
+Turbo does NOT read `.env` files. Your framework (Next.js, Vite, etc.) or `dotenv` loads them. But Turbo needs to know when they change.
+
+**Wrong:**
+
+```json
+{
+ "tasks": {
+ "build": {
+ "env": ["DATABASE_URL"]
+ }
+ }
+}
+```
+
+**Right:**
+
+```json
+{
+ "tasks": {
+ "build": {
+ "env": ["DATABASE_URL"],
+ "inputs": ["$TURBO_DEFAULT$", ".env", ".env.local", ".env.production"]
+ }
+ }
+}
+```
+
+## Strict Mode Filters CI Variables
+
+In strict mode, CI provider variables (GITHUB_TOKEN, GITLAB_CI, etc.) are filtered unless explicitly listed.
+
+**Symptom:** Task fails with "authentication required" or "permission denied" in CI.
+
+**Solution:**
+
+```json
+{
+ "globalPassThroughEnv": ["GITHUB_TOKEN", "GITLAB_CI", "CI"]
+}
+```
+
+## passThroughEnv Doesn't Affect Hash
+
+Variables in `passThroughEnv` are available at runtime but changes WON'T trigger rebuilds.
+
+**Dangerous example:**
+
+```json
+{
+ "tasks": {
+ "build": {
+ "passThroughEnv": ["API_URL"]
+ }
+ }
+}
+```
+
+If `API_URL` changes from staging to production, Turbo may serve a cached build pointing to the wrong API.
+
+**Use passThroughEnv only for:**
+
+- Auth tokens that don't affect output (SENTRY_AUTH_TOKEN)
+- CI metadata (GITHUB_RUN_ID)
+- Variables consumed after build (deploy credentials)
+
+## Runtime-Created Variables Are Invisible
+
+Turbo captures env vars at startup. Variables created during execution aren't seen.
+
+**Won't work:**
+
+```bash
+# In package.json scripts
+"build": "export API_URL=$COMPUTED_VALUE && next build"
+```
+
+**Solution:** Set vars before invoking turbo:
+
+```bash
+API_URL=$COMPUTED_VALUE turbo run build
+```
+
+## Different .env Files for Different Environments
+
+If you use `.env.development` and `.env.production`, both should be in inputs.
+
+```json
+{
+ "tasks": {
+ "build": {
+ "inputs": [
+ "$TURBO_DEFAULT$",
+ ".env",
+ ".env.local",
+ ".env.development",
+ ".env.development.local",
+ ".env.production",
+ ".env.production.local"
+ ]
+ }
+ }
+}
+```
+
+## Complete Next.js Example
+
+```json
+{
+ "$schema": "https://v2-10-8-canary-4.turborepo.dev/schema.json",
+ "globalEnv": ["CI", "NODE_ENV", "VERCEL"],
+ "globalPassThroughEnv": ["GITHUB_TOKEN", "VERCEL_URL"],
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "env": ["DATABASE_URL", "NEXT_PUBLIC_*", "!NEXT_PUBLIC_ANALYTICS_ID"],
+ "passThroughEnv": ["SENTRY_AUTH_TOKEN"],
+ "inputs": [
+ "$TURBO_DEFAULT$",
+ ".env",
+ ".env.local",
+ ".env.production",
+ ".env.production.local"
+ ],
+ "outputs": [".next/**", "!.next/cache/**", "!.next/dev/**"]
+ }
+ }
+}
+```
+
+This config:
+
+- Hashes DATABASE*URL and NEXT_PUBLIC*\* vars (except analytics)
+- Passes through SENTRY_AUTH_TOKEN without hashing
+- Includes all .env file variants in the hash
+- Makes CI tokens available globally
+
+### With `futureFlags.globalConfiguration`
+
+The same config using the `global` key. The `.env` files move to `global.inputs`, which means they get folded into each task's hash individually rather than the global hash. This lets tasks exclude specific `.env` files if needed.
+
+```json
+{
+ "$schema": "https://v2-10-8-canary-4.turborepo.dev/schema.json",
+ "futureFlags": { "globalConfiguration": true },
+ "global": {
+ "env": ["CI", "NODE_ENV", "VERCEL"],
+ "passThroughEnv": ["GITHUB_TOKEN", "VERCEL_URL"],
+ "inputs": [".env", ".env.local", ".env.production", ".env.production.local"]
+ },
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "env": ["DATABASE_URL", "NEXT_PUBLIC_*", "!NEXT_PUBLIC_ANALYTICS_ID"],
+ "passThroughEnv": ["SENTRY_AUTH_TOKEN"],
+ "outputs": [".next/**", "!.next/cache/**", "!.next/dev/**"]
+ }
+ }
+}
+```
+
+With this approach, a task that doesn't care about `.env.production` can exclude it:
+
+```json
+"lint": {
+ "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/.env.production"]
+}
+```
+
+This wouldn't have been possible with `globalDependencies`, where `.env.production` would be baked into the global hash and affect every task unconditionally.
diff --git a/.agents/skills/turborepo/references/environment/modes.md b/.agents/skills/turborepo/references/environment/modes.md
new file mode 100644
index 00000000..2e655331
--- /dev/null
+++ b/.agents/skills/turborepo/references/environment/modes.md
@@ -0,0 +1,101 @@
+# Environment Modes
+
+Turborepo supports different modes for handling environment variables during task execution.
+
+## Strict Mode (Default)
+
+Only explicitly configured variables are available to tasks.
+
+**Behavior:**
+
+- Tasks only see vars listed in `env`, `globalEnv`, `passThroughEnv`, or `globalPassThroughEnv`
+- Unlisted vars are filtered out
+- Tasks fail if they require unlisted variables
+
+**Benefits:**
+
+- Guarantees cache correctness
+- Prevents accidental dependencies on system vars
+- Reproducible builds across machines
+
+```bash
+# Explicit (though it's the default)
+turbo run build --env-mode=strict
+```
+
+## Loose Mode
+
+All system environment variables are available to tasks.
+
+```bash
+turbo run build --env-mode=loose
+```
+
+**Behavior:**
+
+- Every system env var is passed through
+- Only vars in `env`/`globalEnv` affect the hash
+- Other vars are available but NOT hashed
+
+**Risks:**
+
+- Cache may restore incorrect results if unhashed vars changed
+- "Works on my machine" bugs
+- CI vs local environment mismatches
+
+**Use case:** Migrating legacy projects or debugging strict mode issues.
+
+## Framework Inference (Automatic)
+
+Turborepo automatically detects frameworks and includes their conventional env vars.
+
+### Inferred Variables by Framework
+
+| Framework | Pattern |
+| ---------------- | ------------------- |
+| Next.js | `NEXT_PUBLIC_*` |
+| Vite | `VITE_*` |
+| Create React App | `REACT_APP_*` |
+| Gatsby | `GATSBY_*` |
+| Nuxt | `NUXT_*`, `NITRO_*` |
+| Expo | `EXPO_PUBLIC_*` |
+| Astro | `PUBLIC_*` |
+| SvelteKit | `PUBLIC_*` |
+| Remix | `REMIX_*` |
+| Redwood | `REDWOOD_ENV_*` |
+| Sanity | `SANITY_STUDIO_*` |
+| Solid | `VITE_*` |
+
+### Disabling Framework Inference
+
+Globally via CLI:
+
+```bash
+turbo run build --framework-inference=false
+```
+
+Or exclude specific patterns in config:
+
+```json
+{
+ "tasks": {
+ "build": {
+ "env": ["!NEXT_PUBLIC_*"]
+ }
+ }
+}
+```
+
+### Why Disable?
+
+- You want explicit control over all env vars
+- Framework vars shouldn't bust the cache (e.g., analytics IDs)
+- Debugging unexpected cache misses
+
+## Checking Environment Mode
+
+Use `--dry` to see which vars affect each task:
+
+```bash
+turbo run build --dry=json | jq '.tasks[].environmentVariables'
+```
diff --git a/.agents/skills/turborepo/references/filtering/RULE.md b/.agents/skills/turborepo/references/filtering/RULE.md
new file mode 100644
index 00000000..04e19cc8
--- /dev/null
+++ b/.agents/skills/turborepo/references/filtering/RULE.md
@@ -0,0 +1,148 @@
+# Turborepo Filter Syntax Reference
+
+## Running Only Changed Packages: `--affected`
+
+**The primary way to run only changed packages is `--affected`:**
+
+```bash
+# Run build/test/lint only in changed packages and their dependents
+turbo run build test lint --affected
+```
+
+This compares your current branch to the default branch (usually `main` or `master`) and runs tasks in:
+
+1. Packages with file changes
+2. Packages that depend on changed packages (dependents)
+
+### Why Include Dependents?
+
+If you change `@repo/ui`, packages that import `@repo/ui` (like `apps/web`) need to re-run their tasks to verify they still work with the changes.
+
+### Customizing --affected
+
+```bash
+# Use a different base branch
+turbo run build --affected --affected-base=origin/develop
+
+# Use a different head (current state)
+turbo run build --affected --affected-head=HEAD~5
+```
+
+### Common CI Pattern
+
+```yaml
+# .github/workflows/ci.yml
+- run: turbo run build test lint --affected
+```
+
+This is the most efficient CI setup - only run tasks for what actually changed.
+
+---
+
+## Manual Git Comparison with --filter
+
+For more control, use `--filter` with git comparison syntax:
+
+```bash
+# Changed packages + dependents (same as --affected)
+turbo run build --filter=...[origin/main]
+
+# Only changed packages (no dependents)
+turbo run build --filter=[origin/main]
+
+# Changed packages + dependencies (packages they import)
+turbo run build --filter=[origin/main]...
+
+# Changed since last commit
+turbo run build --filter=...[HEAD^1]
+
+# Changed between two commits
+turbo run build --filter=[a1b2c3d...e4f5g6h]
+```
+
+### Comparison Syntax
+
+| Syntax | Meaning |
+| ------------- | ------------------------------------- |
+| `[ref]` | Packages changed since `ref` |
+| `...[ref]` | Changed packages + their dependents |
+| `[ref]...` | Changed packages + their dependencies |
+| `...[ref]...` | Dependencies, changed, AND dependents |
+
+---
+
+## Other Filter Types
+
+Filters select which packages to include in a `turbo run` invocation.
+
+### Basic Syntax
+
+```bash
+turbo run build --filter=<package-name>
+turbo run build -F <package-name>
+```
+
+Multiple filters combine as a union (packages matching ANY filter run).
+
+### By Package Name
+
+```bash
+--filter=web # exact match
+--filter=@acme/* # scope glob
+--filter=*-app # name glob
+```
+
+### By Directory
+
+```bash
+--filter=./apps/* # all packages in apps/
+--filter=./packages/ui # specific directory
+```
+
+### By Dependencies/Dependents
+
+| Syntax | Meaning |
+| ----------- | -------------------------------------- |
+| `pkg...` | Package AND all its dependencies |
+| `...pkg` | Package AND all its dependents |
+| `...pkg...` | Dependencies, package, AND dependents |
+| `^pkg...` | Only dependencies (exclude pkg itself) |
+| `...^pkg` | Only dependents (exclude pkg itself) |
+
+### Negation
+
+Exclude packages with `!`:
+
+```bash
+--filter=!web # exclude web
+--filter=./apps/* --filter=!admin # apps except admin
+```
+
+### Task Identifiers
+
+Run a specific task in a specific package:
+
+```bash
+turbo run web#build # only web's build task
+turbo run web#build api#test # web build + api test
+```
+
+### Combining Filters
+
+Multiple `--filter` flags create a union:
+
+```bash
+turbo run build --filter=web --filter=api # runs in both
+```
+
+---
+
+## Quick Reference: Changed Packages
+
+| Goal | Command |
+| ---------------------------------- | ----------------------------------------------------------- |
+| Changed + dependents (recommended) | `turbo run build --affected` |
+| Custom base branch | `turbo run build --affected --affected-base=origin/develop` |
+| Only changed (no dependents) | `turbo run build --filter=[origin/main]` |
+| Changed + dependencies | `turbo run build --filter=[origin/main]...` |
+| Since last commit | `turbo run build --filter=...[HEAD^1]` |
diff --git a/.agents/skills/turborepo/references/filtering/patterns.md b/.agents/skills/turborepo/references/filtering/patterns.md
new file mode 100644
index 00000000..17b9f1c5
--- /dev/null
+++ b/.agents/skills/turborepo/references/filtering/patterns.md
@@ -0,0 +1,152 @@
+# Common Filter Patterns
+
+Practical examples for typical monorepo scenarios.
+
+## Single Package
+
+Run task in one package:
+
+```bash
+turbo run build --filter=web
+turbo run test --filter=@acme/api
+```
+
+## Package with Dependencies
+
+Build a package and everything it depends on:
+
+```bash
+turbo run build --filter=web...
+```
+
+Useful for: ensuring all dependencies are built before the target.
+
+## Package Dependents
+
+Run in all packages that depend on a library:
+
+```bash
+turbo run test --filter=...ui
+```
+
+Useful for: testing consumers after changing a shared package.
+
+## Dependents Only (Exclude Target)
+
+Test packages that depend on ui, but not ui itself:
+
+```bash
+turbo run test --filter=...^ui
+```
+
+## Changed Packages
+
+Run only in packages with file changes since last commit:
+
+```bash
+turbo run lint --filter=[HEAD^1]
+```
+
+Since a specific branch point:
+
+```bash
+turbo run lint --filter=[main...HEAD]
+```
+
+## Changed + Dependents (PR Builds)
+
+Run in changed packages AND packages that depend on them:
+
+```bash
+turbo run build test --filter=...[HEAD^1]
+```
+
+Or use the shortcut:
+
+```bash
+turbo run build test --affected
+```
+
+## Directory-Based
+
+Run in all apps:
+
+```bash
+turbo run build --filter=./apps/*
+```
+
+Run in specific directories:
+
+```bash
+turbo run build --filter=./apps/web --filter=./apps/api
+```
+
+## Scope-Based
+
+Run in all packages under a scope:
+
+```bash
+turbo run build --filter=@acme/*
+```
+
+## Exclusions
+
+Run in all apps except admin:
+
+```bash
+turbo run build --filter=./apps/* --filter=!admin
+```
+
+Run everywhere except specific packages:
+
+```bash
+turbo run lint --filter=!legacy-app --filter=!deprecated-pkg
+```
+
+## Complex Combinations
+
+Apps that changed, plus their dependents:
+
+```bash
+turbo run build --filter=...[HEAD^1] --filter=./apps/*
+```
+
+All packages except docs, but only if changed:
+
+```bash
+turbo run build --filter=[main...HEAD] --filter=!docs
+```
+
+## Debugging Filters
+
+Use `--dry` to see what would run without executing:
+
+```bash
+turbo run build --filter=web... --dry
+```
+
+Use `--dry=json` for machine-readable output:
+
+```bash
+turbo run build --filter=...[HEAD^1] --dry=json
+```
+
+## CI/CD Patterns
+
+PR validation (most common):
+
+```bash
+turbo run build test lint --affected
+```
+
+Deploy only changed apps:
+
+```bash
+turbo run deploy --filter=./apps/* --filter=[main...HEAD]
+```
+
+Full rebuild of specific app and deps:
+
+```bash
+turbo run build --filter=production-app...
+```
diff --git a/.agents/skills/turborepo/references/watch/RULE.md b/.agents/skills/turborepo/references/watch/RULE.md
new file mode 100644
index 00000000..44bcf13e
--- /dev/null
+++ b/.agents/skills/turborepo/references/watch/RULE.md
@@ -0,0 +1,99 @@
+# turbo watch
+
+Full docs: https://turborepo.dev/docs/reference/watch
+
+Re-run tasks automatically when code changes. Dependency-aware.
+
+```bash
+turbo watch [tasks]
+```
+
+## Basic Usage
+
+```bash
+# Watch and re-run build task when code changes
+turbo watch build
+
+# Watch multiple tasks
+turbo watch build test lint
+```
+
+Tasks re-run in order configured in `turbo.json` when source files change.
+
+## With Persistent Tasks
+
+Persistent tasks (`"persistent": true`) won't exit, so they can't be depended on. They work the same in `turbo watch` as `turbo run`.
+
+### Dependency-Aware Persistent Tasks
+
+If your tool has built-in watching (like `next dev`), use its watcher:
+
+```json
+{
+ "tasks": {
+ "dev": {
+ "persistent": true,
+ "cache": false
+ }
+ }
+}
+```
+
+### Non-Dependency-Aware Tools
+
+For tools that don't detect dependency changes, use `interruptible`:
+
+```json
+{
+ "tasks": {
+ "dev": {
+ "persistent": true,
+ "interruptible": true,
+ "cache": false
+ }
+ }
+}
+```
+
+`turbo watch` will restart interruptible tasks when dependencies change.
+
+## Limitations
+
+### Caching
+
+Caching is experimental with watch mode:
+
+```bash
+turbo watch your-tasks --experimental-write-cache
+```
+
+### Task Outputs in Source Control
+
+If tasks write files tracked by git, watch mode may loop infinitely. Watch mode uses file hashes to prevent this but it's not foolproof.
+
+**Recommendation**: Remove task outputs from git.
+
+## vs turbo run
+
+| Feature | `turbo run` | `turbo watch` |
+| ----------------- | ----------- | ------------- |
+| Runs once | Yes | No |
+| Re-runs on change | No | Yes |
+| Caching | Full | Experimental |
+| Use case | CI, one-off | Development |
+
+## Common Patterns
+
+### Development Workflow
+
+```bash
+# Run dev servers and watch for build changes
+turbo watch dev build
+```
+
+### Type Checking During Development
+
+```bash
+# Watch and re-run type checks
+turbo watch check-types
+```
diff --git a/.agents/skills/typescript-advanced-types/SKILL.md b/.agents/skills/typescript-advanced-types/SKILL.md
new file mode 100644
index 00000000..5057af79
--- /dev/null
+++ b/.agents/skills/typescript-advanced-types/SKILL.md
@@ -0,0 +1,318 @@
+---
+name: typescript-advanced-types
+description: Master TypeScript's advanced type system including generics, conditional types, mapped types, template literals, and utility types for building type-safe applications. Use when implementing complex type logic, creating reusable type utilities, or ensuring compile-time type safety in TypeScript projects.
+---
+
+# TypeScript Advanced Types
+
+Comprehensive guidance for mastering TypeScript's advanced type system including generics, conditional types, mapped types, template literal types, and utility types for building robust, type-safe applications.
+
+## When to Use This Skill
+
+- Building type-safe libraries or frameworks
+- Creating reusable generic components
+- Implementing complex type inference logic
+- Designing type-safe API clients
+- Building form validation systems
+- Creating strongly-typed configuration objects
+- Implementing type-safe state management
+- Migrating JavaScript codebases to TypeScript
+
+## Core Concepts
+
+### 1. Generics
+
+**Purpose:** Create reusable, type-flexible components while maintaining type safety.
+
+**Basic Generic Function:**
+
+```typescript
+function identity<T>(value: T): T {
+ return value;
+}
+
+const num = identity<number>(42); // Type: number
+const str = identity<string>("hello"); // Type: string
+const auto = identity(true); // Type inferred: boolean
+```
+
+**Generic Constraints:**
+
+```typescript
+interface HasLength {
+ length: number;
+}
+
+function logLength<T extends HasLength>(item: T): T {
+ console.log(item.length);
+ return item;
+}
+
+logLength("hello"); // OK: string has length
+logLength([1, 2, 3]); // OK: array has length
+logLength({ length: 10 }); // OK: object has length
+// logLength(42); // Error: number has no length
+```
+
+**Multiple Type Parameters:**
+
+```typescript
+function merge<T, U>(obj1: T, obj2: U): T & U {
+ return { ...obj1, ...obj2 };
+}
+
+const merged = merge({ name: "John" }, { age: 30 });
+// Type: { name: string } & { age: number }
+```
+
+### 2. Conditional Types
+
+**Purpose:** Create types that depend on conditions, enabling sophisticated type logic.
+
+**Basic Conditional Type:**
+
+```typescript
+type IsString<T> = T extends string ? true : false;
+
+type A = IsString<string>; // true
+type B = IsString<number>; // false
+```
+
+**Extracting Return Types:**
+
+```typescript
+type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
+
+function getUser() {
+ return { id: 1, name: "John" };
+}
+
+type User = ReturnType<typeof getUser>;
+// Type: { id: number; name: string; }
+```
+
+**Distributive Conditional Types:**
+
+```typescript
+type ToArray<T> = T extends any ? T[] : never;
+
+type StrOrNumArray = ToArray<string | number>;
+// Type: string[] | number[]
+```
+
+**Nested Conditions:**
+
+```typescript
+type TypeName<T> = T extends string
+ ? "string"
+ : T extends number
+ ? "number"
+ : T extends boolean
+ ? "boolean"
+ : T extends undefined
+ ? "undefined"
+ : T extends Function
+ ? "function"
+ : "object";
+
+type T1 = TypeName<string>; // "string"
+type T2 = TypeName<() => void>; // "function"
+```
+
+### 3. Mapped Types
+
+**Purpose:** Transform existing types by iterating over their properties.
+
+**Basic Mapped Type:**
+
+```typescript
+type Readonly<T> = {
+ readonly [P in keyof T]: T[P];
+};
+
+interface User {
+ id: number;
+ name: string;
+}
+
+type ReadonlyUser = Readonly<User>;
+// Type: { readonly id: number; readonly name: string; }
+```
+
+**Optional Properties:**
+
+```typescript
+type Partial<T> = {
+ [P in keyof T]?: T[P];
+};
+
+type PartialUser = Partial<User>;
+// Type: { id?: number; name?: string; }
+```
+
+**Key Remapping:**
+
+```typescript
+type Getters<T> = {
+ [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
+};
+
+interface Person {
+ name: string;
+ age: number;
+}
+
+type PersonGetters = Getters<Person>;
+// Type: { getName: () => string; getAge: () => number; }
+```
+
+**Filtering Properties:**
+
+```typescript
+type PickByType<T, U> = {
+ [K in keyof T as T[K] extends U ? K : never]: T[K];
+};
+
+interface Mixed {
+ id: number;
+ name: string;
+ age: number;
+ active: boolean;
+}
+
+type OnlyNumbers = PickByType<Mixed, number>;
+// Type: { id: number; age: number; }
+```
+
+### 4. Template Literal Types
+
+**Purpose:** Create string-based types with pattern matching and transformation.
+
+**Basic Template Literal:**
+
+```typescript
+type EventName = "click" | "focus" | "blur";
+type EventHandler = `on${Capitalize<EventName>}`;
+// Type: "onClick" | "onFocus" | "onBlur"
+```
+
+**String Manipulation:**
+
+```typescript
+type UppercaseGreeting = Uppercase<"hello">; // "HELLO"
+type LowercaseGreeting = Lowercase<"HELLO">; // "hello"
+type CapitalizedName = Capitalize<"john">; // "John"
+type UncapitalizedName = Uncapitalize<"John">; // "john"
+```
+
+**Path Building:**
+
+```typescript
+type Path<T> = T extends object
+ ? {
+ [K in keyof T]: K extends string ? `${K}` | `${K}.${Path<T[K]>}` : never;
+ }[keyof T]
+ : never;
+
+interface Config {
+ server: {
+ host: string;
+ port: number;
+ };
+ database: {
+ url: string;
+ };
+}
+
+type ConfigPath = Path<Config>;
+// Type: "server" | "database" | "server.host" | "server.port" | "database.url"
+```
+
+### 5. Utility Types
+
+**Built-in Utility Types:**
+
+```typescript
+// Partial<T> - Make all properties optional
+type PartialUser = Partial<User>;
+
+// Required<T> - Make all properties required
+type RequiredUser = Required<PartialUser>;
+
+// Readonly<T> - Make all properties readonly
+type ReadonlyUser = Readonly<User>;
+
+// Pick<T, K> - Select specific properties
+type UserName = Pick<User, "name" | "email">;
+
+// Omit<T, K> - Remove specific properties
+type UserWithoutPassword = Omit<User, "password">;
+
+// Exclude<T, U> - Exclude types from union
+type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
+
+// Extract<T, U> - Extract types from union
+type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"
+
+// NonNullable<T> - Exclude null and undefined
+type T3 = NonNullable<string | null | undefined>; // string
+
+// Record<K, T> - Create object type with keys K and values T
+type PageInfo = Record<"home" | "about", { title: string }>;
+```
+
+## Detailed worked examples and patterns
+
+Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient.
+
+## Best Practices
+
+1. **Use `unknown` over `any`**: Enforce type checking
+2. **Prefer `interface` for object shapes**: Better error messages
+3. **Use `type` for unions and complex types**: More flexible
+4. **Leverage type inference**: Let TypeScript infer when possible
+5. **Create helper types**: Build reusable type utilities
+6. **Use const assertions**: Preserve literal types
+7. **Avoid type assertions**: Use type guards instead
+8. **Document complex types**: Add JSDoc comments
+9. **Use strict mode**: Enable all strict compiler options
+10. **Test your types**: Use type tests to verify type behavior
+
+## Type Testing
+
+```typescript
+// Type assertion tests
+type AssertEqual<T, U> = [T] extends [U]
+ ? [U] extends [T]
+ ? true
+ : false
+ : false;
+
+type Test1 = AssertEqual<string, string>; // true
+type Test2 = AssertEqual<string, number>; // false
+type Test3 = AssertEqual<string | number, string>; // false
+
+// Expect error helper
+type ExpectError<T extends never> = T;
+
+// Example usage
+type ShouldError = ExpectError<AssertEqual<string, number>>;
+```
+
+## Common Pitfalls
+
+1. **Over-using `any`**: Defeats the purpose of TypeScript
+2. **Ignoring strict null checks**: Can lead to runtime errors
+3. **Too complex types**: Can slow down compilation
+4. **Not using discriminated unions**: Misses type narrowing opportunities
+5. **Forgetting readonly modifiers**: Allows unintended mutations
+6. **Circular type references**: Can cause compiler errors
+7. **Not handling edge cases**: Like empty arrays or null values
+
+## Performance Considerations
+
+- Avoid deeply nested conditional types
+- Use simple types when possible
+- Cache complex type computations
+- Limit recursion depth in recursive types
+- Use build tools to skip type checking in production
diff --git a/.agents/skills/typescript-advanced-types/references/details.md b/.agents/skills/typescript-advanced-types/references/details.md
new file mode 100644
index 00000000..6b1b9a15
--- /dev/null
+++ b/.agents/skills/typescript-advanced-types/references/details.md
@@ -0,0 +1,404 @@
+# typescript-advanced-types — detailed worked examples
+
+## Advanced Patterns
+
+### Pattern 1: Type-Safe Event Emitter
+
+```typescript
+type EventMap = {
+ "user:created": { id: string; name: string };
+ "user:updated": { id: string };
+ "user:deleted": { id: string };
+};
+
+class TypedEventEmitter<T extends Record<string, any>> {
+ private listeners: {
+ [K in keyof T]?: Array<(data: T[K]) => void>;
+ } = {};
+
+ on<K extends keyof T>(event: K, callback: (data: T[K]) => void): void {
+ if (!this.listeners[event]) {
+ this.listeners[event] = [];
+ }
+ this.listeners[event]!.push(callback);
+ }
+
+ emit<K extends keyof T>(event: K, data: T[K]): void {
+ const callbacks = this.listeners[event];
+ if (callbacks) {
+ callbacks.forEach((callback) => callback(data));
+ }
+ }
+}
+
+const emitter = new TypedEventEmitter<EventMap>();
+
+emitter.on("user:created", (data) => {
+ console.log(data.id, data.name); // Type-safe!
+});
+
+emitter.emit("user:created", { id: "1", name: "John" });
+// emitter.emit("user:created", { id: "1" }); // Error: missing 'name'
+```
+
+### Pattern 2: Type-Safe API Client
+
+```typescript
+type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";
+
+type EndpointConfig = {
+ "/users": {
+ GET: { response: User[] };
+ POST: { body: { name: string; email: string }; response: User };
+ };
+ "/users/:id": {
+ GET: { params: { id: string }; response: User };
+ PUT: { params: { id: string }; body: Partial<User>; response: User };
+ DELETE: { params: { id: string }; response: void };
+ };
+};
+
+type ExtractParams<T> = T extends { params: infer P } ? P : never;
+type ExtractBody<T> = T extends { body: infer B } ? B : never;
+type ExtractResponse<T> = T extends { response: infer R } ? R : never;
+
+class APIClient<Config extends Record<string, Record<HTTPMethod, any>>> {
+ async request<Path extends keyof Config, Method extends keyof Config[Path]>(
+ path: Path,
+ method: Method,
+ ...[options]: ExtractParams<Config[Path][Method]> extends never
+ ? ExtractBody<Config[Path][Method]> extends never
+ ? []
+ : [{ body: ExtractBody<Config[Path][Method]> }]
+ : [
+ {
+ params: ExtractParams<Config[Path][Method]>;
+ body?: ExtractBody<Config[Path][Method]>;
+ },
+ ]
+ ): Promise<ExtractResponse<Config[Path][Method]>> {
+ // Implementation here
+ return {} as any;
+ }
+}
+
+const api = new APIClient<EndpointConfig>();
+
+// Type-safe API calls
+const users = await api.request("/users", "GET");
+// Type: User[]
+
+const newUser = await api.request("/users", "POST", {
+ body: { name: "John", email: "[email protected]" },
+});
+// Type: User
+
+const user = await api.request("/users/:id", "GET", {
+ params: { id: "123" },
+});
+// Type: User
+```
+
+### Pattern 3: Builder Pattern with Type Safety
+
+```typescript
+type BuilderState<T> = {
+ [K in keyof T]: T[K] | undefined;
+};
+
+type RequiredKeys<T> = {
+ [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
+}[keyof T];
+
+type OptionalKeys<T> = {
+ [K in keyof T]-?: {} extends Pick<T, K> ? K : never;
+}[keyof T];
+
+type IsComplete<T, S> =
+ RequiredKeys<T> extends keyof S
+ ? S[RequiredKeys<T>] extends undefined
+ ? false
+ : true
+ : false;
+
+class Builder<T, S extends BuilderState<T> = {}> {
+ private state: S = {} as S;
+
+ set<K extends keyof T>(key: K, value: T[K]): Builder<T, S & Record<K, T[K]>> {
+ this.state[key] = value;
+ return this as any;
+ }
+
+ build(this: IsComplete<T, S> extends true ? this : never): T {
+ return this.state as T;
+ }
+}
+
+interface User {
+ id: string;
+ name: string;
+ email: string;
+ age?: number;
+}
+
+const builder = new Builder<User>();
+
+const user = builder
+ .set("id", "1")
+ .set("name", "John")
+ .set("email", "[email protected]")
+ .build(); // OK: all required fields set
+
+// const incomplete = builder
+// .set("id", "1")
+// .build(); // Error: missing required fields
+```
+
+### Pattern 4: Deep Readonly/Partial
+
+```typescript
+type DeepReadonly<T> = {
+ readonly [P in keyof T]: T[P] extends object
+ ? T[P] extends Function
+ ? T[P]
+ : DeepReadonly<T[P]>
+ : T[P];
+};
+
+type DeepPartial<T> = {
+ [P in keyof T]?: T[P] extends object
+ ? T[P] extends Array<infer U>
+ ? Array<DeepPartial<U>>
+ : DeepPartial<T[P]>
+ : T[P];
+};
+
+interface Config {
+ server: {
+ host: string;
+ port: number;
+ ssl: {
+ enabled: boolean;
+ cert: string;
+ };
+ };
+ database: {
+ url: string;
+ pool: {
+ min: number;
+ max: number;
+ };
+ };
+}
+
+type ReadonlyConfig = DeepReadonly<Config>;
+// All nested properties are readonly
+
+type PartialConfig = DeepPartial<Config>;
+// All nested properties are optional
+```
+
+### Pattern 5: Type-Safe Form Validation
+
+```typescript
+type ValidationRule<T> = {
+ validate: (value: T) => boolean;
+ message: string;
+};
+
+type FieldValidation<T> = {
+ [K in keyof T]?: ValidationRule<T[K]>[];
+};
+
+type ValidationErrors<T> = {
+ [K in keyof T]?: string[];
+};
+
+class FormValidator<T extends Record<string, any>> {
+ constructor(private rules: FieldValidation<T>) {}
+
+ validate(data: T): ValidationErrors<T> | null {
+ const errors: ValidationErrors<T> = {};
+ let hasErrors = false;
+
+ for (const key in this.rules) {
+ const fieldRules = this.rules[key];
+ const value = data[key];
+
+ if (fieldRules) {
+ const fieldErrors: string[] = [];
+
+ for (const rule of fieldRules) {
+ if (!rule.validate(value)) {
+ fieldErrors.push(rule.message);
+ }
+ }
+
+ if (fieldErrors.length > 0) {
+ errors[key] = fieldErrors;
+ hasErrors = true;
+ }
+ }
+ }
+
+ return hasErrors ? errors : null;
+ }
+}
+
+interface LoginForm {
+ email: string;
+ password: string;
+}
+
+const validator = new FormValidator<LoginForm>({
+ email: [
+ {
+ validate: (v) => v.includes("@"),
+ message: "Email must contain @",
+ },
+ {
+ validate: (v) => v.length > 0,
+ message: "Email is required",
+ },
+ ],
+ password: [
+ {
+ validate: (v) => v.length >= 8,
+ message: "Password must be at least 8 characters",
+ },
+ ],
+});
+
+const errors = validator.validate({
+ email: "invalid",
+ password: "short",
+});
+// Type: { email?: string[]; password?: string[]; } | null
+```
+
+### Pattern 6: Discriminated Unions
+
+```typescript
+type Success<T> = {
+ status: "success";
+ data: T;
+};
+
+type Error = {
+ status: "error";
+ error: string;
+};
+
+type Loading = {
+ status: "loading";
+};
+
+type AsyncState<T> = Success<T> | Error | Loading;
+
+function handleState<T>(state: AsyncState<T>): void {
+ switch (state.status) {
+ case "success":
+ console.log(state.data); // Type: T
+ break;
+ case "error":
+ console.log(state.error); // Type: string
+ break;
+ case "loading":
+ console.log("Loading...");
+ break;
+ }
+}
+
+// Type-safe state machine
+type State =
+ | { type: "idle" }
+ | { type: "fetching"; requestId: string }
+ | { type: "success"; data: any }
+ | { type: "error"; error: Error };
+
+type Event =
+ | { type: "FETCH"; requestId: string }
+ | { type: "SUCCESS"; data: any }
+ | { type: "ERROR"; error: Error }
+ | { type: "RESET" };
+
+function reducer(state: State, event: Event): State {
+ switch (state.type) {
+ case "idle":
+ return event.type === "FETCH"
+ ? { type: "fetching", requestId: event.requestId }
+ : state;
+ case "fetching":
+ if (event.type === "SUCCESS") {
+ return { type: "success", data: event.data };
+ }
+ if (event.type === "ERROR") {
+ return { type: "error", error: event.error };
+ }
+ return state;
+ case "success":
+ case "error":
+ return event.type === "RESET" ? { type: "idle" } : state;
+ }
+}
+```
+
+## Type Inference Techniques
+
+### 1. Infer Keyword
+
+```typescript
+// Extract array element type
+type ElementType<T> = T extends (infer U)[] ? U : never;
+
+type NumArray = number[];
+type Num = ElementType<NumArray>; // number
+
+// Extract promise type
+type PromiseType<T> = T extends Promise<infer U> ? U : never;
+
+type AsyncNum = PromiseType<Promise<number>>; // number
+
+// Extract function parameters
+type Parameters<T> = T extends (...args: infer P) => any ? P : never;
+
+function foo(a: string, b: number) {}
+type FooParams = Parameters<typeof foo>; // [string, number]
+```
+
+### 2. Type Guards
+
+```typescript
+function isString(value: unknown): value is string {
+ return typeof value === "string";
+}
+
+function isArrayOf<T>(
+ value: unknown,
+ guard: (item: unknown) => item is T,
+): value is T[] {
+ return Array.isArray(value) && value.every(guard);
+}
+
+const data: unknown = ["a", "b", "c"];
+
+if (isArrayOf(data, isString)) {
+ data.forEach((s) => s.toUpperCase()); // Type: string[]
+}
+```
+
+### 3. Assertion Functions
+
+```typescript
+function assertIsString(value: unknown): asserts value is string {
+ if (typeof value !== "string") {
+ throw new Error("Not a string");
+ }
+}
+
+function processValue(value: unknown) {
+ assertIsString(value);
+ // value is now typed as string
+ console.log(value.toUpperCase());
+}
+```
diff --git a/.agents/skills/vercel-composition-patterns/AGENTS.md b/.agents/skills/vercel-composition-patterns/AGENTS.md
new file mode 100644
index 00000000..558bf9aa
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/AGENTS.md
@@ -0,0 +1,946 @@
+# React Composition Patterns
+
+**Version 1.0.0**
+Engineering
+January 2026
+
+> **Note:**
+> This document is mainly for agents and LLMs to follow when maintaining,
+> generating, or refactoring React codebases using composition. Humans
+> may also find it useful, but guidance here is optimized for automation
+> and consistency by AI-assisted workflows.
+
+---
+
+## Abstract
+
+Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.
+
+---
+
+## Table of Contents
+
+1. [Component Architecture](#1-component-architecture) — **HIGH**
+ - 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation)
+ - 1.2 [Use Compound Components](#12-use-compound-components)
+2. [State Management](#2-state-management) — **MEDIUM**
+ - 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui)
+ - 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection)
+ - 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)
+3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM**
+ - 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants)
+ - 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)
+4. [React 19 APIs](#4-react-19-apis) — **MEDIUM**
+ - 4.1 [React 19 API Changes](#41-react-19-api-changes)
+
+---
+
+## 1. Component Architecture
+
+**Impact: HIGH**
+
+Fundamental patterns for structuring components to avoid prop
+proliferation and enable flexible composition.
+
+### 1.1 Avoid Boolean Prop Proliferation
+
+**Impact: CRITICAL (prevents unmaintainable component variants)**
+
+Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
+
+component behavior. Each boolean doubles possible states and creates
+
+unmaintainable conditional logic. Use composition instead.
+
+**Incorrect: boolean props create exponential complexity**
+
+```tsx
+function Composer({
+ onSubmit,
+ isThread,
+ channelId,
+ isDMThread,
+ dmId,
+ isEditing,
+ isForwarding,
+}: Props) {
+ return (
+ <form>
+ <Header />
+ <Input />
+ {isDMThread ? (
+ <AlsoSendToDMField id={dmId} />
+ ) : isThread ? (
+ <AlsoSendToChannelField id={channelId} />
+ ) : null}
+ {isEditing ? (
+ <EditActions />
+ ) : isForwarding ? (
+ <ForwardActions />
+ ) : (
+ <DefaultActions />
+ )}
+ <Footer onSubmit={onSubmit} />
+ </form>
+ )
+}
+```
+
+**Correct: composition eliminates conditionals**
+
+```tsx
+// Channel composer
+function ChannelComposer() {
+ return (
+ <Composer.Frame>
+ <Composer.Header />
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Attachments />
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+ )
+}
+
+// Thread composer - adds "also send to channel" field
+function ThreadComposer({ channelId }: { channelId: string }) {
+ return (
+ <Composer.Frame>
+ <Composer.Header />
+ <Composer.Input />
+ <AlsoSendToChannelField id={channelId} />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+ )
+}
+
+// Edit composer - different footer actions
+function EditComposer() {
+ return (
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.CancelEdit />
+ <Composer.SaveEdit />
+ </Composer.Footer>
+ </Composer.Frame>
+ )
+}
+```
+
+Each variant is explicit about what it renders. We can share internals without
+
+sharing a single monolithic parent.
+
+### 1.2 Use Compound Components
+
+**Impact: HIGH (enables flexible composition without prop drilling)**
+
+Structure complex components as compound components with a shared context. Each
+
+subcomponent accesses shared state via context, not props. Consumers compose the
+
+pieces they need.
+
+**Incorrect: monolithic component with render props**
+
+```tsx
+function Composer({
+ renderHeader,
+ renderFooter,
+ renderActions,
+ showAttachments,
+ showFormatting,
+ showEmojis,
+}: Props) {
+ return (
+ <form>
+ {renderHeader?.()}
+ <Input />
+ {showAttachments && <Attachments />}
+ {renderFooter ? (
+ renderFooter()
+ ) : (
+ <Footer>
+ {showFormatting && <Formatting />}
+ {showEmojis && <Emojis />}
+ {renderActions?.()}
+ </Footer>
+ )}
+ </form>
+ )
+}
+```
+
+**Correct: compound components with shared context**
+
+```tsx
+const ComposerContext = createContext<ComposerContextValue | null>(null)
+
+function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
+ return (
+ <ComposerContext value={{ state, actions, meta }}>
+ {children}
+ </ComposerContext>
+ )
+}
+
+function ComposerFrame({ children }: { children: React.ReactNode }) {
+ return <form>{children}</form>
+}
+
+function ComposerInput() {
+ const {
+ state,
+ actions: { update },
+ meta: { inputRef },
+ } = use(ComposerContext)
+ return (
+ <TextInput
+ ref={inputRef}
+ value={state.input}
+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}
+ />
+ )
+}
+
+function ComposerSubmit() {
+ const {
+ actions: { submit },
+ } = use(ComposerContext)
+ return <Button onPress={submit}>Send</Button>
+}
+
+// Export as compound component
+const Composer = {
+ Provider: ComposerProvider,
+ Frame: ComposerFrame,
+ Input: ComposerInput,
+ Submit: ComposerSubmit,
+ Header: ComposerHeader,
+ Footer: ComposerFooter,
+ Attachments: ComposerAttachments,
+ Formatting: ComposerFormatting,
+ Emojis: ComposerEmojis,
+}
+```
+
+**Usage:**
+
+```tsx
+<Composer.Provider state={state} actions={actions} meta={meta}>
+ <Composer.Frame>
+ <Composer.Header />
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+</Composer.Provider>
+```
+
+Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
+
+---
+
+## 2. State Management
+
+**Impact: MEDIUM**
+
+Patterns for lifting state and managing shared context across
+composed components.
+
+### 2.1 Decouple State Management from UI
+
+**Impact: MEDIUM (enables swapping state implementations without changing UI)**
+
+The provider component should be the only place that knows how state is managed.
+
+UI components consume the context interface—they don't know if state comes from
+
+useState, Zustand, or a server sync.
+
+**Incorrect: UI coupled to state implementation**
+
+```tsx
+function ChannelComposer({ channelId }: { channelId: string }) {
+ // UI component knows about global state implementation
+ const state = useGlobalChannelState(channelId)
+ const { submit, updateInput } = useChannelSync(channelId)
+
+ return (
+ <Composer.Frame>
+ <Composer.Input
+ value={state.input}
+ onChange={(text) => sync.updateInput(text)}
+ />
+ <Composer.Submit onPress={() => sync.submit()} />
+ </Composer.Frame>
+ )
+}
+```
+
+**Correct: state management isolated in provider**
+
+```tsx
+// Provider handles all state management details
+function ChannelProvider({
+ channelId,
+ children,
+}: {
+ channelId: string
+ children: React.ReactNode
+}) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+ const inputRef = useRef(null)
+
+ return (
+ <Composer.Provider
+ state={state}
+ actions={{ update, submit }}
+ meta={{ inputRef }}
+ >
+ {children}
+ </Composer.Provider>
+ )
+}
+
+// UI component only knows about the context interface
+function ChannelComposer() {
+ return (
+ <Composer.Frame>
+ <Composer.Header />
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+ )
+}
+
+// Usage
+function Channel({ channelId }: { channelId: string }) {
+ return (
+ <ChannelProvider channelId={channelId}>
+ <ChannelComposer />
+ </ChannelProvider>
+ )
+}
+```
+
+**Different providers, same UI:**
+
+```tsx
+// Local state for ephemeral forms
+function ForwardMessageProvider({ children }) {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+
+ return (
+ <Composer.Provider
+ state={state}
+ actions={{ update: setState, submit: forwardMessage }}
+ >
+ {children}
+ </Composer.Provider>
+ )
+}
+
+// Global synced state for channels
+function ChannelProvider({ channelId, children }) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+
+ return (
+ <Composer.Provider state={state} actions={{ update, submit }}>
+ {children}
+ </Composer.Provider>
+ )
+}
+```
+
+The same `Composer.Input` component works with both providers because it only
+
+depends on the context interface, not the implementation.
+
+### 2.2 Define Generic Context Interfaces for Dependency Injection
+
+**Impact: HIGH (enables dependency-injectable state across use-cases)**
+
+Define a **generic interface** for your component context with three parts:
+
+`state`, `actions`, and `meta`. This interface is a contract that any provider
+
+can implement—enabling the same UI components to work with completely different
+
+state implementations.
+
+**Core principle:** Lift state, compose internals, make state
+
+dependency-injectable.
+
+**Incorrect: UI coupled to specific state implementation**
+
+```tsx
+function ComposerInput() {
+ // Tightly coupled to a specific hook
+ const { input, setInput } = useChannelComposerState()
+ return <TextInput value={input} onChangeText={setInput} />
+}
+```
+
+**Correct: generic interface enables dependency injection**
+
+```tsx
+// Define a GENERIC interface that any provider can implement
+interface ComposerState {
+ input: string
+ attachments: Attachment[]
+ isSubmitting: boolean
+}
+
+interface ComposerActions {
+ update: (updater: (state: ComposerState) => ComposerState) => void
+ submit: () => void
+}
+
+interface ComposerMeta {
+ inputRef: React.RefObject<TextInput>
+}
+
+interface ComposerContextValue {
+ state: ComposerState
+ actions: ComposerActions
+ meta: ComposerMeta
+}
+
+const ComposerContext = createContext<ComposerContextValue | null>(null)
+```
+
+**UI components consume the interface, not the implementation:**
+
+```tsx
+function ComposerInput() {
+ const {
+ state,
+ actions: { update },
+ meta,
+ } = use(ComposerContext)
+
+ // This component works with ANY provider that implements the interface
+ return (
+ <TextInput
+ ref={meta.inputRef}
+ value={state.input}
+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}
+ />
+ )
+}
+```
+
+**Different providers implement the same interface:**
+
+```tsx
+// Provider A: Local state for ephemeral forms
+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
+ const [state, setState] = useState(initialState)
+ const inputRef = useRef(null)
+ const submit = useForwardMessage()
+
+ return (
+ <ComposerContext
+ value={{
+ state,
+ actions: { update: setState, submit },
+ meta: { inputRef },
+ }}
+ >
+ {children}
+ </ComposerContext>
+ )
+}
+
+// Provider B: Global synced state for channels
+function ChannelProvider({ channelId, children }: Props) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+ const inputRef = useRef(null)
+
+ return (
+ <ComposerContext
+ value={{
+ state,
+ actions: { update, submit },
+ meta: { inputRef },
+ }}
+ >
+ {children}
+ </ComposerContext>
+ )
+}
+```
+
+**The same composed UI works with both:**
+
+```tsx
+// Works with ForwardMessageProvider (local state)
+<ForwardMessageProvider>
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Submit />
+ </Composer.Frame>
+</ForwardMessageProvider>
+
+// Works with ChannelProvider (global synced state)
+<ChannelProvider channelId="abc">
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Submit />
+ </Composer.Frame>
+</ChannelProvider>
+```
+
+**Custom UI outside the component can access state and actions:**
+
+```tsx
+function ForwardMessageDialog() {
+ return (
+ <ForwardMessageProvider>
+ <Dialog>
+ {/* The composer UI */}
+ <Composer.Frame>
+ <Composer.Input placeholder="Add a message, if you'd like." />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ </Composer.Footer>
+ </Composer.Frame>
+
+ {/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
+ <MessagePreview />
+
+ {/* Actions at the bottom of the dialog */}
+ <DialogActions>
+ <CancelButton />
+ <ForwardButton />
+ </DialogActions>
+ </Dialog>
+ </ForwardMessageProvider>
+ )
+}
+
+// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
+function ForwardButton() {
+ const {
+ actions: { submit },
+ } = use(ComposerContext)
+ return <Button onPress={submit}>Forward</Button>
+}
+
+// This preview lives OUTSIDE Composer.Frame but can read composer's state!
+function MessagePreview() {
+ const { state } = use(ComposerContext)
+ return <Preview message={state.input} attachments={state.attachments} />
+}
+```
+
+The provider boundary is what matters—not the visual nesting. Components that
+
+need shared state don't have to be inside the `Composer.Frame`. They just need
+
+to be within the provider.
+
+The `ForwardButton` and `MessagePreview` are not visually inside the composer
+
+box, but they can still access its state and actions. This is the power of
+
+lifting state into providers.
+
+The UI is reusable bits you compose together. The state is dependency-injected
+
+by the provider. Swap the provider, keep the UI.
+
+### 2.3 Lift State into Provider Components
+
+**Impact: HIGH (enables state sharing outside component boundaries)**
+
+Move state management into dedicated provider components. This allows sibling
+
+components outside the main UI to access and modify state without prop drilling
+
+or awkward refs.
+
+**Incorrect: state trapped inside component**
+
+```tsx
+function ForwardMessageComposer() {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+
+ return (
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Footer />
+ </Composer.Frame>
+ )
+}
+
+// Problem: How does this button access composer state?
+function ForwardMessageDialog() {
+ return (
+ <Dialog>
+ <ForwardMessageComposer />
+ <MessagePreview /> {/* Needs composer state */}
+ <DialogActions>
+ <CancelButton />
+ <ForwardButton /> {/* Needs to call submit */}
+ </DialogActions>
+ </Dialog>
+ )
+}
+```
+
+**Incorrect: useEffect to sync state up**
+
+```tsx
+function ForwardMessageDialog() {
+ const [input, setInput] = useState('')
+ return (
+ <Dialog>
+ <ForwardMessageComposer onInputChange={setInput} />
+ <MessagePreview input={input} />
+ </Dialog>
+ )
+}
+
+function ForwardMessageComposer({ onInputChange }) {
+ const [state, setState] = useState(initialState)
+ useEffect(() => {
+ onInputChange(state.input) // Sync on every change 😬
+ }, [state.input])
+}
+```
+
+**Incorrect: reading state from ref on submit**
+
+```tsx
+function ForwardMessageDialog() {
+ const stateRef = useRef(null)
+ return (
+ <Dialog>
+ <ForwardMessageComposer stateRef={stateRef} />
+ <ForwardButton onPress={() => submit(stateRef.current)} />
+ </Dialog>
+ )
+}
+```
+
+**Correct: state lifted to provider**
+
+```tsx
+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+ const inputRef = useRef(null)
+
+ return (
+ <Composer.Provider
+ state={state}
+ actions={{ update: setState, submit: forwardMessage }}
+ meta={{ inputRef }}
+ >
+ {children}
+ </Composer.Provider>
+ )
+}
+
+function ForwardMessageDialog() {
+ return (
+ <ForwardMessageProvider>
+ <Dialog>
+ <ForwardMessageComposer />
+ <MessagePreview /> {/* Custom components can access state and actions */}
+ <DialogActions>
+ <CancelButton />
+ <ForwardButton /> {/* Custom components can access state and actions */}
+ </DialogActions>
+ </Dialog>
+ </ForwardMessageProvider>
+ )
+}
+
+function ForwardButton() {
+ const { actions } = use(Composer.Context)
+ return <Button onPress={actions.submit}>Forward</Button>
+}
+```
+
+The ForwardButton lives outside the Composer.Frame but still has access to the
+
+submit action because it's within the provider. Even though it's a one-off
+
+component, it can still access the composer's state and actions from outside the
+
+UI itself.
+
+**Key insight:** Components that need shared state don't have to be visually
+
+nested inside each other—they just need to be within the same provider.
+
+---
+
+## 3. Implementation Patterns
+
+**Impact: MEDIUM**
+
+Specific techniques for implementing compound components and
+context providers.
+
+### 3.1 Create Explicit Component Variants
+
+**Impact: MEDIUM (self-documenting code, no hidden conditionals)**
+
+Instead of one component with many boolean props, create explicit variant
+
+components. Each variant composes the pieces it needs. The code documents
+
+itself.
+
+**Incorrect: one component, many modes**
+
+```tsx
+// What does this component actually render?
+<Composer
+ isThread
+ isEditing={false}
+ channelId='abc'
+ showAttachments
+ showFormatting={false}
+/>
+```
+
+**Correct: explicit variants**
+
+```tsx
+// Immediately clear what this renders
+<ThreadComposer channelId="abc" />
+
+// Or
+<EditMessageComposer messageId="xyz" />
+
+// Or
+<ForwardMessageComposer messageId="123" />
+```
+
+Each implementation is unique, explicit and self-contained. Yet they can each
+
+use shared parts.
+
+**Implementation:**
+
+```tsx
+function ThreadComposer({ channelId }: { channelId: string }) {
+ return (
+ <ThreadProvider channelId={channelId}>
+ <Composer.Frame>
+ <Composer.Input />
+ <AlsoSendToChannelField channelId={channelId} />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+ </ThreadProvider>
+ )
+}
+
+function EditMessageComposer({ messageId }: { messageId: string }) {
+ return (
+ <EditMessageProvider messageId={messageId}>
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.CancelEdit />
+ <Composer.SaveEdit />
+ </Composer.Footer>
+ </Composer.Frame>
+ </EditMessageProvider>
+ )
+}
+
+function ForwardMessageComposer({ messageId }: { messageId: string }) {
+ return (
+ <ForwardMessageProvider messageId={messageId}>
+ <Composer.Frame>
+ <Composer.Input placeholder="Add a message, if you'd like." />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.Mentions />
+ </Composer.Footer>
+ </Composer.Frame>
+ </ForwardMessageProvider>
+ )
+}
+```
+
+Each variant is explicit about:
+
+- What provider/state it uses
+
+- What UI elements it includes
+
+- What actions are available
+
+No boolean prop combinations to reason about. No impossible states.
+
+### 3.2 Prefer Composing Children Over Render Props
+
+**Impact: MEDIUM (cleaner composition, better readability)**
+
+Use `children` for composition instead of `renderX` props. Children are more
+
+readable, compose naturally, and don't require understanding callback
+
+signatures.
+
+**Incorrect: render props**
+
+```tsx
+function Composer({
+ renderHeader,
+ renderFooter,
+ renderActions,
+}: {
+ renderHeader?: () => React.ReactNode
+ renderFooter?: () => React.ReactNode
+ renderActions?: () => React.ReactNode
+}) {
+ return (
+ <form>
+ {renderHeader?.()}
+ <Input />
+ {renderFooter ? renderFooter() : <DefaultFooter />}
+ {renderActions?.()}
+ </form>
+ )
+}
+
+// Usage is awkward and inflexible
+return (
+ <Composer
+ renderHeader={() => <CustomHeader />}
+ renderFooter={() => (
+ <>
+ <Formatting />
+ <Emojis />
+ </>
+ )}
+ renderActions={() => <SubmitButton />}
+ />
+)
+```
+
+**Correct: compound components with children**
+
+```tsx
+function ComposerFrame({ children }: { children: React.ReactNode }) {
+ return <form>{children}</form>
+}
+
+function ComposerFooter({ children }: { children: React.ReactNode }) {
+ return <footer className='flex'>{children}</footer>
+}
+
+// Usage is flexible
+return (
+ <Composer.Frame>
+ <CustomHeader />
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <SubmitButton />
+ </Composer.Footer>
+ </Composer.Frame>
+)
+```
+
+**When render props are appropriate:**
+
+```tsx
+// Render props work well when you need to pass data back
+<List
+ data={items}
+ renderItem={({ item, index }) => <Item item={item} index={index} />}
+/>
+```
+
+Use render props when the parent needs to provide data or state to the child.
+
+Use children when composing static structure.
+
+---
+
+## 4. React 19 APIs
+
+**Impact: MEDIUM**
+
+React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
+
+### 4.1 React 19 API Changes
+
+**Impact: MEDIUM (cleaner component definitions and context usage)**
+
+> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
+
+In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
+
+**Incorrect: forwardRef in React 19**
+
+```tsx
+const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
+ return <TextInput ref={ref} {...props} />
+})
+```
+
+**Correct: ref as a regular prop**
+
+```tsx
+function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
+ return <TextInput ref={ref} {...props} />
+}
+```
+
+**Incorrect: useContext in React 19**
+
+```tsx
+const value = useContext(MyContext)
+```
+
+**Correct: use instead of useContext**
+
+```tsx
+const value = use(MyContext)
+```
+
+`use()` can also be called conditionally, unlike `useContext()`.
+
+---
+
+## References
+
+1. [https://react.dev](https://react.dev)
+2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)
+3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)
diff --git a/.agents/skills/vercel-composition-patterns/README.md b/.agents/skills/vercel-composition-patterns/README.md
new file mode 100644
index 00000000..01f359b0
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/README.md
@@ -0,0 +1,60 @@
+# React Composition Patterns
+
+A structured repository for React composition patterns that scale. These
+patterns help avoid boolean prop proliferation by using compound components,
+lifting state, and composing internals.
+
+## Structure
+
+- `rules/` - Individual rule files (one per rule)
+ - `_sections.md` - Section metadata (titles, impacts, descriptions)
+ - `_template.md` - Template for creating new rules
+ - `area-description.md` - Individual rule files
+- `metadata.json` - Document metadata (version, organization, abstract)
+- **`AGENTS.md`** - Compiled output (generated)
+
+## Rules
+
+### Component Architecture (CRITICAL)
+
+- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize
+ behavior
+- `architecture-compound-components.md` - Structure as compound components with
+ shared context
+
+### State Management (HIGH)
+
+- `state-lift-state.md` - Lift state into provider components
+- `state-context-interface.md` - Define clear context interfaces
+ (state/actions/meta)
+- `state-decouple-implementation.md` - Decouple state management from UI
+
+### Implementation Patterns (MEDIUM)
+
+- `patterns-children-over-render-props.md` - Prefer children over renderX props
+- `patterns-explicit-variants.md` - Create explicit component variants
+
+## Core Principles
+
+1. **Composition over configuration** — Instead of adding props, let consumers
+ compose
+2. **Lift your state** — State in providers, not trapped in components
+3. **Compose your internals** — Subcomponents access context, not props
+4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer
+ with isThread
+
+## Creating a New Rule
+
+1. Copy `rules/_template.md` to `rules/area-description.md`
+2. Choose the appropriate area prefix:
+ - `architecture-` for Component Architecture
+ - `state-` for State Management
+ - `patterns-` for Implementation Patterns
+3. Fill in the frontmatter and content
+4. Ensure you have clear examples with explanations
+
+## Impact Levels
+
+- `CRITICAL` - Foundational patterns, prevents unmaintainable code
+- `HIGH` - Significant maintainability improvements
+- `MEDIUM` - Good practices for cleaner code
diff --git a/.agents/skills/vercel-composition-patterns/SKILL.md b/.agents/skills/vercel-composition-patterns/SKILL.md
new file mode 100644
index 00000000..d07025bf
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/SKILL.md
@@ -0,0 +1,89 @@
+---
+name: vercel-composition-patterns
+description:
+ React composition patterns that scale. Use when refactoring components with
+ boolean prop proliferation, building flexible component libraries, or
+ designing reusable APIs. Triggers on tasks involving compound components,
+ render props, context providers, or component architecture. Includes React 19
+ API changes.
+license: MIT
+metadata:
+ author: vercel
+ version: '1.0.0'
+---
+
+# React Composition Patterns
+
+Composition patterns for building flexible, maintainable React components. Avoid
+boolean prop proliferation by using compound components, lifting state, and
+composing internals. These patterns make codebases easier for both humans and AI
+agents to work with as they scale.
+
+## When to Apply
+
+Reference these guidelines when:
+
+- Refactoring components with many boolean props
+- Building reusable component libraries
+- Designing flexible component APIs
+- Reviewing component architecture
+- Working with compound components or context providers
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+| -------- | ----------------------- | ------ | --------------- |
+| 1 | Component Architecture | HIGH | `architecture-` |
+| 2 | State Management | MEDIUM | `state-` |
+| 3 | Implementation Patterns | MEDIUM | `patterns-` |
+| 4 | React 19 APIs | MEDIUM | `react19-` |
+
+## Quick Reference
+
+### 1. Component Architecture (HIGH)
+
+- `architecture-avoid-boolean-props` - Don't add boolean props to customize
+ behavior; use composition
+- `architecture-compound-components` - Structure complex components with shared
+ context
+
+### 2. State Management (MEDIUM)
+
+- `state-decouple-implementation` - Provider is the only place that knows how
+ state is managed
+- `state-context-interface` - Define generic interface with state, actions, meta
+ for dependency injection
+- `state-lift-state` - Move state into provider components for sibling access
+
+### 3. Implementation Patterns (MEDIUM)
+
+- `patterns-explicit-variants` - Create explicit variant components instead of
+ boolean modes
+- `patterns-children-over-render-props` - Use children for composition instead
+ of renderX props
+
+### 4. React 19 APIs (MEDIUM)
+
+> **⚠️ React 19+ only.** Skip this section if using React 18 or earlier.
+
+- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`
+
+## How to Use
+
+Read individual rule files for detailed explanations and code examples:
+
+```
+rules/architecture-avoid-boolean-props.md
+rules/state-context-interface.md
+```
+
+Each rule file contains:
+
+- Brief explanation of why it matters
+- Incorrect code example with explanation
+- Correct code example with explanation
+- Additional context and references
+
+## Full Compiled Document
+
+For the complete guide with all rules expanded: `AGENTS.md`
diff --git a/.agents/skills/vercel-composition-patterns/metadata.json b/.agents/skills/vercel-composition-patterns/metadata.json
new file mode 100644
index 00000000..46bf685b
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/metadata.json
@@ -0,0 +1,11 @@
+{
+ "version": "1.0.0",
+ "organization": "Engineering",
+ "date": "January 2026",
+ "abstract": "Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.",
+ "references": [
+ "https://react.dev",
+ "https://react.dev/learn/passing-data-deeply-with-context",
+ "https://react.dev/reference/react/use"
+ ]
+}
diff --git a/.agents/skills/vercel-composition-patterns/rules/_sections.md b/.agents/skills/vercel-composition-patterns/rules/_sections.md
new file mode 100644
index 00000000..f921dd41
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/_sections.md
@@ -0,0 +1,29 @@
+# Sections
+
+This file defines all sections, their ordering, impact levels, and descriptions.
+The section ID (in parentheses) is the filename prefix used to group rules.
+
+---
+
+## 1. Component Architecture (architecture)
+
+**Impact:** HIGH
+**Description:** Fundamental patterns for structuring components to avoid prop
+proliferation and enable flexible composition.
+
+## 2. State Management (state)
+
+**Impact:** MEDIUM
+**Description:** Patterns for lifting state and managing shared context across
+composed components.
+
+## 3. Implementation Patterns (patterns)
+
+**Impact:** MEDIUM
+**Description:** Specific techniques for implementing compound components and
+context providers.
+
+## 4. React 19 APIs (react19)
+
+**Impact:** MEDIUM
+**Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
diff --git a/.agents/skills/vercel-composition-patterns/rules/_template.md b/.agents/skills/vercel-composition-patterns/rules/_template.md
new file mode 100644
index 00000000..119a3016
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/_template.md
@@ -0,0 +1,24 @@
+---
+title: Rule Title Here
+impact: MEDIUM
+impactDescription: brief description of impact
+tags: composition, components
+---
+
+## Rule Title Here
+
+Brief explanation of the rule and why it matters.
+
+**Incorrect:**
+
+```tsx
+// Bad code example
+```
+
+**Correct:**
+
+```tsx
+// Good code example
+```
+
+Reference: [Link](https://example.com)
diff --git a/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md b/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md
new file mode 100644
index 00000000..ccee19ce
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md
@@ -0,0 +1,100 @@
+---
+title: Avoid Boolean Prop Proliferation
+impact: CRITICAL
+impactDescription: prevents unmaintainable component variants
+tags: composition, props, architecture
+---
+
+## Avoid Boolean Prop Proliferation
+
+Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
+component behavior. Each boolean doubles possible states and creates
+unmaintainable conditional logic. Use composition instead.
+
+**Incorrect (boolean props create exponential complexity):**
+
+```tsx
+function Composer({
+ onSubmit,
+ isThread,
+ channelId,
+ isDMThread,
+ dmId,
+ isEditing,
+ isForwarding,
+}: Props) {
+ return (
+ <form>
+ <Header />
+ <Input />
+ {isDMThread ? (
+ <AlsoSendToDMField id={dmId} />
+ ) : isThread ? (
+ <AlsoSendToChannelField id={channelId} />
+ ) : null}
+ {isEditing ? (
+ <EditActions />
+ ) : isForwarding ? (
+ <ForwardActions />
+ ) : (
+ <DefaultActions />
+ )}
+ <Footer onSubmit={onSubmit} />
+ </form>
+ )
+}
+```
+
+**Correct (composition eliminates conditionals):**
+
+```tsx
+// Channel composer
+function ChannelComposer() {
+ return (
+ <Composer.Frame>
+ <Composer.Header />
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Attachments />
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+ )
+}
+
+// Thread composer - adds "also send to channel" field
+function ThreadComposer({ channelId }: { channelId: string }) {
+ return (
+ <Composer.Frame>
+ <Composer.Header />
+ <Composer.Input />
+ <AlsoSendToChannelField id={channelId} />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+ )
+}
+
+// Edit composer - different footer actions
+function EditComposer() {
+ return (
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.CancelEdit />
+ <Composer.SaveEdit />
+ </Composer.Footer>
+ </Composer.Frame>
+ )
+}
+```
+
+Each variant is explicit about what it renders. We can share internals without
+sharing a single monolithic parent.
diff --git a/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md b/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md
new file mode 100644
index 00000000..e5e3043c
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md
@@ -0,0 +1,112 @@
+---
+title: Use Compound Components
+impact: HIGH
+impactDescription: enables flexible composition without prop drilling
+tags: composition, compound-components, architecture
+---
+
+## Use Compound Components
+
+Structure complex components as compound components with a shared context. Each
+subcomponent accesses shared state via context, not props. Consumers compose the
+pieces they need.
+
+**Incorrect (monolithic component with render props):**
+
+```tsx
+function Composer({
+ renderHeader,
+ renderFooter,
+ renderActions,
+ showAttachments,
+ showFormatting,
+ showEmojis,
+}: Props) {
+ return (
+ <form>
+ {renderHeader?.()}
+ <Input />
+ {showAttachments && <Attachments />}
+ {renderFooter ? (
+ renderFooter()
+ ) : (
+ <Footer>
+ {showFormatting && <Formatting />}
+ {showEmojis && <Emojis />}
+ {renderActions?.()}
+ </Footer>
+ )}
+ </form>
+ )
+}
+```
+
+**Correct (compound components with shared context):**
+
+```tsx
+const ComposerContext = createContext<ComposerContextValue | null>(null)
+
+function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
+ return (
+ <ComposerContext value={{ state, actions, meta }}>
+ {children}
+ </ComposerContext>
+ )
+}
+
+function ComposerFrame({ children }: { children: React.ReactNode }) {
+ return <form>{children}</form>
+}
+
+function ComposerInput() {
+ const {
+ state,
+ actions: { update },
+ meta: { inputRef },
+ } = use(ComposerContext)
+ return (
+ <TextInput
+ ref={inputRef}
+ value={state.input}
+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}
+ />
+ )
+}
+
+function ComposerSubmit() {
+ const {
+ actions: { submit },
+ } = use(ComposerContext)
+ return <Button onPress={submit}>Send</Button>
+}
+
+// Export as compound component
+const Composer = {
+ Provider: ComposerProvider,
+ Frame: ComposerFrame,
+ Input: ComposerInput,
+ Submit: ComposerSubmit,
+ Header: ComposerHeader,
+ Footer: ComposerFooter,
+ Attachments: ComposerAttachments,
+ Formatting: ComposerFormatting,
+ Emojis: ComposerEmojis,
+}
+```
+
+**Usage:**
+
+```tsx
+<Composer.Provider state={state} actions={actions} meta={meta}>
+ <Composer.Frame>
+ <Composer.Header />
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+</Composer.Provider>
+```
+
+Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
diff --git a/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md b/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md
new file mode 100644
index 00000000..d4345ee3
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md
@@ -0,0 +1,87 @@
+---
+title: Prefer Composing Children Over Render Props
+impact: MEDIUM
+impactDescription: cleaner composition, better readability
+tags: composition, children, render-props
+---
+
+## Prefer Children Over Render Props
+
+Use `children` for composition instead of `renderX` props. Children are more
+readable, compose naturally, and don't require understanding callback
+signatures.
+
+**Incorrect (render props):**
+
+```tsx
+function Composer({
+ renderHeader,
+ renderFooter,
+ renderActions,
+}: {
+ renderHeader?: () => React.ReactNode
+ renderFooter?: () => React.ReactNode
+ renderActions?: () => React.ReactNode
+}) {
+ return (
+ <form>
+ {renderHeader?.()}
+ <Input />
+ {renderFooter ? renderFooter() : <DefaultFooter />}
+ {renderActions?.()}
+ </form>
+ )
+}
+
+// Usage is awkward and inflexible
+return (
+ <Composer
+ renderHeader={() => <CustomHeader />}
+ renderFooter={() => (
+ <>
+ <Formatting />
+ <Emojis />
+ </>
+ )}
+ renderActions={() => <SubmitButton />}
+ />
+)
+```
+
+**Correct (compound components with children):**
+
+```tsx
+function ComposerFrame({ children }: { children: React.ReactNode }) {
+ return <form>{children}</form>
+}
+
+function ComposerFooter({ children }: { children: React.ReactNode }) {
+ return <footer className='flex'>{children}</footer>
+}
+
+// Usage is flexible
+return (
+ <Composer.Frame>
+ <CustomHeader />
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <SubmitButton />
+ </Composer.Footer>
+ </Composer.Frame>
+)
+```
+
+**When render props are appropriate:**
+
+```tsx
+// Render props work well when you need to pass data back
+<List
+ data={items}
+ renderItem={({ item, index }) => <Item item={item} index={index} />}
+/>
+```
+
+Use render props when the parent needs to provide data or state to the child.
+Use children when composing static structure.
diff --git a/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md b/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md
new file mode 100644
index 00000000..56e32e8b
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md
@@ -0,0 +1,100 @@
+---
+title: Create Explicit Component Variants
+impact: MEDIUM
+impactDescription: self-documenting code, no hidden conditionals
+tags: composition, variants, architecture
+---
+
+## Create Explicit Component Variants
+
+Instead of one component with many boolean props, create explicit variant
+components. Each variant composes the pieces it needs. The code documents
+itself.
+
+**Incorrect (one component, many modes):**
+
+```tsx
+// What does this component actually render?
+<Composer
+ isThread
+ isEditing={false}
+ channelId='abc'
+ showAttachments
+ showFormatting={false}
+/>
+```
+
+**Correct (explicit variants):**
+
+```tsx
+// Immediately clear what this renders
+<ThreadComposer channelId="abc" />
+
+// Or
+<EditMessageComposer messageId="xyz" />
+
+// Or
+<ForwardMessageComposer messageId="123" />
+```
+
+Each implementation is unique, explicit and self-contained. Yet they can each
+use shared parts.
+
+**Implementation:**
+
+```tsx
+function ThreadComposer({ channelId }: { channelId: string }) {
+ return (
+ <ThreadProvider channelId={channelId}>
+ <Composer.Frame>
+ <Composer.Input />
+ <AlsoSendToChannelField channelId={channelId} />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+ </ThreadProvider>
+ )
+}
+
+function EditMessageComposer({ messageId }: { messageId: string }) {
+ return (
+ <EditMessageProvider messageId={messageId}>
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.CancelEdit />
+ <Composer.SaveEdit />
+ </Composer.Footer>
+ </Composer.Frame>
+ </EditMessageProvider>
+ )
+}
+
+function ForwardMessageComposer({ messageId }: { messageId: string }) {
+ return (
+ <ForwardMessageProvider messageId={messageId}>
+ <Composer.Frame>
+ <Composer.Input placeholder="Add a message, if you'd like." />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ <Composer.Mentions />
+ </Composer.Footer>
+ </Composer.Frame>
+ </ForwardMessageProvider>
+ )
+}
+```
+
+Each variant is explicit about:
+
+- What provider/state it uses
+- What UI elements it includes
+- What actions are available
+
+No boolean prop combinations to reason about. No impossible states.
diff --git a/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md b/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md
new file mode 100644
index 00000000..e0d8f8a7
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md
@@ -0,0 +1,42 @@
+---
+title: React 19 API Changes
+impact: MEDIUM
+impactDescription: cleaner component definitions and context usage
+tags: react19, refs, context, hooks
+---
+
+## React 19 API Changes
+
+> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
+
+In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
+
+**Incorrect (forwardRef in React 19):**
+
+```tsx
+const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
+ return <TextInput ref={ref} {...props} />
+})
+```
+
+**Correct (ref as a regular prop):**
+
+```tsx
+function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
+ return <TextInput ref={ref} {...props} />
+}
+```
+
+**Incorrect (useContext in React 19):**
+
+```tsx
+const value = useContext(MyContext)
+```
+
+**Correct (use instead of useContext):**
+
+```tsx
+const value = use(MyContext)
+```
+
+`use()` can also be called conditionally, unlike `useContext()`.
diff --git a/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md b/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md
new file mode 100644
index 00000000..d961bede
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md
@@ -0,0 +1,191 @@
+---
+title: Define Generic Context Interfaces for Dependency Injection
+impact: HIGH
+impactDescription: enables dependency-injectable state across use-cases
+tags: composition, context, state, typescript, dependency-injection
+---
+
+## Define Generic Context Interfaces for Dependency Injection
+
+Define a **generic interface** for your component context with three parts:
+`state`, `actions`, and `meta`. This interface is a contract that any provider
+can implement—enabling the same UI components to work with completely different
+state implementations.
+
+**Core principle:** Lift state, compose internals, make state
+dependency-injectable.
+
+**Incorrect (UI coupled to specific state implementation):**
+
+```tsx
+function ComposerInput() {
+ // Tightly coupled to a specific hook
+ const { input, setInput } = useChannelComposerState()
+ return <TextInput value={input} onChangeText={setInput} />
+}
+```
+
+**Correct (generic interface enables dependency injection):**
+
+```tsx
+// Define a GENERIC interface that any provider can implement
+interface ComposerState {
+ input: string
+ attachments: Attachment[]
+ isSubmitting: boolean
+}
+
+interface ComposerActions {
+ update: (updater: (state: ComposerState) => ComposerState) => void
+ submit: () => void
+}
+
+interface ComposerMeta {
+ inputRef: React.RefObject<TextInput>
+}
+
+interface ComposerContextValue {
+ state: ComposerState
+ actions: ComposerActions
+ meta: ComposerMeta
+}
+
+const ComposerContext = createContext<ComposerContextValue | null>(null)
+```
+
+**UI components consume the interface, not the implementation:**
+
+```tsx
+function ComposerInput() {
+ const {
+ state,
+ actions: { update },
+ meta,
+ } = use(ComposerContext)
+
+ // This component works with ANY provider that implements the interface
+ return (
+ <TextInput
+ ref={meta.inputRef}
+ value={state.input}
+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}
+ />
+ )
+}
+```
+
+**Different providers implement the same interface:**
+
+```tsx
+// Provider A: Local state for ephemeral forms
+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
+ const [state, setState] = useState(initialState)
+ const inputRef = useRef(null)
+ const submit = useForwardMessage()
+
+ return (
+ <ComposerContext
+ value={{
+ state,
+ actions: { update: setState, submit },
+ meta: { inputRef },
+ }}
+ >
+ {children}
+ </ComposerContext>
+ )
+}
+
+// Provider B: Global synced state for channels
+function ChannelProvider({ channelId, children }: Props) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+ const inputRef = useRef(null)
+
+ return (
+ <ComposerContext
+ value={{
+ state,
+ actions: { update, submit },
+ meta: { inputRef },
+ }}
+ >
+ {children}
+ </ComposerContext>
+ )
+}
+```
+
+**The same composed UI works with both:**
+
+```tsx
+// Works with ForwardMessageProvider (local state)
+<ForwardMessageProvider>
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Submit />
+ </Composer.Frame>
+</ForwardMessageProvider>
+
+// Works with ChannelProvider (global synced state)
+<ChannelProvider channelId="abc">
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Submit />
+ </Composer.Frame>
+</ChannelProvider>
+```
+
+**Custom UI outside the component can access state and actions:**
+
+The provider boundary is what matters—not the visual nesting. Components that
+need shared state don't have to be inside the `Composer.Frame`. They just need
+to be within the provider.
+
+```tsx
+function ForwardMessageDialog() {
+ return (
+ <ForwardMessageProvider>
+ <Dialog>
+ {/* The composer UI */}
+ <Composer.Frame>
+ <Composer.Input placeholder="Add a message, if you'd like." />
+ <Composer.Footer>
+ <Composer.Formatting />
+ <Composer.Emojis />
+ </Composer.Footer>
+ </Composer.Frame>
+
+ {/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
+ <MessagePreview />
+
+ {/* Actions at the bottom of the dialog */}
+ <DialogActions>
+ <CancelButton />
+ <ForwardButton />
+ </DialogActions>
+ </Dialog>
+ </ForwardMessageProvider>
+ )
+}
+
+// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
+function ForwardButton() {
+ const {
+ actions: { submit },
+ } = use(ComposerContext)
+ return <Button onPress={submit}>Forward</Button>
+}
+
+// This preview lives OUTSIDE Composer.Frame but can read composer's state!
+function MessagePreview() {
+ const { state } = use(ComposerContext)
+ return <Preview message={state.input} attachments={state.attachments} />
+}
+```
+
+The `ForwardButton` and `MessagePreview` are not visually inside the composer
+box, but they can still access its state and actions. This is the power of
+lifting state into providers.
+
+The UI is reusable bits you compose together. The state is dependency-injected
+by the provider. Swap the provider, keep the UI.
diff --git a/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md b/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md
new file mode 100644
index 00000000..71a5afaa
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md
@@ -0,0 +1,113 @@
+---
+title: Decouple State Management from UI
+impact: MEDIUM
+impactDescription: enables swapping state implementations without changing UI
+tags: composition, state, architecture
+---
+
+## Decouple State Management from UI
+
+The provider component should be the only place that knows how state is managed.
+UI components consume the context interface—they don't know if state comes from
+useState, Zustand, or a server sync.
+
+**Incorrect (UI coupled to state implementation):**
+
+```tsx
+function ChannelComposer({ channelId }: { channelId: string }) {
+ // UI component knows about global state implementation
+ const state = useGlobalChannelState(channelId)
+ const { submit, updateInput } = useChannelSync(channelId)
+
+ return (
+ <Composer.Frame>
+ <Composer.Input
+ value={state.input}
+ onChange={(text) => sync.updateInput(text)}
+ />
+ <Composer.Submit onPress={() => sync.submit()} />
+ </Composer.Frame>
+ )
+}
+```
+
+**Correct (state management isolated in provider):**
+
+```tsx
+// Provider handles all state management details
+function ChannelProvider({
+ channelId,
+ children,
+}: {
+ channelId: string
+ children: React.ReactNode
+}) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+ const inputRef = useRef(null)
+
+ return (
+ <Composer.Provider
+ state={state}
+ actions={{ update, submit }}
+ meta={{ inputRef }}
+ >
+ {children}
+ </Composer.Provider>
+ )
+}
+
+// UI component only knows about the context interface
+function ChannelComposer() {
+ return (
+ <Composer.Frame>
+ <Composer.Header />
+ <Composer.Input />
+ <Composer.Footer>
+ <Composer.Submit />
+ </Composer.Footer>
+ </Composer.Frame>
+ )
+}
+
+// Usage
+function Channel({ channelId }: { channelId: string }) {
+ return (
+ <ChannelProvider channelId={channelId}>
+ <ChannelComposer />
+ </ChannelProvider>
+ )
+}
+```
+
+**Different providers, same UI:**
+
+```tsx
+// Local state for ephemeral forms
+function ForwardMessageProvider({ children }) {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+
+ return (
+ <Composer.Provider
+ state={state}
+ actions={{ update: setState, submit: forwardMessage }}
+ >
+ {children}
+ </Composer.Provider>
+ )
+}
+
+// Global synced state for channels
+function ChannelProvider({ channelId, children }) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+
+ return (
+ <Composer.Provider state={state} actions={{ update, submit }}>
+ {children}
+ </Composer.Provider>
+ )
+}
+```
+
+The same `Composer.Input` component works with both providers because it only
+depends on the context interface, not the implementation.
diff --git a/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md b/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md
new file mode 100644
index 00000000..d7fe27b5
--- /dev/null
+++ b/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md
@@ -0,0 +1,125 @@
+---
+title: Lift State into Provider Components
+impact: HIGH
+impactDescription: enables state sharing outside component boundaries
+tags: composition, state, context, providers
+---
+
+## Lift State into Provider Components
+
+Move state management into dedicated provider components. This allows sibling
+components outside the main UI to access and modify state without prop drilling
+or awkward refs.
+
+**Incorrect (state trapped inside component):**
+
+```tsx
+function ForwardMessageComposer() {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+
+ return (
+ <Composer.Frame>
+ <Composer.Input />
+ <Composer.Footer />
+ </Composer.Frame>
+ )
+}
+
+// Problem: How does this button access composer state?
+function ForwardMessageDialog() {
+ return (
+ <Dialog>
+ <ForwardMessageComposer />
+ <MessagePreview /> {/* Needs composer state */}
+ <DialogActions>
+ <CancelButton />
+ <ForwardButton /> {/* Needs to call submit */}
+ </DialogActions>
+ </Dialog>
+ )
+}
+```
+
+**Incorrect (useEffect to sync state up):**
+
+```tsx
+function ForwardMessageDialog() {
+ const [input, setInput] = useState('')
+ return (
+ <Dialog>
+ <ForwardMessageComposer onInputChange={setInput} />
+ <MessagePreview input={input} />
+ </Dialog>
+ )
+}
+
+function ForwardMessageComposer({ onInputChange }) {
+ const [state, setState] = useState(initialState)
+ useEffect(() => {
+ onInputChange(state.input) // Sync on every change 😬
+ }, [state.input])
+}
+```
+
+**Incorrect (reading state from ref on submit):**
+
+```tsx
+function ForwardMessageDialog() {
+ const stateRef = useRef(null)
+ return (
+ <Dialog>
+ <ForwardMessageComposer stateRef={stateRef} />
+ <ForwardButton onPress={() => submit(stateRef.current)} />
+ </Dialog>
+ )
+}
+```
+
+**Correct (state lifted to provider):**
+
+```tsx
+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+ const inputRef = useRef(null)
+
+ return (
+ <Composer.Provider
+ state={state}
+ actions={{ update: setState, submit: forwardMessage }}
+ meta={{ inputRef }}
+ >
+ {children}
+ </Composer.Provider>
+ )
+}
+
+function ForwardMessageDialog() {
+ return (
+ <ForwardMessageProvider>
+ <Dialog>
+ <ForwardMessageComposer />
+ <MessagePreview /> {/* Custom components can access state and actions */}
+ <DialogActions>
+ <CancelButton />
+ <ForwardButton /> {/* Custom components can access state and actions */}
+ </DialogActions>
+ </Dialog>
+ </ForwardMessageProvider>
+ )
+}
+
+function ForwardButton() {
+ const { actions } = use(Composer.Context)
+ return <Button onPress={actions.submit}>Forward</Button>
+}
+```
+
+The ForwardButton lives outside the Composer.Frame but still has access to the
+submit action because it's within the provider. Even though it's a one-off
+component, it can still access the composer's state and actions from outside the
+UI itself.
+
+**Key insight:** Components that need shared state don't have to be visually
+nested inside each other—they just need to be within the same provider.
diff --git a/.agents/skills/vercel-react-best-practices/AGENTS.md b/.agents/skills/vercel-react-best-practices/AGENTS.md
new file mode 100644
index 00000000..4e340a50
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/AGENTS.md
@@ -0,0 +1,3810 @@
+# React Best Practices
+
+**Version 1.0.0**
+Vercel Engineering
+January 2026
+
+> **Note:**
+> This document is mainly for agents and LLMs to follow when maintaining,
+> generating, or refactoring React and Next.js codebases. Humans
+> may also find it useful, but guidance here is optimized for automation
+> and consistency by AI-assisted workflows.
+
+---
+
+## Abstract
+
+Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.
+
+---
+
+## Table of Contents
+
+1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**
+ - 1.1 [Check Cheap Conditions Before Async Flags](#11-check-cheap-conditions-before-async-flags)
+ - 1.2 [Defer Await Until Needed](#12-defer-await-until-needed)
+ - 1.3 [Dependency-Based Parallelization](#13-dependency-based-parallelization)
+ - 1.4 [Prevent Waterfall Chains in API Routes](#14-prevent-waterfall-chains-in-api-routes)
+ - 1.5 [Promise.all() for Independent Operations](#15-promiseall-for-independent-operations)
+ - 1.6 [Strategic Suspense Boundaries](#16-strategic-suspense-boundaries)
+2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**
+ - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports)
+ - 2.2 [Conditional Module Loading](#22-conditional-module-loading)
+ - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries)
+ - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components)
+ - 2.5 [Prefer Statically Analyzable Paths](#25-prefer-statically-analyzable-paths)
+ - 2.6 [Preload Based on User Intent](#26-preload-based-on-user-intent)
+3. [Server-Side Performance](#3-server-side-performance) — **HIGH**
+ - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes)
+ - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props)
+ - 3.3 [Avoid Shared Module State for Request Data](#33-avoid-shared-module-state-for-request-data)
+ - 3.4 [Cross-Request LRU Caching](#34-cross-request-lru-caching)
+ - 3.5 [Hoist Static I/O to Module Level](#35-hoist-static-io-to-module-level)
+ - 3.6 [Minimize Serialization at RSC Boundaries](#36-minimize-serialization-at-rsc-boundaries)
+ - 3.7 [Parallel Data Fetching with Component Composition](#37-parallel-data-fetching-with-component-composition)
+ - 3.8 [Parallel Nested Data Fetching](#38-parallel-nested-data-fetching)
+ - 3.9 [Per-Request Deduplication with React.cache()](#39-per-request-deduplication-with-reactcache)
+ - 3.10 [Use after() for Non-Blocking Operations](#310-use-after-for-non-blocking-operations)
+4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**
+ - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners)
+ - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance)
+ - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication)
+ - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data)
+5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM**
+ - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering)
+ - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point)
+ - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo)
+ - 5.4 [Don't Define Components Inside Components](#54-dont-define-components-inside-components)
+ - 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#55-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant)
+ - 5.6 [Extract to Memoized Components](#56-extract-to-memoized-components)
+ - 5.7 [Narrow Effect Dependencies](#57-narrow-effect-dependencies)
+ - 5.8 [Put Interaction Logic in Event Handlers](#58-put-interaction-logic-in-event-handlers)
+ - 5.9 [Split Combined Hook Computations](#59-split-combined-hook-computations)
+ - 5.10 [Subscribe to Derived State](#510-subscribe-to-derived-state)
+ - 5.11 [Use Functional setState Updates](#511-use-functional-setstate-updates)
+ - 5.12 [Use Lazy State Initialization](#512-use-lazy-state-initialization)
+ - 5.13 [Use Transitions for Non-Urgent Updates](#513-use-transitions-for-non-urgent-updates)
+ - 5.14 [Use useDeferredValue for Expensive Derived Renders](#514-use-usedeferredvalue-for-expensive-derived-renders)
+ - 5.15 [Use useRef for Transient Values](#515-use-useref-for-transient-values)
+6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**
+ - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element)
+ - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists)
+ - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements)
+ - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision)
+ - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering)
+ - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches)
+ - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide)
+ - 6.8 [Use defer or async on Script Tags](#68-use-defer-or-async-on-script-tags)
+ - 6.9 [Use Explicit Conditional Rendering](#69-use-explicit-conditional-rendering)
+ - 6.10 [Use React DOM Resource Hints](#610-use-react-dom-resource-hints)
+ - 6.11 [Use useTransition Over Manual Loading States](#611-use-usetransition-over-manual-loading-states)
+7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**
+ - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing)
+ - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups)
+ - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops)
+ - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls)
+ - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls)
+ - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations)
+ - 7.7 [Defer Non-Critical Work with requestIdleCallback](#77-defer-non-critical-work-with-requestidlecallback)
+ - 7.8 [Early Length Check for Array Comparisons](#78-early-length-check-for-array-comparisons)
+ - 7.9 [Early Return from Functions](#79-early-return-from-functions)
+ - 7.10 [Hoist RegExp Creation](#710-hoist-regexp-creation)
+ - 7.11 [Use flatMap to Map and Filter in One Pass](#711-use-flatmap-to-map-and-filter-in-one-pass)
+ - 7.12 [Use Loop for Min/Max Instead of Sort](#712-use-loop-for-minmax-instead-of-sort)
+ - 7.13 [Use Set/Map for O(1) Lookups](#713-use-setmap-for-o1-lookups)
+ - 7.14 [Use toSorted() Instead of sort() for Immutability](#714-use-tosorted-instead-of-sort-for-immutability)
+8. [Advanced Patterns](#8-advanced-patterns) — **LOW**
+ - 8.1 [Do Not Put Effect Events in Dependency Arrays](#81-do-not-put-effect-events-in-dependency-arrays)
+ - 8.2 [Initialize App Once, Not Per Mount](#82-initialize-app-once-not-per-mount)
+ - 8.3 [Store Event Handlers in Refs](#83-store-event-handlers-in-refs)
+ - 8.4 [useEffectEvent for Stable Callback Refs](#84-useeffectevent-for-stable-callback-refs)
+
+---
+
+## 1. Eliminating Waterfalls
+
+**Impact: CRITICAL**
+
+Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
+
+### 1.1 Check Cheap Conditions Before Async Flags
+
+**Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)**
+
+When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
+
+This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
+
+**Incorrect:**
+
+```typescript
+const someFlag = await getFlag()
+
+if (someFlag && someCondition) {
+ // ...
+}
+```
+
+**Correct:**
+
+```typescript
+if (someCondition) {
+ const someFlag = await getFlag()
+ if (someFlag) {
+ // ...
+ }
+}
+```
+
+This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
+
+Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
+
+### 1.2 Defer Await Until Needed
+
+**Impact: HIGH (avoids blocking unused code paths)**
+
+Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
+
+**Incorrect: blocks both branches**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ const userData = await fetchUserData(userId)
+
+ if (skipProcessing) {
+ // Returns immediately but still waited for userData
+ return { skipped: true }
+ }
+
+ // Only this branch uses userData
+ return processUserData(userData)
+}
+```
+
+**Correct: only blocks when needed**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ if (skipProcessing) {
+ // Returns immediately without waiting
+ return { skipped: true }
+ }
+
+ // Fetch only when needed
+ const userData = await fetchUserData(userId)
+ return processUserData(userData)
+}
+```
+
+**Another example: early return optimization**
+
+```typescript
+// Incorrect: always fetches permissions
+async function updateResource(resourceId: string, userId: string) {
+ const permissions = await fetchPermissions(userId)
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+
+// Correct: fetches only when needed
+async function updateResource(resourceId: string, userId: string) {
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ const permissions = await fetchPermissions(userId)
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+```
+
+This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
+
+For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
+
+### 1.3 Dependency-Based Parallelization
+
+**Impact: CRITICAL (2-10× improvement)**
+
+For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
+
+**Incorrect: profile waits for config unnecessarily**
+
+```typescript
+const [user, config] = await Promise.all([
+ fetchUser(),
+ fetchConfig()
+])
+const profile = await fetchProfile(user.id)
+```
+
+**Correct: config and profile run in parallel**
+
+```typescript
+import { all } from 'better-all'
+
+const { user, config, profile } = await all({
+ async user() { return fetchUser() },
+ async config() { return fetchConfig() },
+ async profile() {
+ return fetchProfile((await this.$.user).id)
+ }
+})
+```
+
+**Alternative without extra dependencies:**
+
+```typescript
+const userPromise = fetchUser()
+const profilePromise = userPromise.then(user => fetchProfile(user.id))
+
+const [user, config, profile] = await Promise.all([
+ userPromise,
+ fetchConfig(),
+ profilePromise
+])
+```
+
+We can also create all the promises first, and do `Promise.all()` at the end.
+
+Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
+
+### 1.4 Prevent Waterfall Chains in API Routes
+
+**Impact: CRITICAL (2-10× improvement)**
+
+In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
+
+**Incorrect: config waits for auth, data waits for both**
+
+```typescript
+export async function GET(request: Request) {
+ const session = await auth()
+ const config = await fetchConfig()
+ const data = await fetchData(session.user.id)
+ return Response.json({ data, config })
+}
+```
+
+**Correct: auth and config start immediately**
+
+```typescript
+export async function GET(request: Request) {
+ const sessionPromise = auth()
+ const configPromise = fetchConfig()
+ const session = await sessionPromise
+ const [config, data] = await Promise.all([
+ configPromise,
+ fetchData(session.user.id)
+ ])
+ return Response.json({ data, config })
+}
+```
+
+For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
+
+### 1.5 Promise.all() for Independent Operations
+
+**Impact: CRITICAL (2-10× improvement)**
+
+When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
+
+**Incorrect: sequential execution, 3 round trips**
+
+```typescript
+const user = await fetchUser()
+const posts = await fetchPosts()
+const comments = await fetchComments()
+```
+
+**Correct: parallel execution, 1 round trip**
+
+```typescript
+const [user, posts, comments] = await Promise.all([
+ fetchUser(),
+ fetchPosts(),
+ fetchComments()
+])
+```
+
+### 1.6 Strategic Suspense Boundaries
+
+**Impact: HIGH (faster initial paint)**
+
+Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
+
+**Incorrect: wrapper blocked by data fetching**
+
+```tsx
+async function Page() {
+ const data = await fetchData() // Blocks entire page
+
+ return (
+ <div>
+ <div>Sidebar</div>
+ <div>Header</div>
+ <div>
+ <DataDisplay data={data} />
+ </div>
+ <div>Footer</div>
+ </div>
+ )
+}
+```
+
+The entire layout waits for data even though only the middle section needs it.
+
+**Correct: wrapper shows immediately, data streams in**
+
+```tsx
+function Page() {
+ return (
+ <div>
+ <div>Sidebar</div>
+ <div>Header</div>
+ <div>
+ <Suspense fallback={<Skeleton />}>
+ <DataDisplay />
+ </Suspense>
+ </div>
+ <div>Footer</div>
+ </div>
+ )
+}
+
+async function DataDisplay() {
+ const data = await fetchData() // Only blocks this component
+ return <div>{data.content}</div>
+}
+```
+
+Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
+
+**Alternative: share promise across components**
+
+```tsx
+function Page() {
+ // Start fetch immediately, but don't await
+ const dataPromise = fetchData()
+
+ return (
+ <div>
+ <div>Sidebar</div>
+ <div>Header</div>
+ <Suspense fallback={<Skeleton />}>
+ <DataDisplay dataPromise={dataPromise} />
+ <DataSummary dataPromise={dataPromise} />
+ </Suspense>
+ <div>Footer</div>
+ </div>
+ )
+}
+
+function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
+ const data = use(dataPromise) // Unwraps the promise
+ return <div>{data.content}</div>
+}
+
+function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
+ const data = use(dataPromise) // Reuses the same promise
+ return <div>{data.summary}</div>
+}
+```
+
+Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
+
+**When NOT to use this pattern:**
+
+- Critical data needed for layout decisions (affects positioning)
+
+- SEO-critical content above the fold
+
+- Small, fast queries where suspense overhead isn't worth it
+
+- When you want to avoid layout shift (loading → content jump)
+
+**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
+
+---
+
+## 2. Bundle Size Optimization
+
+**Impact: CRITICAL**
+
+Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
+
+### 2.1 Avoid Barrel File Imports
+
+**Impact: CRITICAL (200-800ms import cost, slow builds)**
+
+Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
+
+Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
+
+**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
+
+**Incorrect: imports entire library**
+
+```tsx
+import { Check, X, Menu } from 'lucide-react'
+// Loads 1,583 modules, takes ~2.8s extra in dev
+// Runtime cost: 200-800ms on every cold start
+
+import { Button, TextField } from '@mui/material'
+// Loads 2,225 modules, takes ~4.2s extra in dev
+```
+
+**Correct - Next.js 13.5+ (recommended):**
+
+```tsx
+// Keep the standard imports - Next.js transforms them to direct imports
+import { Check, X, Menu } from 'lucide-react'
+// Full TypeScript support, no manual path wrangling
+```
+
+This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
+
+**Correct - Direct imports (non-Next.js projects):**
+
+```tsx
+import Button from '@mui/material/Button'
+import TextField from '@mui/material/TextField'
+// Loads only what you use
+```
+
+> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
+
+These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
+
+Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
+
+Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
+
+### 2.2 Conditional Module Loading
+
+**Impact: HIGH (loads large data only when needed)**
+
+Load large data or modules only when a feature is activated.
+
+**Example: lazy-load animation frames**
+
+```tsx
+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
+ const [frames, setFrames] = useState<Frame[] | null>(null)
+
+ useEffect(() => {
+ if (enabled && !frames && typeof window !== 'undefined') {
+ import('./animation-frames.js')
+ .then(mod => setFrames(mod.frames))
+ .catch(() => setEnabled(false))
+ }
+ }, [enabled, frames, setEnabled])
+
+ if (!frames) return <Skeleton />
+ return <Canvas frames={frames} />
+}
+```
+
+The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
+
+### 2.3 Defer Non-Critical Third-Party Libraries
+
+**Impact: MEDIUM (loads after hydration)**
+
+Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
+
+**Incorrect: blocks initial bundle**
+
+```tsx
+import { Analytics } from '@vercel/analytics/react'
+
+export default function RootLayout({ children }) {
+ return (
+ <html>
+ <body>
+ {children}
+ <Analytics />
+ </body>
+ </html>
+ )
+}
+```
+
+**Correct: loads after hydration**
+
+```tsx
+import dynamic from 'next/dynamic'
+
+const Analytics = dynamic(
+ () => import('@vercel/analytics/react').then(m => m.Analytics),
+ { ssr: false }
+)
+
+export default function RootLayout({ children }) {
+ return (
+ <html>
+ <body>
+ {children}
+ <Analytics />
+ </body>
+ </html>
+ )
+}
+```
+
+### 2.4 Dynamic Imports for Heavy Components
+
+**Impact: CRITICAL (directly affects TTI and LCP)**
+
+Use `next/dynamic` to lazy-load large components not needed on initial render.
+
+**Incorrect: Monaco bundles with main chunk ~300KB**
+
+```tsx
+import { MonacoEditor } from './monaco-editor'
+
+function CodePanel({ code }: { code: string }) {
+ return <MonacoEditor value={code} />
+}
+```
+
+**Correct: Monaco loads on demand**
+
+```tsx
+import dynamic from 'next/dynamic'
+
+const MonacoEditor = dynamic(
+ () => import('./monaco-editor').then(m => m.MonacoEditor),
+ { ssr: false }
+)
+
+function CodePanel({ code }: { code: string }) {
+ return <MonacoEditor value={code} />
+}
+```
+
+### 2.5 Prefer Statically Analyzable Paths
+
+**Impact: HIGH (avoids accidental broad bundles and file traces)**
+
+Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
+
+Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.
+
+When analysis becomes too broad, the cost is real:
+
+- Larger server bundles
+
+- Slower builds
+
+- Worse cold starts
+
+- More memory use
+
+**Incorrect: the bundler cannot tell what may be imported**
+
+```ts
+const PAGE_MODULES = {
+ home: './pages/home',
+ settings: './pages/settings',
+} as const
+
+const Page = await import(PAGE_MODULES[pageName])
+```
+
+**Correct: use an explicit map of allowed modules**
+
+```ts
+const PAGE_MODULES = {
+ home: () => import('./pages/home'),
+ settings: () => import('./pages/settings'),
+} as const
+
+const Page = await PAGE_MODULES[pageName]()
+```
+
+**Incorrect: a 2-value enum still hides the final path from static analysis**
+
+```ts
+const baseDir = path.join(process.cwd(), 'content/' + contentKind)
+```
+
+**Correct: make each final path literal at the callsite**
+
+```ts
+const baseDir =
+ kind === ContentKind.Blog
+ ? path.join(process.cwd(), 'content/blog')
+ : path.join(process.cwd(), 'content/docs')
+```
+
+In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.
+
+Reference: [https://nextjs.org/docs/app/api-reference/config/next-config-js/output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [https://nextjs.org/learn/seo/dynamic-imports](https://nextjs.org/learn/seo/dynamic-imports), [https://vite.dev/guide/features.html](https://vite.dev/guide/features.html), [https://esbuild.github.io/api/](https://esbuild.github.io/api/), [https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [https://webpack.js.org/guides/dependency-management/](https://webpack.js.org/guides/dependency-management/)
+
+### 2.6 Preload Based on User Intent
+
+**Impact: MEDIUM (reduces perceived latency)**
+
+Preload heavy bundles before they're needed to reduce perceived latency.
+
+**Example: preload on hover/focus**
+
+```tsx
+function EditorButton({ onClick }: { onClick: () => void }) {
+ const preload = () => {
+ if (typeof window !== 'undefined') {
+ void import('./monaco-editor')
+ }
+ }
+
+ return (
+ <button
+ onMouseEnter={preload}
+ onFocus={preload}
+ onClick={onClick}
+ >
+ Open Editor
+ </button>
+ )
+}
+```
+
+**Example: preload when feature flag is enabled**
+
+```tsx
+function FlagsProvider({ children, flags }: Props) {
+ useEffect(() => {
+ if (flags.editorEnabled && typeof window !== 'undefined') {
+ void import('./monaco-editor').then(mod => mod.init())
+ }
+ }, [flags.editorEnabled])
+
+ return <FlagsContext.Provider value={flags}>
+ {children}
+ </FlagsContext.Provider>
+}
+```
+
+The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
+
+---
+
+## 3. Server-Side Performance
+
+**Impact: HIGH**
+
+Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
+
+### 3.1 Authenticate Server Actions Like API Routes
+
+**Impact: CRITICAL (prevents unauthorized access to server mutations)**
+
+Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
+
+Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
+
+**Incorrect: no authentication check**
+
+```typescript
+'use server'
+
+export async function deleteUser(userId: string) {
+ // Anyone can call this! No auth check
+ await db.user.delete({ where: { id: userId } })
+ return { success: true }
+}
+```
+
+**Correct: authentication inside the action**
+
+```typescript
+'use server'
+
+import { verifySession } from '@/lib/auth'
+import { unauthorized } from '@/lib/errors'
+
+export async function deleteUser(userId: string) {
+ // Always check auth inside the action
+ const session = await verifySession()
+
+ if (!session) {
+ throw unauthorized('Must be logged in')
+ }
+
+ // Check authorization too
+ if (session.user.role !== 'admin' && session.user.id !== userId) {
+ throw unauthorized('Cannot delete other users')
+ }
+
+ await db.user.delete({ where: { id: userId } })
+ return { success: true }
+}
+```
+
+**With input validation:**
+
+```typescript
+'use server'
+
+import { verifySession } from '@/lib/auth'
+import { z } from 'zod'
+
+const updateProfileSchema = z.object({
+ userId: z.string().uuid(),
+ name: z.string().min(1).max(100),
+ email: z.string().email()
+})
+
+export async function updateProfile(data: unknown) {
+ // Validate input first
+ const validated = updateProfileSchema.parse(data)
+
+ // Then authenticate
+ const session = await verifySession()
+ if (!session) {
+ throw new Error('Unauthorized')
+ }
+
+ // Then authorize
+ if (session.user.id !== validated.userId) {
+ throw new Error('Can only update own profile')
+ }
+
+ // Finally perform the mutation
+ await db.user.update({
+ where: { id: validated.userId },
+ data: {
+ name: validated.name,
+ email: validated.email
+ }
+ })
+
+ return { success: true }
+}
+```
+
+Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
+
+### 3.2 Avoid Duplicate Serialization in RSC Props
+
+**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
+
+RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
+
+**Incorrect: duplicates array**
+
+```tsx
+// RSC: sends 6 strings (2 arrays × 3 items)
+<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
+```
+
+**Correct: sends 3 strings**
+
+```tsx
+// RSC: send once
+<ClientList usernames={usernames} />
+
+// Client: transform there
+'use client'
+const sorted = useMemo(() => [...usernames].sort(), [usernames])
+```
+
+**Nested deduplication behavior:**
+
+```tsx
+// string[] - duplicates everything
+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
+
+// object[] - duplicates array structure only
+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
+```
+
+Deduplication works recursively. Impact varies by data type:
+
+- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
+
+- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
+
+**Operations breaking deduplication: create new references**
+
+- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
+
+- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
+
+**More examples:**
+
+```tsx
+// ❌ Bad
+<C users={users} active={users.filter(u => u.active)} />
+<C product={product} productName={product.name} />
+
+// ✅ Good
+<C users={users} />
+<C product={product} />
+// Do filtering/destructuring in client
+```
+
+**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
+
+### 3.3 Avoid Shared Module State for Request Data
+
+**Impact: HIGH (prevents concurrency bugs and request data leaks)**
+
+For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.
+
+Treat module scope on the server as process-wide shared memory, not request-local state.
+
+**Incorrect: request data leaks across concurrent renders**
+
+```tsx
+let currentUser: User | null = null
+
+export default async function Page() {
+ currentUser = await auth()
+ return <Dashboard />
+}
+
+async function Dashboard() {
+ return <div>{currentUser?.name}</div>
+}
+```
+
+If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.
+
+**Correct: keep request data local to the render tree**
+
+```tsx
+export default async function Page() {
+ const user = await auth()
+ return <Dashboard user={user} />
+}
+
+function Dashboard({ user }: { user: User | null }) {
+ return <div>{user?.name}</div>
+}
+```
+
+Safe exceptions:
+
+- Immutable static assets or config loaded once at module scope
+
+- Shared caches intentionally designed for cross-request reuse and keyed correctly
+
+- Process-wide singletons that do not store request- or user-specific mutable data
+
+For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).
+
+### 3.4 Cross-Request LRU Caching
+
+**Impact: HIGH (caches across requests)**
+
+`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
+
+**Implementation:**
+
+```typescript
+import { LRUCache } from 'lru-cache'
+
+const cache = new LRUCache<string, any>({
+ max: 1000,
+ ttl: 5 * 60 * 1000 // 5 minutes
+})
+
+export async function getUser(id: string) {
+ const cached = cache.get(id)
+ if (cached) return cached
+
+ const user = await db.user.findUnique({ where: { id } })
+ cache.set(id, user)
+ return user
+}
+
+// Request 1: DB query, result cached
+// Request 2: cache hit, no DB query
+```
+
+Use when sequential user actions hit multiple endpoints needing the same data within seconds.
+
+**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
+
+**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
+
+Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
+
+### 3.5 Hoist Static I/O to Module Level
+
+**Impact: HIGH (avoids repeated file/network I/O per request)**
+
+When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
+
+**Incorrect: reads font file on every request**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+
+export async function GET(request: Request) {
+ // Runs on EVERY request - expensive!
+ const fontData = await fetch(
+ new URL('./fonts/Inter.ttf', import.meta.url)
+ ).then(res => res.arrayBuffer())
+
+ const logoData = await fetch(
+ new URL('./images/logo.png', import.meta.url)
+ ).then(res => res.arrayBuffer())
+
+ return new ImageResponse(
+ <div style={{ fontFamily: 'Inter' }}>
+ <img src={logoData} />
+ Hello World
+ </div>,
+ { fonts: [{ name: 'Inter', data: fontData }] }
+ )
+}
+```
+
+**Correct: loads once at module initialization**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+
+// Module-level: runs ONCE when module is first imported
+const fontData = fetch(
+ new URL('./fonts/Inter.ttf', import.meta.url)
+).then(res => res.arrayBuffer())
+
+const logoData = fetch(
+ new URL('./images/logo.png', import.meta.url)
+).then(res => res.arrayBuffer())
+
+export async function GET(request: Request) {
+ // Await the already-started promises
+ const [font, logo] = await Promise.all([fontData, logoData])
+
+ return new ImageResponse(
+ <div style={{ fontFamily: 'Inter' }}>
+ <img src={logo} />
+ Hello World
+ </div>,
+ { fonts: [{ name: 'Inter', data: font }] }
+ )
+}
+```
+
+**Correct: synchronous fs at module level**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+import { readFileSync } from 'fs'
+import { join } from 'path'
+
+// Synchronous read at module level - blocks only during module init
+const fontData = readFileSync(
+ join(process.cwd(), 'public/fonts/Inter.ttf')
+)
+
+const logoData = readFileSync(
+ join(process.cwd(), 'public/images/logo.png')
+)
+
+export async function GET(request: Request) {
+ return new ImageResponse(
+ <div style={{ fontFamily: 'Inter' }}>
+ <img src={logoData} />
+ Hello World
+ </div>,
+ { fonts: [{ name: 'Inter', data: fontData }] }
+ )
+}
+```
+
+**Incorrect: reads config on every call**
+
+```typescript
+import fs from 'node:fs/promises'
+
+export async function processRequest(data: Data) {
+ const config = JSON.parse(
+ await fs.readFile('./config.json', 'utf-8')
+ )
+ const template = await fs.readFile('./template.html', 'utf-8')
+
+ return render(template, data, config)
+}
+```
+
+**Correct: hoists config and template to module level**
+
+```typescript
+import fs from 'node:fs/promises'
+
+const configPromise = fs
+ .readFile('./config.json', 'utf-8')
+ .then(JSON.parse)
+const templatePromise = fs.readFile('./template.html', 'utf-8')
+
+export async function processRequest(data: Data) {
+ const [config, template] = await Promise.all([
+ configPromise,
+ templatePromise,
+ ])
+
+ return render(template, data, config)
+}
+```
+
+When to use this pattern:
+
+- Loading fonts for OG image generation
+
+- Loading static logos, icons, or watermarks
+
+- Reading configuration files that don't change at runtime
+
+- Loading email templates or other static templates
+
+- Any static asset that's the same across all requests
+
+When not to use this pattern:
+
+- Assets that vary per request or user
+
+- Files that may change during runtime (use caching with TTL instead)
+
+- Large files that would consume too much memory if kept loaded
+
+- Sensitive data that shouldn't persist in memory
+
+With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
+
+In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
+
+### 3.6 Minimize Serialization at RSC Boundaries
+
+**Impact: HIGH (reduces data transfer size)**
+
+The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
+
+**Incorrect: serializes all 50 fields**
+
+```tsx
+async function Page() {
+ const user = await fetchUser() // 50 fields
+ return <Profile user={user} />
+}
+
+'use client'
+function Profile({ user }: { user: User }) {
+ return <div>{user.name}</div> // uses 1 field
+}
+```
+
+**Correct: serializes only 1 field**
+
+```tsx
+async function Page() {
+ const user = await fetchUser()
+ return <Profile name={user.name} />
+}
+
+'use client'
+function Profile({ name }: { name: string }) {
+ return <div>{name}</div>
+}
+```
+
+### 3.7 Parallel Data Fetching with Component Composition
+
+**Impact: CRITICAL (eliminates server-side waterfalls)**
+
+React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
+
+**Incorrect: Sidebar waits for Page's fetch to complete**
+
+```tsx
+export default async function Page() {
+ const header = await fetchHeader()
+ return (
+ <div>
+ <div>{header}</div>
+ <Sidebar />
+ </div>
+ )
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return <nav>{items.map(renderItem)}</nav>
+}
+```
+
+**Correct: both fetch simultaneously**
+
+```tsx
+async function Header() {
+ const data = await fetchHeader()
+ return <div>{data}</div>
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return <nav>{items.map(renderItem)}</nav>
+}
+
+export default function Page() {
+ return (
+ <div>
+ <Header />
+ <Sidebar />
+ </div>
+ )
+}
+```
+
+**Alternative with children prop:**
+
+```tsx
+async function Header() {
+ const data = await fetchHeader()
+ return <div>{data}</div>
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return <nav>{items.map(renderItem)}</nav>
+}
+
+function Layout({ children }: { children: ReactNode }) {
+ return (
+ <div>
+ <Header />
+ {children}
+ </div>
+ )
+}
+
+export default function Page() {
+ return (
+ <Layout>
+ <Sidebar />
+ </Layout>
+ )
+}
+```
+
+### 3.8 Parallel Nested Data Fetching
+
+**Impact: CRITICAL (eliminates server-side waterfalls)**
+
+When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.
+
+**Incorrect: a single slow item blocks all nested fetches**
+
+```tsx
+const chats = await Promise.all(
+ chatIds.map(id => getChat(id))
+)
+
+const chatAuthors = await Promise.all(
+ chats.map(chat => getUser(chat.author))
+)
+```
+
+If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.
+
+**Correct: each item chains its own nested fetch**
+
+```tsx
+const chatAuthors = await Promise.all(
+ chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
+)
+```
+
+Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.
+
+### 3.9 Per-Request Deduplication with React.cache()
+
+**Impact: MEDIUM (deduplicates within request)**
+
+Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
+
+**Usage:**
+
+```typescript
+import { cache } from 'react'
+
+export const getCurrentUser = cache(async () => {
+ const session = await auth()
+ if (!session?.user?.id) return null
+ return await db.user.findUnique({
+ where: { id: session.user.id }
+ })
+})
+```
+
+Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
+
+**Avoid inline objects as arguments:**
+
+`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
+
+**Incorrect: always cache miss**
+
+```typescript
+const getUser = cache(async (params: { uid: number }) => {
+ return await db.user.findUnique({ where: { id: params.uid } })
+})
+
+// Each call creates new object, never hits cache
+getUser({ uid: 1 })
+getUser({ uid: 1 }) // Cache miss, runs query again
+```
+
+**Correct: cache hit**
+
+```typescript
+const params = { uid: 1 }
+getUser(params) // Query runs
+getUser(params) // Cache hit (same reference)
+```
+
+If you must pass objects, pass the same reference:
+
+**Next.js-Specific Note:**
+
+In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
+
+- Database queries (Prisma, Drizzle, etc.)
+
+- Heavy computations
+
+- Authentication checks
+
+- File system operations
+
+- Any non-fetch async work
+
+Use `React.cache()` to deduplicate these operations across your component tree.
+
+Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache)
+
+### 3.10 Use after() for Non-Blocking Operations
+
+**Impact: MEDIUM (faster response times)**
+
+Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
+
+**Incorrect: blocks response**
+
+```tsx
+import { logUserAction } from '@/app/utils'
+
+export async function POST(request: Request) {
+ // Perform mutation
+ await updateDatabase(request)
+
+ // Logging blocks the response
+ const userAgent = request.headers.get('user-agent') || 'unknown'
+ await logUserAction({ userAgent })
+
+ return new Response(JSON.stringify({ status: 'success' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' }
+ })
+}
+```
+
+**Correct: non-blocking**
+
+```tsx
+import { after } from 'next/server'
+import { headers, cookies } from 'next/headers'
+import { logUserAction } from '@/app/utils'
+
+export async function POST(request: Request) {
+ // Perform mutation
+ await updateDatabase(request)
+
+ // Log after response is sent
+ after(async () => {
+ const userAgent = (await headers()).get('user-agent') || 'unknown'
+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
+
+ logUserAction({ sessionCookie, userAgent })
+ })
+
+ return new Response(JSON.stringify({ status: 'success' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' }
+ })
+}
+```
+
+The response is sent immediately while logging happens in the background.
+
+**Common use cases:**
+
+- Analytics tracking
+
+- Audit logging
+
+- Sending notifications
+
+- Cache invalidation
+
+- Cleanup tasks
+
+**Important notes:**
+
+- `after()` runs even if the response fails or redirects
+
+- Works in Server Actions, Route Handlers, and Server Components
+
+Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
+
+---
+
+## 4. Client-Side Data Fetching
+
+**Impact: MEDIUM-HIGH**
+
+Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
+
+### 4.1 Deduplicate Global Event Listeners
+
+**Impact: LOW (single listener for N components)**
+
+Use `useSWRSubscription()` to share global event listeners across component instances.
+
+**Incorrect: N instances = N listeners**
+
+```tsx
+function useKeyboardShortcut(key: string, callback: () => void) {
+ useEffect(() => {
+ const handler = (e: KeyboardEvent) => {
+ if (e.metaKey && e.key === key) {
+ callback()
+ }
+ }
+ window.addEventListener('keydown', handler)
+ return () => window.removeEventListener('keydown', handler)
+ }, [key, callback])
+}
+```
+
+When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
+
+**Correct: N instances = 1 listener**
+
+```tsx
+import useSWRSubscription from 'swr/subscription'
+
+// Module-level Map to track callbacks per key
+const keyCallbacks = new Map<string, Set<() => void>>()
+
+function useKeyboardShortcut(key: string, callback: () => void) {
+ // Register this callback in the Map
+ useEffect(() => {
+ if (!keyCallbacks.has(key)) {
+ keyCallbacks.set(key, new Set())
+ }
+ keyCallbacks.get(key)!.add(callback)
+
+ return () => {
+ const set = keyCallbacks.get(key)
+ if (set) {
+ set.delete(callback)
+ if (set.size === 0) {
+ keyCallbacks.delete(key)
+ }
+ }
+ }
+ }, [key, callback])
+
+ useSWRSubscription('global-keydown', () => {
+ const handler = (e: KeyboardEvent) => {
+ if (e.metaKey && keyCallbacks.has(e.key)) {
+ keyCallbacks.get(e.key)!.forEach(cb => cb())
+ }
+ }
+ window.addEventListener('keydown', handler)
+ return () => window.removeEventListener('keydown', handler)
+ })
+}
+
+function Profile() {
+ // Multiple shortcuts will share the same listener
+ useKeyboardShortcut('p', () => { /* ... */ })
+ useKeyboardShortcut('k', () => { /* ... */ })
+ // ...
+}
+```
+
+### 4.2 Use Passive Event Listeners for Scrolling Performance
+
+**Impact: MEDIUM (eliminates scroll delay caused by event listeners)**
+
+Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
+
+**Incorrect:**
+
+```typescript
+useEffect(() => {
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
+
+ document.addEventListener('touchstart', handleTouch)
+ document.addEventListener('wheel', handleWheel)
+
+ return () => {
+ document.removeEventListener('touchstart', handleTouch)
+ document.removeEventListener('wheel', handleWheel)
+ }
+}, [])
+```
+
+**Correct:**
+
+```typescript
+useEffect(() => {
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
+
+ document.addEventListener('touchstart', handleTouch, { passive: true })
+ document.addEventListener('wheel', handleWheel, { passive: true })
+
+ return () => {
+ document.removeEventListener('touchstart', handleTouch)
+ document.removeEventListener('wheel', handleWheel)
+ }
+}, [])
+```
+
+**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
+
+**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
+
+### 4.3 Use SWR for Automatic Deduplication
+
+**Impact: MEDIUM-HIGH (automatic deduplication)**
+
+SWR enables request deduplication, caching, and revalidation across component instances.
+
+**Incorrect: no deduplication, each instance fetches**
+
+```tsx
+function UserList() {
+ const [users, setUsers] = useState([])
+ useEffect(() => {
+ fetch('/api/users')
+ .then(r => r.json())
+ .then(setUsers)
+ }, [])
+}
+```
+
+**Correct: multiple instances share one request**
+
+```tsx
+import useSWR from 'swr'
+
+function UserList() {
+ const { data: users } = useSWR('/api/users', fetcher)
+}
+```
+
+**For immutable data:**
+
+```tsx
+import { useImmutableSWR } from '@/lib/swr'
+
+function StaticContent() {
+ const { data } = useImmutableSWR('/api/config', fetcher)
+}
+```
+
+**For mutations:**
+
+```tsx
+import { useSWRMutation } from 'swr/mutation'
+
+function UpdateButton() {
+ const { trigger } = useSWRMutation('/api/user', updateUser)
+ return <button onClick={() => trigger()}>Update</button>
+}
+```
+
+Reference: [https://swr.vercel.app](https://swr.vercel.app)
+
+### 4.4 Version and Minimize localStorage Data
+
+**Impact: MEDIUM (prevents schema conflicts, reduces storage size)**
+
+Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
+
+**Incorrect:**
+
+```typescript
+// No version, stores everything, no error handling
+localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
+const data = localStorage.getItem('userConfig')
+```
+
+**Correct:**
+
+```typescript
+const VERSION = 'v2'
+
+function saveConfig(config: { theme: string; language: string }) {
+ try {
+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
+ } catch {
+ // Throws in incognito/private browsing, quota exceeded, or disabled
+ }
+}
+
+function loadConfig() {
+ try {
+ const data = localStorage.getItem(`userConfig:${VERSION}`)
+ return data ? JSON.parse(data) : null
+ } catch {
+ return null
+ }
+}
+
+// Migration from v1 to v2
+function migrate() {
+ try {
+ const v1 = localStorage.getItem('userConfig:v1')
+ if (v1) {
+ const old = JSON.parse(v1)
+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
+ localStorage.removeItem('userConfig:v1')
+ }
+ } catch {}
+}
+```
+
+**Store minimal fields from server responses:**
+
+```typescript
+// User object has 20+ fields, only store what UI needs
+function cachePrefs(user: FullUser) {
+ try {
+ localStorage.setItem('prefs:v1', JSON.stringify({
+ theme: user.preferences.theme,
+ notifications: user.preferences.notifications
+ }))
+ } catch {}
+}
+```
+
+**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
+
+**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
+
+---
+
+## 5. Re-render Optimization
+
+**Impact: MEDIUM**
+
+Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
+
+### 5.1 Calculate Derived State During Rendering
+
+**Impact: MEDIUM (avoids redundant renders and state drift)**
+
+If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
+
+**Incorrect: redundant state and effect**
+
+```tsx
+function Form() {
+ const [firstName, setFirstName] = useState('First')
+ const [lastName, setLastName] = useState('Last')
+ const [fullName, setFullName] = useState('')
+
+ useEffect(() => {
+ setFullName(firstName + ' ' + lastName)
+ }, [firstName, lastName])
+
+ return <p>{fullName}</p>
+}
+```
+
+**Correct: derive during render**
+
+```tsx
+function Form() {
+ const [firstName, setFirstName] = useState('First')
+ const [lastName, setLastName] = useState('Last')
+ const fullName = firstName + ' ' + lastName
+
+ return <p>{fullName}</p>
+}
+```
+
+Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect)
+
+### 5.2 Defer State Reads to Usage Point
+
+**Impact: MEDIUM (avoids unnecessary subscriptions)**
+
+Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
+
+**Incorrect: subscribes to all searchParams changes**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const searchParams = useSearchParams()
+
+ const handleShare = () => {
+ const ref = searchParams.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return <button onClick={handleShare}>Share</button>
+}
+```
+
+**Correct: reads on demand, no subscription**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const handleShare = () => {
+ const params = new URLSearchParams(window.location.search)
+ const ref = params.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return <button onClick={handleShare}>Share</button>
+}
+```
+
+### 5.3 Do not wrap a simple expression with a primitive result type in useMemo
+
+**Impact: LOW-MEDIUM (wasted computation on every render)**
+
+When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
+
+Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
+
+**Incorrect:**
+
+```tsx
+function Header({ user, notifications }: Props) {
+ const isLoading = useMemo(() => {
+ return user.isLoading || notifications.isLoading
+ }, [user.isLoading, notifications.isLoading])
+
+ if (isLoading) return <Skeleton />
+ // return some markup
+}
+```
+
+**Correct:**
+
+```tsx
+function Header({ user, notifications }: Props) {
+ const isLoading = user.isLoading || notifications.isLoading
+
+ if (isLoading) return <Skeleton />
+ // return some markup
+}
+```
+
+### 5.4 Don't Define Components Inside Components
+
+**Impact: HIGH (prevents remount on every render)**
+
+Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
+
+A common reason developers do this is to access parent variables without passing props. Always pass props instead.
+
+**Incorrect: remounts on every render**
+
+```tsx
+function UserProfile({ user, theme }) {
+ // Defined inside to access `theme` - BAD
+ const Avatar = () => (
+ <img
+ src={user.avatarUrl}
+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
+ />
+ )
+
+ // Defined inside to access `user` - BAD
+ const Stats = () => (
+ <div>
+ <span>{user.followers} followers</span>
+ <span>{user.posts} posts</span>
+ </div>
+ )
+
+ return (
+ <div>
+ <Avatar />
+ <Stats />
+ </div>
+ )
+}
+```
+
+Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
+
+**Correct: pass props instead**
+
+```tsx
+function Avatar({ src, theme }: { src: string; theme: string }) {
+ return (
+ <img
+ src={src}
+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
+ />
+ )
+}
+
+function Stats({ followers, posts }: { followers: number; posts: number }) {
+ return (
+ <div>
+ <span>{followers} followers</span>
+ <span>{posts} posts</span>
+ </div>
+ )
+}
+
+function UserProfile({ user, theme }) {
+ return (
+ <div>
+ <Avatar src={user.avatarUrl} theme={theme} />
+ <Stats followers={user.followers} posts={user.posts} />
+ </div>
+ )
+}
+```
+
+**Symptoms of this bug:**
+
+- Input fields lose focus on every keystroke
+
+- Animations restart unexpectedly
+
+- `useEffect` cleanup/setup runs on every parent render
+
+- Scroll position resets inside the component
+
+### 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant
+
+**Impact: MEDIUM (restores memoization by using a constant for default value)**
+
+When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
+
+To address this issue, extract the default value into a constant.
+
+**Incorrect: `onClick` has different values on every rerender**
+
+```tsx
+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
+ // ...
+})
+
+// Used without optional onClick
+<UserAvatar />
+```
+
+**Correct: stable default value**
+
+```tsx
+const NOOP = () => {};
+
+const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
+ // ...
+})
+
+// Used without optional onClick
+<UserAvatar />
+```
+
+### 5.6 Extract to Memoized Components
+
+**Impact: MEDIUM (enables early returns)**
+
+Extract expensive work into memoized components to enable early returns before computation.
+
+**Incorrect: computes avatar even when loading**
+
+```tsx
+function Profile({ user, loading }: Props) {
+ const avatar = useMemo(() => {
+ const id = computeAvatarId(user)
+ return <Avatar id={id} />
+ }, [user])
+
+ if (loading) return <Skeleton />
+ return <div>{avatar}</div>
+}
+```
+
+**Correct: skips computation when loading**
+
+```tsx
+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
+ const id = useMemo(() => computeAvatarId(user), [user])
+ return <Avatar id={id} />
+})
+
+function Profile({ user, loading }: Props) {
+ if (loading) return <Skeleton />
+ return (
+ <div>
+ <UserAvatar user={user} />
+ </div>
+ )
+}
+```
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
+
+### 5.7 Narrow Effect Dependencies
+
+**Impact: LOW (minimizes effect re-runs)**
+
+Specify primitive dependencies instead of objects to minimize effect re-runs.
+
+**Incorrect: re-runs on any user field change**
+
+```tsx
+useEffect(() => {
+ console.log(user.id)
+}, [user])
+```
+
+**Correct: re-runs only when id changes**
+
+```tsx
+useEffect(() => {
+ console.log(user.id)
+}, [user.id])
+```
+
+**For derived state, compute outside effect:**
+
+```tsx
+// Incorrect: runs on width=767, 766, 765...
+useEffect(() => {
+ if (width < 768) {
+ enableMobileMode()
+ }
+}, [width])
+
+// Correct: runs only on boolean transition
+const isMobile = width < 768
+useEffect(() => {
+ if (isMobile) {
+ enableMobileMode()
+ }
+}, [isMobile])
+```
+
+### 5.8 Put Interaction Logic in Event Handlers
+
+**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)**
+
+If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
+
+**Incorrect: event modeled as state + effect**
+
+```tsx
+function Form() {
+ const [submitted, setSubmitted] = useState(false)
+ const theme = useContext(ThemeContext)
+
+ useEffect(() => {
+ if (submitted) {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+ }, [submitted, theme])
+
+ return <button onClick={() => setSubmitted(true)}>Submit</button>
+}
+```
+
+**Correct: do it in the handler**
+
+```tsx
+function Form() {
+ const theme = useContext(ThemeContext)
+
+ function handleSubmit() {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+
+ return <button onClick={handleSubmit}>Submit</button>
+}
+```
+
+Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
+
+### 5.9 Split Combined Hook Computations
+
+**Impact: MEDIUM (avoids recomputing independent steps)**
+
+When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
+
+**Incorrect: changing `sortOrder` recomputes filtering**
+
+```tsx
+const sortedProducts = useMemo(() => {
+ const filtered = products.filter((p) => p.category === category)
+ const sorted = filtered.toSorted((a, b) =>
+ sortOrder === "asc" ? a.price - b.price : b.price - a.price
+ )
+ return sorted
+}, [products, category, sortOrder])
+```
+
+**Correct: filtering only recomputes when products or category change**
+
+```tsx
+const filteredProducts = useMemo(
+ () => products.filter((p) => p.category === category),
+ [products, category]
+)
+
+const sortedProducts = useMemo(
+ () =>
+ filteredProducts.toSorted((a, b) =>
+ sortOrder === "asc" ? a.price - b.price : b.price - a.price
+ ),
+ [filteredProducts, sortOrder]
+)
+```
+
+This pattern also applies to `useEffect` when combining unrelated side effects:
+
+**Incorrect: both effects run when either dependency changes**
+
+```tsx
+useEffect(() => {
+ analytics.trackPageView(pathname)
+ document.title = `${pageTitle} | My App`
+}, [pathname, pageTitle])
+```
+
+**Correct: effects run independently**
+
+```tsx
+useEffect(() => {
+ analytics.trackPageView(pathname)
+}, [pathname])
+
+useEffect(() => {
+ document.title = `${pageTitle} | My App`
+}, [pageTitle])
+```
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
+
+### 5.10 Subscribe to Derived State
+
+**Impact: MEDIUM (reduces re-render frequency)**
+
+Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
+
+**Incorrect: re-renders on every pixel change**
+
+```tsx
+function Sidebar() {
+ const width = useWindowWidth() // updates continuously
+ const isMobile = width < 768
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
+}
+```
+
+**Correct: re-renders only when boolean changes**
+
+```tsx
+function Sidebar() {
+ const isMobile = useMediaQuery('(max-width: 767px)')
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
+}
+```
+
+### 5.11 Use Functional setState Updates
+
+**Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)**
+
+When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
+
+**Incorrect: requires state as dependency**
+
+```tsx
+function TodoList() {
+ const [items, setItems] = useState(initialItems)
+
+ // Callback must depend on items, recreated on every items change
+ const addItems = useCallback((newItems: Item[]) => {
+ setItems([...items, ...newItems])
+ }, [items]) // ❌ items dependency causes recreations
+
+ // Risk of stale closure if dependency is forgotten
+ const removeItem = useCallback((id: string) => {
+ setItems(items.filter(item => item.id !== id))
+ }, []) // ❌ Missing items dependency - will use stale items!
+
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
+}
+```
+
+The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
+
+**Correct: stable callbacks, no stale closures**
+
+```tsx
+function TodoList() {
+ const [items, setItems] = useState(initialItems)
+
+ // Stable callback, never recreated
+ const addItems = useCallback((newItems: Item[]) => {
+ setItems(curr => [...curr, ...newItems])
+ }, []) // ✅ No dependencies needed
+
+ // Always uses latest state, no stale closure risk
+ const removeItem = useCallback((id: string) => {
+ setItems(curr => curr.filter(item => item.id !== id))
+ }, []) // ✅ Safe and stable
+
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
+}
+```
+
+**Benefits:**
+
+1. **Stable callback references** - Callbacks don't need to be recreated when state changes
+
+2. **No stale closures** - Always operates on the latest state value
+
+3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
+
+4. **Prevents bugs** - Eliminates the most common source of React closure bugs
+
+**When to use functional updates:**
+
+- Any setState that depends on the current state value
+
+- Inside useCallback/useMemo when state is needed
+
+- Event handlers that reference state
+
+- Async operations that update state
+
+**When direct updates are fine:**
+
+- Setting state to a static value: `setCount(0)`
+
+- Setting state from props/arguments only: `setName(newName)`
+
+- State doesn't depend on previous value
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
+
+### 5.12 Use Lazy State Initialization
+
+**Impact: MEDIUM (wasted computation on every render)**
+
+Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
+
+**Incorrect: runs on every render**
+
+```tsx
+function FilteredList({ items }: { items: Item[] }) {
+ // buildSearchIndex() runs on EVERY render, even after initialization
+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
+ const [query, setQuery] = useState('')
+
+ // When query changes, buildSearchIndex runs again unnecessarily
+ return <SearchResults index={searchIndex} query={query} />
+}
+
+function UserProfile() {
+ // JSON.parse runs on every render
+ const [settings, setSettings] = useState(
+ JSON.parse(localStorage.getItem('settings') || '{}')
+ )
+
+ return <SettingsForm settings={settings} onChange={setSettings} />
+}
+```
+
+**Correct: runs only once**
+
+```tsx
+function FilteredList({ items }: { items: Item[] }) {
+ // buildSearchIndex() runs ONLY on initial render
+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
+ const [query, setQuery] = useState('')
+
+ return <SearchResults index={searchIndex} query={query} />
+}
+
+function UserProfile() {
+ // JSON.parse runs only on initial render
+ const [settings, setSettings] = useState(() => {
+ const stored = localStorage.getItem('settings')
+ return stored ? JSON.parse(stored) : {}
+ })
+
+ return <SettingsForm settings={settings} onChange={setSettings} />
+}
+```
+
+Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
+
+For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
+
+### 5.13 Use Transitions for Non-Urgent Updates
+
+**Impact: MEDIUM (maintains UI responsiveness)**
+
+Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
+
+**Incorrect: blocks UI on every scroll**
+
+```tsx
+function ScrollTracker() {
+ const [scrollY, setScrollY] = useState(0)
+ useEffect(() => {
+ const handler = () => setScrollY(window.scrollY)
+ window.addEventListener('scroll', handler, { passive: true })
+ return () => window.removeEventListener('scroll', handler)
+ }, [])
+}
+```
+
+**Correct: non-blocking updates**
+
+```tsx
+import { startTransition } from 'react'
+
+function ScrollTracker() {
+ const [scrollY, setScrollY] = useState(0)
+ useEffect(() => {
+ const handler = () => {
+ startTransition(() => setScrollY(window.scrollY))
+ }
+ window.addEventListener('scroll', handler, { passive: true })
+ return () => window.removeEventListener('scroll', handler)
+ }, [])
+}
+```
+
+### 5.14 Use useDeferredValue for Expensive Derived Renders
+
+**Impact: MEDIUM (keeps input responsive during heavy computation)**
+
+When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
+
+**Incorrect: input feels laggy while filtering**
+
+```tsx
+function Search({ items }: { items: Item[] }) {
+ const [query, setQuery] = useState('')
+ const filtered = items.filter(item => fuzzyMatch(item, query))
+
+ return (
+ <>
+ <input value={query} onChange={e => setQuery(e.target.value)} />
+ <ResultsList results={filtered} />
+ </>
+ )
+}
+```
+
+**Correct: input stays snappy, results render when ready**
+
+```tsx
+function Search({ items }: { items: Item[] }) {
+ const [query, setQuery] = useState('')
+ const deferredQuery = useDeferredValue(query)
+ const filtered = useMemo(
+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),
+ [items, deferredQuery]
+ )
+ const isStale = query !== deferredQuery
+
+ return (
+ <>
+ <input value={query} onChange={e => setQuery(e.target.value)} />
+ <div style={{ opacity: isStale ? 0.7 : 1 }}>
+ <ResultsList results={filtered} />
+ </div>
+ </>
+ )
+}
+```
+
+**When to use:**
+
+- Filtering/searching large lists
+
+- Expensive visualizations (charts, graphs) reacting to input
+
+- Any derived state that causes noticeable render delays
+
+**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
+
+Reference: [https://react.dev/reference/react/useDeferredValue](https://react.dev/reference/react/useDeferredValue)
+
+### 5.15 Use useRef for Transient Values
+
+**Impact: MEDIUM (avoids unnecessary re-renders on frequent updates)**
+
+When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
+
+**Incorrect: renders every update**
+
+```tsx
+function Tracker() {
+ const [lastX, setLastX] = useState(0)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => setLastX(e.clientX)
+ window.addEventListener('mousemove', onMove)
+ return () => window.removeEventListener('mousemove', onMove)
+ }, [])
+
+ return (
+ <div
+ style={{
+ position: 'fixed',
+ top: 0,
+ left: lastX,
+ width: 8,
+ height: 8,
+ background: 'black',
+ }}
+ />
+ )
+}
+```
+
+**Correct: no re-render for tracking**
+
+```tsx
+function Tracker() {
+ const lastXRef = useRef(0)
+ const dotRef = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => {
+ lastXRef.current = e.clientX
+ const node = dotRef.current
+ if (node) {
+ node.style.transform = `translateX(${e.clientX}px)`
+ }
+ }
+ window.addEventListener('mousemove', onMove)
+ return () => window.removeEventListener('mousemove', onMove)
+ }, [])
+
+ return (
+ <div
+ ref={dotRef}
+ style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ width: 8,
+ height: 8,
+ background: 'black',
+ transform: 'translateX(0px)',
+ }}
+ />
+ )
+}
+```
+
+---
+
+## 6. Rendering Performance
+
+**Impact: MEDIUM**
+
+Optimizing the rendering process reduces the work the browser needs to do.
+
+### 6.1 Animate SVG Wrapper Instead of SVG Element
+
+**Impact: LOW (enables hardware acceleration)**
+
+Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
+
+**Incorrect: animating SVG directly - no hardware acceleration**
+
+```tsx
+function LoadingSpinner() {
+ return (
+ <svg
+ className="animate-spin"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ >
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
+ </svg>
+ )
+}
+```
+
+**Correct: animating wrapper div - hardware accelerated**
+
+```tsx
+function LoadingSpinner() {
+ return (
+ <div className="animate-spin">
+ <svg
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ >
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
+ </svg>
+ </div>
+ )
+}
+```
+
+This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
+
+### 6.2 CSS content-visibility for Long Lists
+
+**Impact: HIGH (faster initial render)**
+
+Apply `content-visibility: auto` to defer off-screen rendering.
+
+**CSS:**
+
+```css
+.message-item {
+ content-visibility: auto;
+ contain-intrinsic-size: 0 80px;
+}
+```
+
+**Example:**
+
+```tsx
+function MessageList({ messages }: { messages: Message[] }) {
+ return (
+ <div className="overflow-y-auto h-screen">
+ {messages.map(msg => (
+ <div key={msg.id} className="message-item">
+ <Avatar user={msg.author} />
+ <div>{msg.content}</div>
+ </div>
+ ))}
+ </div>
+ )
+}
+```
+
+For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
+
+### 6.3 Hoist Static JSX Elements
+
+**Impact: LOW (avoids re-creation)**
+
+Extract static JSX outside components to avoid re-creation.
+
+**Incorrect: recreates element every render**
+
+```tsx
+function LoadingSkeleton() {
+ return <div className="animate-pulse h-20 bg-gray-200" />
+}
+
+function Container() {
+ return (
+ <div>
+ {loading && <LoadingSkeleton />}
+ </div>
+ )
+}
+```
+
+**Correct: reuses same element**
+
+```tsx
+const loadingSkeleton = (
+ <div className="animate-pulse h-20 bg-gray-200" />
+)
+
+function Container() {
+ return (
+ <div>
+ {loading && loadingSkeleton}
+ </div>
+ )
+}
+```
+
+This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
+
+### 6.4 Optimize SVG Precision
+
+**Impact: LOW (reduces file size)**
+
+Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
+
+**Incorrect: excessive precision**
+
+```svg
+<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
+```
+
+**Correct: 1 decimal place**
+
+```svg
+<path d="M 10.3 20.8 L 30.9 40.2" />
+```
+
+**Automate with SVGO:**
+
+```bash
+npx svgo --precision=1 --multipass icon.svg
+```
+
+### 6.5 Prevent Hydration Mismatch Without Flickering
+
+**Impact: MEDIUM (avoids visual flicker and hydration errors)**
+
+When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
+
+**Incorrect: breaks SSR**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ // localStorage is not available on server - throws error
+ const theme = localStorage.getItem('theme') || 'light'
+
+ return (
+ <div className={theme}>
+ {children}
+ </div>
+ )
+}
+```
+
+Server-side rendering will fail because `localStorage` is undefined.
+
+**Incorrect: visual flickering**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ const [theme, setTheme] = useState('light')
+
+ useEffect(() => {
+ // Runs after hydration - causes visible flash
+ const stored = localStorage.getItem('theme')
+ if (stored) {
+ setTheme(stored)
+ }
+ }, [])
+
+ return (
+ <div className={theme}>
+ {children}
+ </div>
+ )
+}
+```
+
+Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
+
+**Correct: no flicker, no hydration mismatch**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ return (
+ <>
+ <div id="theme-wrapper">
+ {children}
+ </div>
+ <script
+ dangerouslySetInnerHTML={{
+ __html: `
+ (function() {
+ try {
+ var theme = localStorage.getItem('theme') || 'light';
+ var el = document.getElementById('theme-wrapper');
+ if (el) el.className = theme;
+ } catch (e) {}
+ })();
+ `,
+ }}
+ />
+ </>
+ )
+}
+```
+
+The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
+
+This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
+
+### 6.6 Suppress Expected Hydration Mismatches
+
+**Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)**
+
+In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
+
+**Incorrect: known mismatch warnings**
+
+```tsx
+function Timestamp() {
+ return <span>{new Date().toLocaleString()}</span>
+}
+```
+
+**Correct: suppress expected mismatch only**
+
+```tsx
+function Timestamp() {
+ return (
+ <span suppressHydrationWarning>
+ {new Date().toLocaleString()}
+ </span>
+ )
+}
+```
+
+### 6.7 Use Activity Component for Show/Hide
+
+**Impact: MEDIUM (preserves state/DOM)**
+
+Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
+
+**Usage:**
+
+```tsx
+import { Activity } from 'react'
+
+function Dropdown({ isOpen }: Props) {
+ return (
+ <Activity mode={isOpen ? 'visible' : 'hidden'}>
+ <ExpensiveMenu />
+ </Activity>
+ )
+}
+```
+
+Avoids expensive re-renders and state loss.
+
+### 6.8 Use defer or async on Script Tags
+
+**Impact: HIGH (eliminates render-blocking)**
+
+Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
+
+- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
+
+- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
+
+Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
+
+**Incorrect: blocks rendering**
+
+```tsx
+export default function Document() {
+ return (
+ <html>
+ <head>
+ <script src="https://example.com/analytics.js" />
+ <script src="/scripts/utils.js" />
+ </head>
+ <body>{/* content */}</body>
+ </html>
+ )
+}
+```
+
+**Correct: non-blocking**
+
+```tsx
+import Script from 'next/script'
+
+export default function Page() {
+ return (
+ <>
+ <Script src="https://example.com/analytics.js" strategy="afterInteractive" />
+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />
+ </>
+ )
+}
+```
+
+**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
+
+Reference: [https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
+
+### 6.9 Use Explicit Conditional Rendering
+
+**Impact: LOW (prevents rendering 0 or NaN)**
+
+Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
+
+**Incorrect: renders "0" when count is 0**
+
+```tsx
+function Badge({ count }: { count: number }) {
+ return (
+ <div>
+ {count && <span className="badge">{count}</span>}
+ </div>
+ )
+}
+
+// When count = 0, renders: <div>0</div>
+// When count = 5, renders: <div><span class="badge">5</span></div>
+```
+
+**Correct: renders nothing when count is 0**
+
+```tsx
+function Badge({ count }: { count: number }) {
+ return (
+ <div>
+ {count > 0 ? <span className="badge">{count}</span> : null}
+ </div>
+ )
+}
+
+// When count = 0, renders: <div></div>
+// When count = 5, renders: <div><span class="badge">5</span></div>
+```
+
+### 6.10 Use React DOM Resource Hints
+
+**Impact: HIGH (reduces load time for critical resources)**
+
+React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
+
+- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
+
+- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
+
+- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
+
+- **`preloadModule(href)`**: Fetch an ES module you'll use soon
+
+- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
+
+- **`preinitModule(href)`**: Fetch and evaluate an ES module
+
+**Example: preconnect to third-party APIs**
+
+```tsx
+import { preconnect, prefetchDNS } from 'react-dom'
+
+export default function App() {
+ prefetchDNS('https://analytics.example.com')
+ preconnect('https://api.example.com')
+
+ return <main>{/* content */}</main>
+}
+```
+
+**Example: preload critical fonts and styles**
+
+```tsx
+import { preload, preinit } from 'react-dom'
+
+export default function RootLayout({ children }) {
+ // Preload font file
+ preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
+
+ // Fetch and apply critical stylesheet immediately
+ preinit('/styles/critical.css', { as: 'style' })
+
+ return (
+ <html>
+ <body>{children}</body>
+ </html>
+ )
+}
+```
+
+**Example: preload modules for code-split routes**
+
+```tsx
+import { preloadModule, preinitModule } from 'react-dom'
+
+function Navigation() {
+ const preloadDashboard = () => {
+ preloadModule('/dashboard.js', { as: 'script' })
+ }
+
+ return (
+ <nav>
+ <a href="/dashboard" onMouseEnter={preloadDashboard}>
+ Dashboard
+ </a>
+ </nav>
+ )
+}
+```
+
+**When to use each:**
+
+| API | Use case |
+
+|-----|----------|
+
+| `prefetchDNS` | Third-party domains you'll connect to later |
+
+| `preconnect` | APIs or CDNs you'll fetch from immediately |
+
+| `preload` | Critical resources needed for current page |
+
+| `preloadModule` | JS modules for likely next navigation |
+
+| `preinit` | Stylesheets/scripts that must execute early |
+
+| `preinitModule` | ES modules that must execute early |
+
+Reference: [https://react.dev/reference/react-dom#resource-preloading-apis](https://react.dev/reference/react-dom#resource-preloading-apis)
+
+### 6.11 Use useTransition Over Manual Loading States
+
+**Impact: LOW (reduces re-renders and improves code clarity)**
+
+Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
+
+**Incorrect: manual loading state**
+
+```tsx
+function SearchResults() {
+ const [query, setQuery] = useState('')
+ const [results, setResults] = useState([])
+ const [isLoading, setIsLoading] = useState(false)
+
+ const handleSearch = async (value: string) => {
+ setIsLoading(true)
+ setQuery(value)
+ const data = await fetchResults(value)
+ setResults(data)
+ setIsLoading(false)
+ }
+
+ return (
+ <>
+ <input onChange={(e) => handleSearch(e.target.value)} />
+ {isLoading && <Spinner />}
+ <ResultsList results={results} />
+ </>
+ )
+}
+```
+
+**Correct: useTransition with built-in pending state**
+
+```tsx
+import { useTransition, useState } from 'react'
+
+function SearchResults() {
+ const [query, setQuery] = useState('')
+ const [results, setResults] = useState([])
+ const [isPending, startTransition] = useTransition()
+
+ const handleSearch = (value: string) => {
+ setQuery(value) // Update input immediately
+
+ startTransition(async () => {
+ // Fetch and update results
+ const data = await fetchResults(value)
+ setResults(data)
+ })
+ }
+
+ return (
+ <>
+ <input onChange={(e) => handleSearch(e.target.value)} />
+ {isPending && <Spinner />}
+ <ResultsList results={results} />
+ </>
+ )
+}
+```
+
+**Benefits:**
+
+- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
+
+- **Error resilience**: Pending state correctly resets even if the transition throws
+
+- **Better responsiveness**: Keeps the UI responsive during updates
+
+- **Interrupt handling**: New transitions automatically cancel pending ones
+
+Reference: [https://react.dev/reference/react/useTransition](https://react.dev/reference/react/useTransition)
+
+---
+
+## 7. JavaScript Performance
+
+**Impact: LOW-MEDIUM**
+
+Micro-optimizations for hot paths can add up to meaningful improvements.
+
+### 7.1 Avoid Layout Thrashing
+
+**Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)**
+
+Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
+
+**This is OK: browser batches style changes**
+
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ // Each line invalidates style, but browser batches the recalculation
+ element.style.width = '100px'
+ element.style.height = '200px'
+ element.style.backgroundColor = 'blue'
+ element.style.border = '1px solid black'
+}
+```
+
+**Incorrect: interleaved reads and writes force reflows**
+
+```typescript
+function layoutThrashing(element: HTMLElement) {
+ element.style.width = '100px'
+ const width = element.offsetWidth // Forces reflow
+ element.style.height = '200px'
+ const height = element.offsetHeight // Forces another reflow
+}
+```
+
+**Correct: batch writes, then read once**
+
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ // Batch all writes together
+ element.style.width = '100px'
+ element.style.height = '200px'
+ element.style.backgroundColor = 'blue'
+ element.style.border = '1px solid black'
+
+ // Read after all writes are done (single reflow)
+ const { width, height } = element.getBoundingClientRect()
+}
+```
+
+**Correct: batch reads, then writes**
+
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ element.classList.add('highlighted-box')
+
+ const { width, height } = element.getBoundingClientRect()
+}
+```
+
+**Better: use CSS classes**
+
+**React example:**
+
+```tsx
+// Incorrect: interleaving style changes with layout queries
+function Box({ isHighlighted }: { isHighlighted: boolean }) {
+ const ref = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (ref.current && isHighlighted) {
+ ref.current.style.width = '100px'
+ const width = ref.current.offsetWidth // Forces layout
+ ref.current.style.height = '200px'
+ }
+ }, [isHighlighted])
+
+ return <div ref={ref}>Content</div>
+}
+
+// Correct: toggle class
+function Box({ isHighlighted }: { isHighlighted: boolean }) {
+ return (
+ <div className={isHighlighted ? 'highlighted-box' : ''}>
+ Content
+ </div>
+ )
+}
+```
+
+Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
+
+See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
+
+### 7.2 Build Index Maps for Repeated Lookups
+
+**Impact: LOW-MEDIUM (1M ops to 2K ops)**
+
+Multiple `.find()` calls by the same key should use a Map.
+
+**Incorrect (O(n) per lookup):**
+
+```typescript
+function processOrders(orders: Order[], users: User[]) {
+ return orders.map(order => ({
+ ...order,
+ user: users.find(u => u.id === order.userId)
+ }))
+}
+```
+
+**Correct (O(1) per lookup):**
+
+```typescript
+function processOrders(orders: Order[], users: User[]) {
+ const userById = new Map(users.map(u => [u.id, u]))
+
+ return orders.map(order => ({
+ ...order,
+ user: userById.get(order.userId)
+ }))
+}
+```
+
+Build map once (O(n)), then all lookups are O(1).
+
+For 1000 orders × 1000 users: 1M ops → 2K ops.
+
+### 7.3 Cache Property Access in Loops
+
+**Impact: LOW-MEDIUM (reduces lookups)**
+
+Cache object property lookups in hot paths.
+
+**Incorrect: 3 lookups × N iterations**
+
+```typescript
+for (let i = 0; i < arr.length; i++) {
+ process(obj.config.settings.value)
+}
+```
+
+**Correct: 1 lookup total**
+
+```typescript
+const value = obj.config.settings.value
+const len = arr.length
+for (let i = 0; i < len; i++) {
+ process(value)
+}
+```
+
+### 7.4 Cache Repeated Function Calls
+
+**Impact: MEDIUM (avoid redundant computation)**
+
+Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
+
+**Incorrect: redundant computation**
+
+```typescript
+function ProjectList({ projects }: { projects: Project[] }) {
+ return (
+ <div>
+ {projects.map(project => {
+ // slugify() called 100+ times for same project names
+ const slug = slugify(project.name)
+
+ return <ProjectCard key={project.id} slug={slug} />
+ })}
+ </div>
+ )
+}
+```
+
+**Correct: cached results**
+
+```typescript
+// Module-level cache
+const slugifyCache = new Map<string, string>()
+
+function cachedSlugify(text: string): string {
+ if (slugifyCache.has(text)) {
+ return slugifyCache.get(text)!
+ }
+ const result = slugify(text)
+ slugifyCache.set(text, result)
+ return result
+}
+
+function ProjectList({ projects }: { projects: Project[] }) {
+ return (
+ <div>
+ {projects.map(project => {
+ // Computed only once per unique project name
+ const slug = cachedSlugify(project.name)
+
+ return <ProjectCard key={project.id} slug={slug} />
+ })}
+ </div>
+ )
+}
+```
+
+**Simpler pattern for single-value functions:**
+
+```typescript
+let isLoggedInCache: boolean | null = null
+
+function isLoggedIn(): boolean {
+ if (isLoggedInCache !== null) {
+ return isLoggedInCache
+ }
+
+ isLoggedInCache = document.cookie.includes('auth=')
+ return isLoggedInCache
+}
+
+// Clear cache when auth changes
+function onAuthChange() {
+ isLoggedInCache = null
+}
+```
+
+Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
+
+Reference: [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
+
+### 7.5 Cache Storage API Calls
+
+**Impact: LOW-MEDIUM (reduces expensive I/O)**
+
+`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
+
+**Incorrect: reads storage on every call**
+
+```typescript
+function getTheme() {
+ return localStorage.getItem('theme') ?? 'light'
+}
+// Called 10 times = 10 storage reads
+```
+
+**Correct: Map cache**
+
+```typescript
+const storageCache = new Map<string, string | null>()
+
+function getLocalStorage(key: string) {
+ if (!storageCache.has(key)) {
+ storageCache.set(key, localStorage.getItem(key))
+ }
+ return storageCache.get(key)
+}
+
+function setLocalStorage(key: string, value: string) {
+ localStorage.setItem(key, value)
+ storageCache.set(key, value) // keep cache in sync
+}
+```
+
+Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
+
+**Cookie caching:**
+
+```typescript
+let cookieCache: Record<string, string> | null = null
+
+function getCookie(name: string) {
+ if (!cookieCache) {
+ cookieCache = Object.fromEntries(
+ document.cookie.split('; ').map(c => c.split('='))
+ )
+ }
+ return cookieCache[name]
+}
+```
+
+**Important: invalidate on external changes**
+
+```typescript
+window.addEventListener('storage', (e) => {
+ if (e.key) storageCache.delete(e.key)
+})
+
+document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'visible') {
+ storageCache.clear()
+ }
+})
+```
+
+If storage can change externally (another tab, server-set cookies), invalidate cache:
+
+### 7.6 Combine Multiple Array Iterations
+
+**Impact: LOW-MEDIUM (reduces iterations)**
+
+Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
+
+**Incorrect: 3 iterations**
+
+```typescript
+const admins = users.filter(u => u.isAdmin)
+const testers = users.filter(u => u.isTester)
+const inactive = users.filter(u => !u.isActive)
+```
+
+**Correct: 1 iteration**
+
+```typescript
+const admins: User[] = []
+const testers: User[] = []
+const inactive: User[] = []
+
+for (const user of users) {
+ if (user.isAdmin) admins.push(user)
+ if (user.isTester) testers.push(user)
+ if (!user.isActive) inactive.push(user)
+}
+```
+
+### 7.7 Defer Non-Critical Work with requestIdleCallback
+
+**Impact: MEDIUM (keeps UI responsive during background tasks)**
+
+Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
+
+**Incorrect: blocks main thread during user interaction**
+
+```typescript
+function handleSearch(query: string) {
+ const results = searchItems(query)
+ setResults(results)
+
+ // These block the main thread immediately
+ analytics.track('search', { query })
+ saveToRecentSearches(query)
+ prefetchTopResults(results.slice(0, 3))
+}
+```
+
+**Correct: defers non-critical work to idle time**
+
+```typescript
+function handleSearch(query: string) {
+ const results = searchItems(query)
+ setResults(results)
+
+ // Defer non-critical work to idle periods
+ requestIdleCallback(() => {
+ analytics.track('search', { query })
+ })
+
+ requestIdleCallback(() => {
+ saveToRecentSearches(query)
+ })
+
+ requestIdleCallback(() => {
+ prefetchTopResults(results.slice(0, 3))
+ })
+}
+```
+
+**With timeout for required work:**
+
+```typescript
+// Ensure analytics fires within 2 seconds even if browser stays busy
+requestIdleCallback(
+ () => analytics.track('page_view', { path: location.pathname }),
+ { timeout: 2000 }
+)
+```
+
+**Chunking large tasks:**
+
+```typescript
+function processLargeDataset(items: Item[]) {
+ let index = 0
+
+ function processChunk(deadline: IdleDeadline) {
+ // Process items while we have idle time (aim for <50ms chunks)
+ while (index < items.length && deadline.timeRemaining() > 0) {
+ processItem(items[index])
+ index++
+ }
+
+ // Schedule next chunk if more items remain
+ if (index < items.length) {
+ requestIdleCallback(processChunk)
+ }
+ }
+
+ requestIdleCallback(processChunk)
+}
+```
+
+**With fallback for unsupported browsers:**
+
+```typescript
+const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
+
+scheduleIdleWork(() => {
+ // Non-critical work
+})
+```
+
+**When to use:**
+
+- Analytics and telemetry
+
+- Saving state to localStorage/IndexedDB
+
+- Prefetching resources for likely next actions
+
+- Processing non-urgent data transformations
+
+- Lazy initialization of non-critical features
+
+**When NOT to use:**
+
+- User-initiated actions that need immediate feedback
+
+- Rendering updates the user is waiting for
+
+- Time-sensitive operations
+
+### 7.8 Early Length Check for Array Comparisons
+
+**Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)**
+
+When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
+
+In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
+
+**Incorrect: always runs expensive comparison**
+
+```typescript
+function hasChanges(current: string[], original: string[]) {
+ // Always sorts and joins, even when lengths differ
+ return current.sort().join() !== original.sort().join()
+}
+```
+
+Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
+
+**Correct (O(1) length check first):**
+
+```typescript
+function hasChanges(current: string[], original: string[]) {
+ // Early return if lengths differ
+ if (current.length !== original.length) {
+ return true
+ }
+ // Only sort when lengths match
+ const currentSorted = current.toSorted()
+ const originalSorted = original.toSorted()
+ for (let i = 0; i < currentSorted.length; i++) {
+ if (currentSorted[i] !== originalSorted[i]) {
+ return true
+ }
+ }
+ return false
+}
+```
+
+This new approach is more efficient because:
+
+- It avoids the overhead of sorting and joining the arrays when lengths differ
+
+- It avoids consuming memory for the joined strings (especially important for large arrays)
+
+- It avoids mutating the original arrays
+
+- It returns early when a difference is found
+
+### 7.9 Early Return from Functions
+
+**Impact: LOW-MEDIUM (avoids unnecessary computation)**
+
+Return early when result is determined to skip unnecessary processing.
+
+**Incorrect: processes all items even after finding answer**
+
+```typescript
+function validateUsers(users: User[]) {
+ let hasError = false
+ let errorMessage = ''
+
+ for (const user of users) {
+ if (!user.email) {
+ hasError = true
+ errorMessage = 'Email required'
+ }
+ if (!user.name) {
+ hasError = true
+ errorMessage = 'Name required'
+ }
+ // Continues checking all users even after error found
+ }
+
+ return hasError ? { valid: false, error: errorMessage } : { valid: true }
+}
+```
+
+**Correct: returns immediately on first error**
+
+```typescript
+function validateUsers(users: User[]) {
+ for (const user of users) {
+ if (!user.email) {
+ return { valid: false, error: 'Email required' }
+ }
+ if (!user.name) {
+ return { valid: false, error: 'Name required' }
+ }
+ }
+
+ return { valid: true }
+}
+```
+
+### 7.10 Hoist RegExp Creation
+
+**Impact: LOW-MEDIUM (avoids recreation)**
+
+Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
+
+**Incorrect: new RegExp every render**
+
+```tsx
+function Highlighter({ text, query }: Props) {
+ const regex = new RegExp(`(${query})`, 'gi')
+ const parts = text.split(regex)
+ return <>{parts.map((part, i) => ...)}</>
+}
+```
+
+**Correct: memoize or hoist**
+
+```tsx
+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
+
+function Highlighter({ text, query }: Props) {
+ const regex = useMemo(
+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
+ [query]
+ )
+ const parts = text.split(regex)
+ return <>{parts.map((part, i) => ...)}</>
+}
+```
+
+**Warning: global regex has mutable state**
+
+```typescript
+const regex = /foo/g
+regex.test('foo') // true, lastIndex = 3
+regex.test('foo') // false, lastIndex = 0
+```
+
+Global regex (`/g`) has mutable `lastIndex` state:
+
+### 7.11 Use flatMap to Map and Filter in One Pass
+
+**Impact: LOW-MEDIUM (eliminates intermediate array)**
+
+Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
+
+**Incorrect: 2 iterations, intermediate array**
+
+```typescript
+const userNames = users
+ .map(user => user.isActive ? user.name : null)
+ .filter(Boolean)
+```
+
+**Correct: 1 iteration, no intermediate array**
+
+```typescript
+const userNames = users.flatMap(user =>
+ user.isActive ? [user.name] : []
+)
+```
+
+**More examples:**
+
+```typescript
+// Extract valid emails from responses
+// Before
+const emails = responses
+ .map(r => r.success ? r.data.email : null)
+ .filter(Boolean)
+
+// After
+const emails = responses.flatMap(r =>
+ r.success ? [r.data.email] : []
+)
+
+// Parse and filter valid numbers
+// Before
+const numbers = strings
+ .map(s => parseInt(s, 10))
+ .filter(n => !isNaN(n))
+
+// After
+const numbers = strings.flatMap(s => {
+ const n = parseInt(s, 10)
+ return isNaN(n) ? [] : [n]
+})
+```
+
+**When to use:**
+
+- Transforming items while filtering some out
+
+- Conditional mapping where some inputs produce no output
+
+- Parsing/validating where invalid inputs should be skipped
+
+### 7.12 Use Loop for Min/Max Instead of Sort
+
+**Impact: LOW (O(n) instead of O(n log n))**
+
+Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
+
+**Incorrect (O(n log n) - sort to find latest):**
+
+```typescript
+interface Project {
+ id: string
+ name: string
+ updatedAt: number
+}
+
+function getLatestProject(projects: Project[]) {
+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
+ return sorted[0]
+}
+```
+
+Sorts the entire array just to find the maximum value.
+
+**Incorrect (O(n log n) - sort for oldest and newest):**
+
+```typescript
+function getOldestAndNewest(projects: Project[]) {
+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
+}
+```
+
+Still sorts unnecessarily when only min/max are needed.
+
+**Correct (O(n) - single loop):**
+
+```typescript
+function getLatestProject(projects: Project[]) {
+ if (projects.length === 0) return null
+
+ let latest = projects[0]
+
+ for (let i = 1; i < projects.length; i++) {
+ if (projects[i].updatedAt > latest.updatedAt) {
+ latest = projects[i]
+ }
+ }
+
+ return latest
+}
+
+function getOldestAndNewest(projects: Project[]) {
+ if (projects.length === 0) return { oldest: null, newest: null }
+
+ let oldest = projects[0]
+ let newest = projects[0]
+
+ for (let i = 1; i < projects.length; i++) {
+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
+ }
+
+ return { oldest, newest }
+}
+```
+
+Single pass through the array, no copying, no sorting.
+
+**Alternative: Math.min/Math.max for small arrays**
+
+```typescript
+const numbers = [5, 2, 8, 1, 9]
+const min = Math.min(...numbers)
+const max = Math.max(...numbers)
+```
+
+This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
+
+### 7.13 Use Set/Map for O(1) Lookups
+
+**Impact: LOW-MEDIUM (O(n) to O(1))**
+
+Convert arrays to Set/Map for repeated membership checks.
+
+**Incorrect (O(n) per check):**
+
+```typescript
+const allowedIds = ['a', 'b', 'c', ...]
+items.filter(item => allowedIds.includes(item.id))
+```
+
+**Correct (O(1) per check):**
+
+```typescript
+const allowedIds = new Set(['a', 'b', 'c', ...])
+items.filter(item => allowedIds.has(item.id))
+```
+
+### 7.14 Use toSorted() Instead of sort() for Immutability
+
+**Impact: MEDIUM-HIGH (prevents mutation bugs in React state)**
+
+`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
+
+**Incorrect: mutates original array**
+
+```typescript
+function UserList({ users }: { users: User[] }) {
+ // Mutates the users prop array!
+ const sorted = useMemo(
+ () => users.sort((a, b) => a.name.localeCompare(b.name)),
+ [users]
+ )
+ return <div>{sorted.map(renderUser)}</div>
+}
+```
+
+**Correct: creates new array**
+
+```typescript
+function UserList({ users }: { users: User[] }) {
+ // Creates new sorted array, original unchanged
+ const sorted = useMemo(
+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),
+ [users]
+ )
+ return <div>{sorted.map(renderUser)}</div>
+}
+```
+
+**Why this matters in React:**
+
+1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
+
+2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
+
+**Browser support: fallback for older browsers**
+
+```typescript
+// Fallback for older browsers
+const sorted = [...items].sort((a, b) => a.value - b.value)
+```
+
+`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
+
+**Other immutable array methods:**
+
+- `.toSorted()` - immutable sort
+
+- `.toReversed()` - immutable reverse
+
+- `.toSpliced()` - immutable splice
+
+- `.with()` - immutable element replacement
+
+---
+
+## 8. Advanced Patterns
+
+**Impact: LOW**
+
+Advanced patterns for specific cases that require careful implementation.
+
+### 8.1 Do Not Put Effect Events in Dependency Arrays
+
+**Impact: LOW (avoids unnecessary effect re-runs and lint errors)**
+
+Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
+
+**Incorrect: Effect Event added as a dependency**
+
+```tsx
+import { useEffect, useEffectEvent } from 'react'
+
+function ChatRoom({ roomId, onConnected }: {
+ roomId: string
+ onConnected: () => void
+}) {
+ const handleConnected = useEffectEvent(onConnected)
+
+ useEffect(() => {
+ const connection = createConnection(roomId)
+ connection.on('connected', handleConnected)
+ connection.connect()
+
+ return () => connection.disconnect()
+ }, [roomId, handleConnected])
+}
+```
+
+Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
+
+**Correct: depend on reactive values, not the Effect Event**
+
+```tsx
+import { useEffect, useEffectEvent } from 'react'
+
+function ChatRoom({ roomId, onConnected }: {
+ roomId: string
+ onConnected: () => void
+}) {
+ const handleConnected = useEffectEvent(onConnected)
+
+ useEffect(() => {
+ const connection = createConnection(roomId)
+ connection.on('connected', handleConnected)
+ connection.connect()
+
+ return () => connection.disconnect()
+ }, [roomId])
+}
+```
+
+Reference: [https://react.dev/reference/react/useEffectEvent#effect-event-in-deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
+
+### 8.2 Initialize App Once, Not Per Mount
+
+**Impact: LOW-MEDIUM (avoids duplicate init in development)**
+
+Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
+
+**Incorrect: runs twice in dev, re-runs on remount**
+
+```tsx
+function Comp() {
+ useEffect(() => {
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+**Correct: once per app load**
+
+```tsx
+let didInit = false
+
+function Comp() {
+ useEffect(() => {
+ if (didInit) return
+ didInit = true
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+Reference: [https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
+
+### 8.3 Store Event Handlers in Refs
+
+**Impact: LOW (stable subscriptions)**
+
+Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
+
+**Incorrect: re-subscribes on every render**
+
+```tsx
+function useWindowEvent(event: string, handler: (e) => void) {
+ useEffect(() => {
+ window.addEventListener(event, handler)
+ return () => window.removeEventListener(event, handler)
+ }, [event, handler])
+}
+```
+
+**Correct: stable subscription**
+
+```tsx
+import { useEffectEvent } from 'react'
+
+function useWindowEvent(event: string, handler: (e) => void) {
+ const onEvent = useEffectEvent(handler)
+
+ useEffect(() => {
+ window.addEventListener(event, onEvent)
+ return () => window.removeEventListener(event, onEvent)
+ }, [event])
+}
+```
+
+**Alternative: use `useEffectEvent` if you're on latest React:**
+
+`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
+
+### 8.4 useEffectEvent for Stable Callback Refs
+
+**Impact: LOW (prevents effect re-runs)**
+
+Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
+
+**Incorrect: effect re-runs on every callback change**
+
+```tsx
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearch(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query, onSearch])
+}
+```
+
+**Correct: using React's useEffectEvent**
+
+```tsx
+import { useEffectEvent } from 'react';
+
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+ const onSearchEvent = useEffectEvent(onSearch)
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearchEvent(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query])
+}
+```
+
+---
+
+## References
+
+1. [https://react.dev](https://react.dev)
+2. [https://nextjs.org](https://nextjs.org)
+3. [https://swr.vercel.app](https://swr.vercel.app)
+4. [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
+5. [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
+6. [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
+7. [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
diff --git a/.agents/skills/vercel-react-best-practices/README.md b/.agents/skills/vercel-react-best-practices/README.md
new file mode 100644
index 00000000..f283e1c0
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/README.md
@@ -0,0 +1,123 @@
+# React Best Practices
+
+A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
+
+## Structure
+
+- `rules/` - Individual rule files (one per rule)
+ - `_sections.md` - Section metadata (titles, impacts, descriptions)
+ - `_template.md` - Template for creating new rules
+ - `area-description.md` - Individual rule files
+- `src/` - Build scripts and utilities
+- `metadata.json` - Document metadata (version, organization, abstract)
+- __`AGENTS.md`__ - Compiled output (generated)
+- __`test-cases.json`__ - Test cases for LLM evaluation (generated)
+
+## Getting Started
+
+1. Install dependencies:
+ ```bash
+ pnpm install
+ ```
+
+2. Build AGENTS.md from rules:
+ ```bash
+ pnpm build
+ ```
+
+3. Validate rule files:
+ ```bash
+ pnpm validate
+ ```
+
+4. Extract test cases:
+ ```bash
+ pnpm extract-tests
+ ```
+
+## Creating a New Rule
+
+1. Copy `rules/_template.md` to `rules/area-description.md`
+2. Choose the appropriate area prefix:
+ - `async-` for Eliminating Waterfalls (Section 1)
+ - `bundle-` for Bundle Size Optimization (Section 2)
+ - `server-` for Server-Side Performance (Section 3)
+ - `client-` for Client-Side Data Fetching (Section 4)
+ - `rerender-` for Re-render Optimization (Section 5)
+ - `rendering-` for Rendering Performance (Section 6)
+ - `js-` for JavaScript Performance (Section 7)
+ - `advanced-` for Advanced Patterns (Section 8)
+3. Fill in the frontmatter and content
+4. Ensure you have clear examples with explanations
+5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
+
+## Rule File Structure
+
+Each rule file should follow this structure:
+
+```markdown
+---
+title: Rule Title Here
+impact: MEDIUM
+impactDescription: Optional description
+tags: tag1, tag2, tag3
+---
+
+## Rule Title Here
+
+Brief explanation of the rule and why it matters.
+
+**Incorrect (description of what's wrong):**
+
+```typescript
+// Bad code example
+```
+
+**Correct (description of what's right):**
+
+```typescript
+// Good code example
+```
+
+Optional explanatory text after examples.
+
+Reference: [Link](https://example.com)
+
+## File Naming Convention
+
+- Files starting with `_` are special (excluded from build)
+- Rule files: `area-description.md` (e.g., `async-parallel.md`)
+- Section is automatically inferred from filename prefix
+- Rules are sorted alphabetically by title within each section
+- IDs (e.g., 1.1, 1.2) are auto-generated during build
+
+## Impact Levels
+
+- `CRITICAL` - Highest priority, major performance gains
+- `HIGH` - Significant performance improvements
+- `MEDIUM-HIGH` - Moderate-high gains
+- `MEDIUM` - Moderate performance improvements
+- `LOW-MEDIUM` - Low-medium gains
+- `LOW` - Incremental improvements
+
+## Scripts
+
+- `pnpm build` - Compile rules into AGENTS.md
+- `pnpm validate` - Validate all rule files
+- `pnpm extract-tests` - Extract test cases for LLM evaluation
+- `pnpm dev` - Build and validate
+
+## Contributing
+
+When adding or modifying rules:
+
+1. Use the correct filename prefix for your section
+2. Follow the `_template.md` structure
+3. Include clear bad/good examples with explanations
+4. Add appropriate tags
+5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
+6. Rules are automatically sorted by title - no need to manage numbers!
+
+## Acknowledgments
+
+Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
diff --git a/.agents/skills/vercel-react-best-practices/SKILL.md b/.agents/skills/vercel-react-best-practices/SKILL.md
new file mode 100644
index 00000000..237988de
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/SKILL.md
@@ -0,0 +1,149 @@
+---
+name: vercel-react-best-practices
+description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
+license: MIT
+metadata:
+ author: vercel
+ version: "1.0.0"
+---
+
+# Vercel React Best Practices
+
+Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
+
+## When to Apply
+
+Reference these guidelines when:
+- Writing new React components or Next.js pages
+- Implementing data fetching (client or server-side)
+- Reviewing code for performance issues
+- Refactoring existing React/Next.js code
+- Optimizing bundle size or load times
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
+| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
+| 3 | Server-Side Performance | HIGH | `server-` |
+| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
+| 5 | Re-render Optimization | MEDIUM | `rerender-` |
+| 6 | Rendering Performance | MEDIUM | `rendering-` |
+| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
+| 8 | Advanced Patterns | LOW | `advanced-` |
+
+## Quick Reference
+
+### 1. Eliminating Waterfalls (CRITICAL)
+
+- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
+- `async-defer-await` - Move await into branches where actually used
+- `async-parallel` - Use Promise.all() for independent operations
+- `async-dependencies` - Use better-all for partial dependencies
+- `async-api-routes` - Start promises early, await late in API routes
+- `async-suspense-boundaries` - Use Suspense to stream content
+
+### 2. Bundle Size Optimization (CRITICAL)
+
+- `bundle-barrel-imports` - Import directly, avoid barrel files
+- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces
+- `bundle-dynamic-imports` - Use next/dynamic for heavy components
+- `bundle-defer-third-party` - Load analytics/logging after hydration
+- `bundle-conditional` - Load modules only when feature is activated
+- `bundle-preload` - Preload on hover/focus for perceived speed
+
+### 3. Server-Side Performance (HIGH)
+
+- `server-auth-actions` - Authenticate server actions like API routes
+- `server-cache-react` - Use React.cache() for per-request deduplication
+- `server-cache-lru` - Use LRU cache for cross-request caching
+- `server-dedup-props` - Avoid duplicate serialization in RSC props
+- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
+- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR
+- `server-serialization` - Minimize data passed to client components
+- `server-parallel-fetching` - Restructure components to parallelize fetches
+- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
+- `server-after-nonblocking` - Use after() for non-blocking operations
+
+### 4. Client-Side Data Fetching (MEDIUM-HIGH)
+
+- `client-swr-dedup` - Use SWR for automatic request deduplication
+- `client-event-listeners` - Deduplicate global event listeners
+- `client-passive-event-listeners` - Use passive listeners for scroll
+- `client-localstorage-schema` - Version and minimize localStorage data
+
+### 5. Re-render Optimization (MEDIUM)
+
+- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
+- `rerender-memo` - Extract expensive work into memoized components
+- `rerender-memo-with-default-value` - Hoist default non-primitive props
+- `rerender-dependencies` - Use primitive dependencies in effects
+- `rerender-derived-state` - Subscribe to derived booleans, not raw values
+- `rerender-derived-state-no-effect` - Derive state during render, not effects
+- `rerender-functional-setstate` - Use functional setState for stable callbacks
+- `rerender-lazy-state-init` - Pass function to useState for expensive values
+- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
+- `rerender-split-combined-hooks` - Split hooks with independent dependencies
+- `rerender-move-effect-to-event` - Put interaction logic in event handlers
+- `rerender-transitions` - Use startTransition for non-urgent updates
+- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
+- `rerender-use-ref-transient-values` - Use refs for transient frequent values
+- `rerender-no-inline-components` - Don't define components inside components
+
+### 6. Rendering Performance (MEDIUM)
+
+- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
+- `rendering-content-visibility` - Use content-visibility for long lists
+- `rendering-hoist-jsx` - Extract static JSX outside components
+- `rendering-svg-precision` - Reduce SVG coordinate precision
+- `rendering-hydration-no-flicker` - Use inline script for client-only data
+- `rendering-hydration-suppress-warning` - Suppress expected mismatches
+- `rendering-activity` - Use Activity component for show/hide
+- `rendering-conditional-render` - Use ternary, not && for conditionals
+- `rendering-usetransition-loading` - Prefer useTransition for loading state
+- `rendering-resource-hints` - Use React DOM resource hints for preloading
+- `rendering-script-defer-async` - Use defer or async on script tags
+
+### 7. JavaScript Performance (LOW-MEDIUM)
+
+- `js-batch-dom-css` - Group CSS changes via classes or cssText
+- `js-index-maps` - Build Map for repeated lookups
+- `js-cache-property-access` - Cache object properties in loops
+- `js-cache-function-results` - Cache function results in module-level Map
+- `js-cache-storage` - Cache localStorage/sessionStorage reads
+- `js-combine-iterations` - Combine multiple filter/map into one loop
+- `js-length-check-first` - Check array length before expensive comparison
+- `js-early-exit` - Return early from functions
+- `js-hoist-regexp` - Hoist RegExp creation outside loops
+- `js-min-max-loop` - Use loop for min/max instead of sort
+- `js-set-map-lookups` - Use Set/Map for O(1) lookups
+- `js-tosorted-immutable` - Use toSorted() for immutability
+- `js-flatmap-filter` - Use flatMap to map and filter in one pass
+- `js-request-idle-callback` - Defer non-critical work to browser idle time
+
+### 8. Advanced Patterns (LOW)
+
+- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps
+- `advanced-event-handler-refs` - Store event handlers in refs
+- `advanced-init-once` - Initialize app once per app load
+- `advanced-use-latest` - useLatest for stable callback refs
+
+## How to Use
+
+Read individual rule files for detailed explanations and code examples:
+
+```
+rules/async-parallel.md
+rules/bundle-barrel-imports.md
+```
+
+Each rule file contains:
+- Brief explanation of why it matters
+- Incorrect code example with explanation
+- Correct code example with explanation
+- Additional context and references
+
+## Full Compiled Document
+
+For the complete guide with all rules expanded: `AGENTS.md`
diff --git a/.agents/skills/vercel-react-best-practices/metadata.json b/.agents/skills/vercel-react-best-practices/metadata.json
new file mode 100644
index 00000000..61b6b6a2
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/metadata.json
@@ -0,0 +1,15 @@
+{
+ "version": "1.0.0",
+ "organization": "Vercel Engineering",
+ "date": "January 2026",
+ "abstract": "Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.",
+ "references": [
+ "https://react.dev",
+ "https://nextjs.org",
+ "https://swr.vercel.app",
+ "https://github.com/shuding/better-all",
+ "https://github.com/isaacs/node-lru-cache",
+ "https://vercel.com/blog/how-we-optimized-package-imports-in-next-js",
+ "https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast"
+ ]
+}
diff --git a/.agents/skills/vercel-react-best-practices/rules/_sections.md b/.agents/skills/vercel-react-best-practices/rules/_sections.md
new file mode 100644
index 00000000..4d20c144
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/_sections.md
@@ -0,0 +1,46 @@
+# Sections
+
+This file defines all sections, their ordering, impact levels, and descriptions.
+The section ID (in parentheses) is the filename prefix used to group rules.
+
+---
+
+## 1. Eliminating Waterfalls (async)
+
+**Impact:** CRITICAL
+**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
+
+## 2. Bundle Size Optimization (bundle)
+
+**Impact:** CRITICAL
+**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
+
+## 3. Server-Side Performance (server)
+
+**Impact:** HIGH
+**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
+
+## 4. Client-Side Data Fetching (client)
+
+**Impact:** MEDIUM-HIGH
+**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
+
+## 5. Re-render Optimization (rerender)
+
+**Impact:** MEDIUM
+**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
+
+## 6. Rendering Performance (rendering)
+
+**Impact:** MEDIUM
+**Description:** Optimizing the rendering process reduces the work the browser needs to do.
+
+## 7. JavaScript Performance (js)
+
+**Impact:** LOW-MEDIUM
+**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
+
+## 8. Advanced Patterns (advanced)
+
+**Impact:** LOW
+**Description:** Advanced patterns for specific cases that require careful implementation.
diff --git a/.agents/skills/vercel-react-best-practices/rules/_template.md b/.agents/skills/vercel-react-best-practices/rules/_template.md
new file mode 100644
index 00000000..1e9e7070
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/_template.md
@@ -0,0 +1,28 @@
+---
+title: Rule Title Here
+impact: MEDIUM
+impactDescription: Optional description of impact (e.g., "20-50% improvement")
+tags: tag1, tag2
+---
+
+## Rule Title Here
+
+**Impact: MEDIUM (optional impact description)**
+
+Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
+
+**Incorrect (description of what's wrong):**
+
+```typescript
+// Bad code example here
+const bad = example()
+```
+
+**Correct (description of what's right):**
+
+```typescript
+// Good code example here
+const good = example()
+```
+
+Reference: [Link to documentation or resource](https://example.com)
diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md b/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md
new file mode 100644
index 00000000..24d901b6
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md
@@ -0,0 +1,56 @@
+---
+title: Do Not Put Effect Events in Dependency Arrays
+impact: LOW
+impactDescription: avoids unnecessary effect re-runs and lint errors
+tags: advanced, hooks, useEffectEvent, dependencies, effects
+---
+
+## Do Not Put Effect Events in Dependency Arrays
+
+Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
+
+**Incorrect (Effect Event added as a dependency):**
+
+```tsx
+import { useEffect, useEffectEvent } from 'react'
+
+function ChatRoom({ roomId, onConnected }: {
+ roomId: string
+ onConnected: () => void
+}) {
+ const handleConnected = useEffectEvent(onConnected)
+
+ useEffect(() => {
+ const connection = createConnection(roomId)
+ connection.on('connected', handleConnected)
+ connection.connect()
+
+ return () => connection.disconnect()
+ }, [roomId, handleConnected])
+}
+```
+
+Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
+
+**Correct (depend on reactive values, not the Effect Event):**
+
+```tsx
+import { useEffect, useEffectEvent } from 'react'
+
+function ChatRoom({ roomId, onConnected }: {
+ roomId: string
+ onConnected: () => void
+}) {
+ const handleConnected = useEffectEvent(onConnected)
+
+ useEffect(() => {
+ const connection = createConnection(roomId)
+ connection.on('connected', handleConnected)
+ connection.connect()
+
+ return () => connection.disconnect()
+ }, [roomId])
+}
+```
+
+Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md b/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md
new file mode 100644
index 00000000..97e7ade2
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md
@@ -0,0 +1,55 @@
+---
+title: Store Event Handlers in Refs
+impact: LOW
+impactDescription: stable subscriptions
+tags: advanced, hooks, refs, event-handlers, optimization
+---
+
+## Store Event Handlers in Refs
+
+Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
+
+**Incorrect (re-subscribes on every render):**
+
+```tsx
+function useWindowEvent(event: string, handler: (e) => void) {
+ useEffect(() => {
+ window.addEventListener(event, handler)
+ return () => window.removeEventListener(event, handler)
+ }, [event, handler])
+}
+```
+
+**Correct (stable subscription):**
+
+```tsx
+function useWindowEvent(event: string, handler: (e) => void) {
+ const handlerRef = useRef(handler)
+ useEffect(() => {
+ handlerRef.current = handler
+ }, [handler])
+
+ useEffect(() => {
+ const listener = (e) => handlerRef.current(e)
+ window.addEventListener(event, listener)
+ return () => window.removeEventListener(event, listener)
+ }, [event])
+}
+```
+
+**Alternative: use `useEffectEvent` if you're on latest React:**
+
+```tsx
+import { useEffectEvent } from 'react'
+
+function useWindowEvent(event: string, handler: (e) => void) {
+ const onEvent = useEffectEvent(handler)
+
+ useEffect(() => {
+ window.addEventListener(event, onEvent)
+ return () => window.removeEventListener(event, onEvent)
+ }, [event])
+}
+```
+
+`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md b/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md
new file mode 100644
index 00000000..73ee38e5
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md
@@ -0,0 +1,42 @@
+---
+title: Initialize App Once, Not Per Mount
+impact: LOW-MEDIUM
+impactDescription: avoids duplicate init in development
+tags: initialization, useEffect, app-startup, side-effects
+---
+
+## Initialize App Once, Not Per Mount
+
+Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
+
+**Incorrect (runs twice in dev, re-runs on remount):**
+
+```tsx
+function Comp() {
+ useEffect(() => {
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+**Correct (once per app load):**
+
+```tsx
+let didInit = false
+
+function Comp() {
+ useEffect(() => {
+ if (didInit) return
+ didInit = true
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md b/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md
new file mode 100644
index 00000000..9c7cb501
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md
@@ -0,0 +1,39 @@
+---
+title: useEffectEvent for Stable Callback Refs
+impact: LOW
+impactDescription: prevents effect re-runs
+tags: advanced, hooks, useEffectEvent, refs, optimization
+---
+
+## useEffectEvent for Stable Callback Refs
+
+Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
+
+**Incorrect (effect re-runs on every callback change):**
+
+```tsx
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearch(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query, onSearch])
+}
+```
+
+**Correct (using React's useEffectEvent):**
+
+```tsx
+import { useEffectEvent } from 'react';
+
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+ const onSearchEvent = useEffectEvent(onSearch)
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearchEvent(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query])
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md b/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md
new file mode 100644
index 00000000..6feda1ef
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md
@@ -0,0 +1,38 @@
+---
+title: Prevent Waterfall Chains in API Routes
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: api-routes, server-actions, waterfalls, parallelization
+---
+
+## Prevent Waterfall Chains in API Routes
+
+In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
+
+**Incorrect (config waits for auth, data waits for both):**
+
+```typescript
+export async function GET(request: Request) {
+ const session = await auth()
+ const config = await fetchConfig()
+ const data = await fetchData(session.user.id)
+ return Response.json({ data, config })
+}
+```
+
+**Correct (auth and config start immediately):**
+
+```typescript
+export async function GET(request: Request) {
+ const sessionPromise = auth()
+ const configPromise = fetchConfig()
+ const session = await sessionPromise
+ const [config, data] = await Promise.all([
+ configPromise,
+ fetchData(session.user.id)
+ ])
+ return Response.json({ data, config })
+}
+```
+
+For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
diff --git a/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md b/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md
new file mode 100644
index 00000000..5799d7f6
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md
@@ -0,0 +1,37 @@
+---
+title: Check Cheap Conditions Before Async Flags
+impact: HIGH
+impactDescription: avoids unnecessary async work when a synchronous guard already fails
+tags: async, await, feature-flags, short-circuit, conditional
+---
+
+## Check Cheap Conditions Before Async Flags
+
+When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
+
+This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
+
+**Incorrect:**
+
+```typescript
+const someFlag = await getFlag()
+
+if (someFlag && someCondition) {
+ // ...
+}
+```
+
+**Correct:**
+
+```typescript
+if (someCondition) {
+ const someFlag = await getFlag()
+ if (someFlag) {
+ // ...
+ }
+}
+```
+
+This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
+
+Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
diff --git a/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md
new file mode 100644
index 00000000..460b5e16
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md
@@ -0,0 +1,82 @@
+---
+title: Defer Await Until Needed
+impact: HIGH
+impactDescription: avoids blocking unused code paths
+tags: async, await, conditional, optimization
+---
+
+## Defer Await Until Needed
+
+Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
+
+**Incorrect (blocks both branches):**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ const userData = await fetchUserData(userId)
+
+ if (skipProcessing) {
+ // Returns immediately but still waited for userData
+ return { skipped: true }
+ }
+
+ // Only this branch uses userData
+ return processUserData(userData)
+}
+```
+
+**Correct (only blocks when needed):**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ if (skipProcessing) {
+ // Returns immediately without waiting
+ return { skipped: true }
+ }
+
+ // Fetch only when needed
+ const userData = await fetchUserData(userId)
+ return processUserData(userData)
+}
+```
+
+**Another example (early return optimization):**
+
+```typescript
+// Incorrect: always fetches permissions
+async function updateResource(resourceId: string, userId: string) {
+ const permissions = await fetchPermissions(userId)
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+
+// Correct: fetches only when needed
+async function updateResource(resourceId: string, userId: string) {
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ const permissions = await fetchPermissions(userId)
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+```
+
+This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
+
+For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
diff --git a/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md
new file mode 100644
index 00000000..0484ebab
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md
@@ -0,0 +1,51 @@
+---
+title: Dependency-Based Parallelization
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: async, parallelization, dependencies, better-all
+---
+
+## Dependency-Based Parallelization
+
+For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
+
+**Incorrect (profile waits for config unnecessarily):**
+
+```typescript
+const [user, config] = await Promise.all([
+ fetchUser(),
+ fetchConfig()
+])
+const profile = await fetchProfile(user.id)
+```
+
+**Correct (config and profile run in parallel):**
+
+```typescript
+import { all } from 'better-all'
+
+const { user, config, profile } = await all({
+ async user() { return fetchUser() },
+ async config() { return fetchConfig() },
+ async profile() {
+ return fetchProfile((await this.$.user).id)
+ }
+})
+```
+
+**Alternative without extra dependencies:**
+
+We can also create all the promises first, and do `Promise.all()` at the end.
+
+```typescript
+const userPromise = fetchUser()
+const profilePromise = userPromise.then(user => fetchProfile(user.id))
+
+const [user, config, profile] = await Promise.all([
+ userPromise,
+ fetchConfig(),
+ profilePromise
+])
+```
+
+Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
diff --git a/.agents/skills/vercel-react-best-practices/rules/async-parallel.md b/.agents/skills/vercel-react-best-practices/rules/async-parallel.md
new file mode 100644
index 00000000..64133f6c
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/async-parallel.md
@@ -0,0 +1,28 @@
+---
+title: Promise.all() for Independent Operations
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: async, parallelization, promises, waterfalls
+---
+
+## Promise.all() for Independent Operations
+
+When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
+
+**Incorrect (sequential execution, 3 round trips):**
+
+```typescript
+const user = await fetchUser()
+const posts = await fetchPosts()
+const comments = await fetchComments()
+```
+
+**Correct (parallel execution, 1 round trip):**
+
+```typescript
+const [user, posts, comments] = await Promise.all([
+ fetchUser(),
+ fetchPosts(),
+ fetchComments()
+])
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md
new file mode 100644
index 00000000..1fbc05b0
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md
@@ -0,0 +1,99 @@
+---
+title: Strategic Suspense Boundaries
+impact: HIGH
+impactDescription: faster initial paint
+tags: async, suspense, streaming, layout-shift
+---
+
+## Strategic Suspense Boundaries
+
+Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
+
+**Incorrect (wrapper blocked by data fetching):**
+
+```tsx
+async function Page() {
+ const data = await fetchData() // Blocks entire page
+
+ return (
+ <div>
+ <div>Sidebar</div>
+ <div>Header</div>
+ <div>
+ <DataDisplay data={data} />
+ </div>
+ <div>Footer</div>
+ </div>
+ )
+}
+```
+
+The entire layout waits for data even though only the middle section needs it.
+
+**Correct (wrapper shows immediately, data streams in):**
+
+```tsx
+function Page() {
+ return (
+ <div>
+ <div>Sidebar</div>
+ <div>Header</div>
+ <div>
+ <Suspense fallback={<Skeleton />}>
+ <DataDisplay />
+ </Suspense>
+ </div>
+ <div>Footer</div>
+ </div>
+ )
+}
+
+async function DataDisplay() {
+ const data = await fetchData() // Only blocks this component
+ return <div>{data.content}</div>
+}
+```
+
+Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
+
+**Alternative (share promise across components):**
+
+```tsx
+function Page() {
+ // Start fetch immediately, but don't await
+ const dataPromise = fetchData()
+
+ return (
+ <div>
+ <div>Sidebar</div>
+ <div>Header</div>
+ <Suspense fallback={<Skeleton />}>
+ <DataDisplay dataPromise={dataPromise} />
+ <DataSummary dataPromise={dataPromise} />
+ </Suspense>
+ <div>Footer</div>
+ </div>
+ )
+}
+
+function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
+ const data = use(dataPromise) // Unwraps the promise
+ return <div>{data.content}</div>
+}
+
+function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
+ const data = use(dataPromise) // Reuses the same promise
+ return <div>{data.summary}</div>
+}
+```
+
+Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
+
+**When NOT to use this pattern:**
+
+- Critical data needed for layout decisions (affects positioning)
+- SEO-critical content above the fold
+- Small, fast queries where suspense overhead isn't worth it
+- When you want to avoid layout shift (loading → content jump)
+
+**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md b/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md
new file mode 100644
index 00000000..8276f156
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md
@@ -0,0 +1,63 @@
+---
+title: Prefer Statically Analyzable Paths
+impact: HIGH
+impactDescription: avoids accidental broad bundles and file traces
+tags: bundle, nextjs, vite, webpack, rollup, esbuild, path
+---
+
+## Prefer Statically Analyzable Paths
+
+Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
+
+Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.
+
+When analysis becomes too broad, the cost is real:
+- Larger server bundles
+- Slower builds
+- Worse cold starts
+- More memory use
+
+### Import Paths
+
+**Incorrect (the bundler cannot tell what may be imported):**
+
+```ts
+const PAGE_MODULES = {
+ home: './pages/home',
+ settings: './pages/settings',
+} as const
+
+const Page = await import(PAGE_MODULES[pageName])
+```
+
+**Correct (use an explicit map of allowed modules):**
+
+```ts
+const PAGE_MODULES = {
+ home: () => import('./pages/home'),
+ settings: () => import('./pages/settings'),
+} as const
+
+const Page = await PAGE_MODULES[pageName]()
+```
+
+### File-System Paths
+
+**Incorrect (a 2-value enum still hides the final path from static analysis):**
+
+```ts
+const baseDir = path.join(process.cwd(), 'content/' + contentKind)
+```
+
+**Correct (make each final path literal at the callsite):**
+
+```ts
+const baseDir =
+ kind === ContentKind.Blog
+ ? path.join(process.cwd(), 'content/blog')
+ : path.join(process.cwd(), 'content/docs')
+```
+
+In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.
+
+Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)
diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md
new file mode 100644
index 00000000..22d10501
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md
@@ -0,0 +1,60 @@
+---
+title: Avoid Barrel File Imports
+impact: CRITICAL
+impactDescription: 200-800ms import cost, slow builds
+tags: bundle, imports, tree-shaking, barrel-files, performance
+---
+
+## Avoid Barrel File Imports
+
+Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
+
+Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
+
+**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
+
+**Incorrect (imports entire library):**
+
+```tsx
+import { Check, X, Menu } from 'lucide-react'
+// Loads 1,583 modules, takes ~2.8s extra in dev
+// Runtime cost: 200-800ms on every cold start
+
+import { Button, TextField } from '@mui/material'
+// Loads 2,225 modules, takes ~4.2s extra in dev
+```
+
+**Correct - Next.js 13.5+ (recommended):**
+
+```js
+// next.config.js - automatically optimizes barrel imports at build time
+module.exports = {
+ experimental: {
+ optimizePackageImports: ['lucide-react', '@mui/material']
+ }
+}
+```
+
+```tsx
+// Keep the standard imports - Next.js transforms them to direct imports
+import { Check, X, Menu } from 'lucide-react'
+// Full TypeScript support, no manual path wrangling
+```
+
+This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
+
+**Correct - Direct imports (non-Next.js projects):**
+
+```tsx
+import Button from '@mui/material/Button'
+import TextField from '@mui/material/TextField'
+// Loads only what you use
+```
+
+> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
+
+These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
+
+Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
+
+Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md b/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md
new file mode 100644
index 00000000..99d6fc90
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md
@@ -0,0 +1,31 @@
+---
+title: Conditional Module Loading
+impact: HIGH
+impactDescription: loads large data only when needed
+tags: bundle, conditional-loading, lazy-loading
+---
+
+## Conditional Module Loading
+
+Load large data or modules only when a feature is activated.
+
+**Example (lazy-load animation frames):**
+
+```tsx
+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
+ const [frames, setFrames] = useState<Frame[] | null>(null)
+
+ useEffect(() => {
+ if (enabled && !frames && typeof window !== 'undefined') {
+ import('./animation-frames.js')
+ .then(mod => setFrames(mod.frames))
+ .catch(() => setEnabled(false))
+ }
+ }, [enabled, frames, setEnabled])
+
+ if (!frames) return <Skeleton />
+ return <Canvas frames={frames} />
+}
+```
+
+The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md b/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md
new file mode 100644
index 00000000..db041d15
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md
@@ -0,0 +1,49 @@
+---
+title: Defer Non-Critical Third-Party Libraries
+impact: MEDIUM
+impactDescription: loads after hydration
+tags: bundle, third-party, analytics, defer
+---
+
+## Defer Non-Critical Third-Party Libraries
+
+Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
+
+**Incorrect (blocks initial bundle):**
+
+```tsx
+import { Analytics } from '@vercel/analytics/react'
+
+export default function RootLayout({ children }) {
+ return (
+ <html>
+ <body>
+ {children}
+ <Analytics />
+ </body>
+ </html>
+ )
+}
+```
+
+**Correct (loads after hydration):**
+
+```tsx
+import dynamic from 'next/dynamic'
+
+const Analytics = dynamic(
+ () => import('@vercel/analytics/react').then(m => m.Analytics),
+ { ssr: false }
+)
+
+export default function RootLayout({ children }) {
+ return (
+ <html>
+ <body>
+ {children}
+ <Analytics />
+ </body>
+ </html>
+ )
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md
new file mode 100644
index 00000000..60b62695
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md
@@ -0,0 +1,35 @@
+---
+title: Dynamic Imports for Heavy Components
+impact: CRITICAL
+impactDescription: directly affects TTI and LCP
+tags: bundle, dynamic-import, code-splitting, next-dynamic
+---
+
+## Dynamic Imports for Heavy Components
+
+Use `next/dynamic` to lazy-load large components not needed on initial render.
+
+**Incorrect (Monaco bundles with main chunk ~300KB):**
+
+```tsx
+import { MonacoEditor } from './monaco-editor'
+
+function CodePanel({ code }: { code: string }) {
+ return <MonacoEditor value={code} />
+}
+```
+
+**Correct (Monaco loads on demand):**
+
+```tsx
+import dynamic from 'next/dynamic'
+
+const MonacoEditor = dynamic(
+ () => import('./monaco-editor').then(m => m.MonacoEditor),
+ { ssr: false }
+)
+
+function CodePanel({ code }: { code: string }) {
+ return <MonacoEditor value={code} />
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md b/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md
new file mode 100644
index 00000000..70005040
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md
@@ -0,0 +1,50 @@
+---
+title: Preload Based on User Intent
+impact: MEDIUM
+impactDescription: reduces perceived latency
+tags: bundle, preload, user-intent, hover
+---
+
+## Preload Based on User Intent
+
+Preload heavy bundles before they're needed to reduce perceived latency.
+
+**Example (preload on hover/focus):**
+
+```tsx
+function EditorButton({ onClick }: { onClick: () => void }) {
+ const preload = () => {
+ if (typeof window !== 'undefined') {
+ void import('./monaco-editor')
+ }
+ }
+
+ return (
+ <button
+ onMouseEnter={preload}
+ onFocus={preload}
+ onClick={onClick}
+ >
+ Open Editor
+ </button>
+ )
+}
+```
+
+**Example (preload when feature flag is enabled):**
+
+```tsx
+function FlagsProvider({ children, flags }: Props) {
+ useEffect(() => {
+ if (flags.editorEnabled && typeof window !== 'undefined') {
+ void import('./monaco-editor').then(mod => mod.init())
+ }
+ }, [flags.editorEnabled])
+
+ return <FlagsContext.Provider value={flags}>
+ {children}
+ </FlagsContext.Provider>
+}
+```
+
+The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
diff --git a/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md
new file mode 100644
index 00000000..aad4ae91
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md
@@ -0,0 +1,74 @@
+---
+title: Deduplicate Global Event Listeners
+impact: LOW
+impactDescription: single listener for N components
+tags: client, swr, event-listeners, subscription
+---
+
+## Deduplicate Global Event Listeners
+
+Use `useSWRSubscription()` to share global event listeners across component instances.
+
+**Incorrect (N instances = N listeners):**
+
+```tsx
+function useKeyboardShortcut(key: string, callback: () => void) {
+ useEffect(() => {
+ const handler = (e: KeyboardEvent) => {
+ if (e.metaKey && e.key === key) {
+ callback()
+ }
+ }
+ window.addEventListener('keydown', handler)
+ return () => window.removeEventListener('keydown', handler)
+ }, [key, callback])
+}
+```
+
+When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
+
+**Correct (N instances = 1 listener):**
+
+```tsx
+import useSWRSubscription from 'swr/subscription'
+
+// Module-level Map to track callbacks per key
+const keyCallbacks = new Map<string, Set<() => void>>()
+
+function useKeyboardShortcut(key: string, callback: () => void) {
+ // Register this callback in the Map
+ useEffect(() => {
+ if (!keyCallbacks.has(key)) {
+ keyCallbacks.set(key, new Set())
+ }
+ keyCallbacks.get(key)!.add(callback)
+
+ return () => {
+ const set = keyCallbacks.get(key)
+ if (set) {
+ set.delete(callback)
+ if (set.size === 0) {
+ keyCallbacks.delete(key)
+ }
+ }
+ }
+ }, [key, callback])
+
+ useSWRSubscription('global-keydown', () => {
+ const handler = (e: KeyboardEvent) => {
+ if (e.metaKey && keyCallbacks.has(e.key)) {
+ keyCallbacks.get(e.key)!.forEach(cb => cb())
+ }
+ }
+ window.addEventListener('keydown', handler)
+ return () => window.removeEventListener('keydown', handler)
+ })
+}
+
+function Profile() {
+ // Multiple shortcuts will share the same listener
+ useKeyboardShortcut('p', () => { /* ... */ })
+ useKeyboardShortcut('k', () => { /* ... */ })
+ // ...
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md b/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md
new file mode 100644
index 00000000..d30a1a7d
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md
@@ -0,0 +1,71 @@
+---
+title: Version and Minimize localStorage Data
+impact: MEDIUM
+impactDescription: prevents schema conflicts, reduces storage size
+tags: client, localStorage, storage, versioning, data-minimization
+---
+
+## Version and Minimize localStorage Data
+
+Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
+
+**Incorrect:**
+
+```typescript
+// No version, stores everything, no error handling
+localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
+const data = localStorage.getItem('userConfig')
+```
+
+**Correct:**
+
+```typescript
+const VERSION = 'v2'
+
+function saveConfig(config: { theme: string; language: string }) {
+ try {
+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
+ } catch {
+ // Throws in incognito/private browsing, quota exceeded, or disabled
+ }
+}
+
+function loadConfig() {
+ try {
+ const data = localStorage.getItem(`userConfig:${VERSION}`)
+ return data ? JSON.parse(data) : null
+ } catch {
+ return null
+ }
+}
+
+// Migration from v1 to v2
+function migrate() {
+ try {
+ const v1 = localStorage.getItem('userConfig:v1')
+ if (v1) {
+ const old = JSON.parse(v1)
+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
+ localStorage.removeItem('userConfig:v1')
+ }
+ } catch {}
+}
+```
+
+**Store minimal fields from server responses:**
+
+```typescript
+// User object has 20+ fields, only store what UI needs
+function cachePrefs(user: FullUser) {
+ try {
+ localStorage.setItem('prefs:v1', JSON.stringify({
+ theme: user.preferences.theme,
+ notifications: user.preferences.notifications
+ }))
+ } catch {}
+}
+```
+
+**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
+
+**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
diff --git a/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md
new file mode 100644
index 00000000..ce39a889
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md
@@ -0,0 +1,48 @@
+---
+title: Use Passive Event Listeners for Scrolling Performance
+impact: MEDIUM
+impactDescription: eliminates scroll delay caused by event listeners
+tags: client, event-listeners, scrolling, performance, touch, wheel
+---
+
+## Use Passive Event Listeners for Scrolling Performance
+
+Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
+
+**Incorrect:**
+
+```typescript
+useEffect(() => {
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
+
+ document.addEventListener('touchstart', handleTouch)
+ document.addEventListener('wheel', handleWheel)
+
+ return () => {
+ document.removeEventListener('touchstart', handleTouch)
+ document.removeEventListener('wheel', handleWheel)
+ }
+}, [])
+```
+
+**Correct:**
+
+```typescript
+useEffect(() => {
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
+
+ document.addEventListener('touchstart', handleTouch, { passive: true })
+ document.addEventListener('wheel', handleWheel, { passive: true })
+
+ return () => {
+ document.removeEventListener('touchstart', handleTouch)
+ document.removeEventListener('wheel', handleWheel)
+ }
+}, [])
+```
+
+**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
+
+**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
diff --git a/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md b/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md
new file mode 100644
index 00000000..2a430f27
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md
@@ -0,0 +1,56 @@
+---
+title: Use SWR for Automatic Deduplication
+impact: MEDIUM-HIGH
+impactDescription: automatic deduplication
+tags: client, swr, deduplication, data-fetching
+---
+
+## Use SWR for Automatic Deduplication
+
+SWR enables request deduplication, caching, and revalidation across component instances.
+
+**Incorrect (no deduplication, each instance fetches):**
+
+```tsx
+function UserList() {
+ const [users, setUsers] = useState([])
+ useEffect(() => {
+ fetch('/api/users')
+ .then(r => r.json())
+ .then(setUsers)
+ }, [])
+}
+```
+
+**Correct (multiple instances share one request):**
+
+```tsx
+import useSWR from 'swr'
+
+function UserList() {
+ const { data: users } = useSWR('/api/users', fetcher)
+}
+```
+
+**For immutable data:**
+
+```tsx
+import { useImmutableSWR } from '@/lib/swr'
+
+function StaticContent() {
+ const { data } = useImmutableSWR('/api/config', fetcher)
+}
+```
+
+**For mutations:**
+
+```tsx
+import { useSWRMutation } from 'swr/mutation'
+
+function UpdateButton() {
+ const { trigger } = useSWRMutation('/api/user', updateUser)
+ return <button onClick={() => trigger()}>Update</button>
+}
+```
+
+Reference: [https://swr.vercel.app](https://swr.vercel.app)
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md b/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md
new file mode 100644
index 00000000..a62d84ed
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md
@@ -0,0 +1,107 @@
+---
+title: Avoid Layout Thrashing
+impact: MEDIUM
+impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
+tags: javascript, dom, css, performance, reflow, layout-thrashing
+---
+
+## Avoid Layout Thrashing
+
+Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
+
+**This is OK (browser batches style changes):**
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ // Each line invalidates style, but browser batches the recalculation
+ element.style.width = '100px'
+ element.style.height = '200px'
+ element.style.backgroundColor = 'blue'
+ element.style.border = '1px solid black'
+}
+```
+
+**Incorrect (interleaved reads and writes force reflows):**
+```typescript
+function layoutThrashing(element: HTMLElement) {
+ element.style.width = '100px'
+ const width = element.offsetWidth // Forces reflow
+ element.style.height = '200px'
+ const height = element.offsetHeight // Forces another reflow
+}
+```
+
+**Correct (batch writes, then read once):**
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ // Batch all writes together
+ element.style.width = '100px'
+ element.style.height = '200px'
+ element.style.backgroundColor = 'blue'
+ element.style.border = '1px solid black'
+
+ // Read after all writes are done (single reflow)
+ const { width, height } = element.getBoundingClientRect()
+}
+```
+
+**Correct (batch reads, then writes):**
+```typescript
+function avoidThrashing(element: HTMLElement) {
+ // Read phase - all layout queries first
+ const rect1 = element.getBoundingClientRect()
+ const offsetWidth = element.offsetWidth
+ const offsetHeight = element.offsetHeight
+
+ // Write phase - all style changes after
+ element.style.width = '100px'
+ element.style.height = '200px'
+}
+```
+
+**Better: use CSS classes**
+```css
+.highlighted-box {
+ width: 100px;
+ height: 200px;
+ background-color: blue;
+ border: 1px solid black;
+}
+```
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ element.classList.add('highlighted-box')
+
+ const { width, height } = element.getBoundingClientRect()
+}
+```
+
+**React example:**
+```tsx
+// Incorrect: interleaving style changes with layout queries
+function Box({ isHighlighted }: { isHighlighted: boolean }) {
+ const ref = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (ref.current && isHighlighted) {
+ ref.current.style.width = '100px'
+ const width = ref.current.offsetWidth // Forces layout
+ ref.current.style.height = '200px'
+ }
+ }, [isHighlighted])
+
+ return <div ref={ref}>Content</div>
+}
+
+// Correct: toggle class
+function Box({ isHighlighted }: { isHighlighted: boolean }) {
+ return (
+ <div className={isHighlighted ? 'highlighted-box' : ''}>
+ Content
+ </div>
+ )
+}
+```
+
+Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
+
+See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md
new file mode 100644
index 00000000..180f8ac8
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md
@@ -0,0 +1,80 @@
+---
+title: Cache Repeated Function Calls
+impact: MEDIUM
+impactDescription: avoid redundant computation
+tags: javascript, cache, memoization, performance
+---
+
+## Cache Repeated Function Calls
+
+Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
+
+**Incorrect (redundant computation):**
+
+```typescript
+function ProjectList({ projects }: { projects: Project[] }) {
+ return (
+ <div>
+ {projects.map(project => {
+ // slugify() called 100+ times for same project names
+ const slug = slugify(project.name)
+
+ return <ProjectCard key={project.id} slug={slug} />
+ })}
+ </div>
+ )
+}
+```
+
+**Correct (cached results):**
+
+```typescript
+// Module-level cache
+const slugifyCache = new Map<string, string>()
+
+function cachedSlugify(text: string): string {
+ if (slugifyCache.has(text)) {
+ return slugifyCache.get(text)!
+ }
+ const result = slugify(text)
+ slugifyCache.set(text, result)
+ return result
+}
+
+function ProjectList({ projects }: { projects: Project[] }) {
+ return (
+ <div>
+ {projects.map(project => {
+ // Computed only once per unique project name
+ const slug = cachedSlugify(project.name)
+
+ return <ProjectCard key={project.id} slug={slug} />
+ })}
+ </div>
+ )
+}
+```
+
+**Simpler pattern for single-value functions:**
+
+```typescript
+let isLoggedInCache: boolean | null = null
+
+function isLoggedIn(): boolean {
+ if (isLoggedInCache !== null) {
+ return isLoggedInCache
+ }
+
+ isLoggedInCache = document.cookie.includes('auth=')
+ return isLoggedInCache
+}
+
+// Clear cache when auth changes
+function onAuthChange() {
+ isLoggedInCache = null
+}
+```
+
+Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
+
+Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md
new file mode 100644
index 00000000..39eec906
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md
@@ -0,0 +1,28 @@
+---
+title: Cache Property Access in Loops
+impact: LOW-MEDIUM
+impactDescription: reduces lookups
+tags: javascript, loops, optimization, caching
+---
+
+## Cache Property Access in Loops
+
+Cache object property lookups in hot paths.
+
+**Incorrect (3 lookups × N iterations):**
+
+```typescript
+for (let i = 0; i < arr.length; i++) {
+ process(obj.config.settings.value)
+}
+```
+
+**Correct (1 lookup total):**
+
+```typescript
+const value = obj.config.settings.value
+const len = arr.length
+for (let i = 0; i < len; i++) {
+ process(value)
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md
new file mode 100644
index 00000000..aa4a30c0
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md
@@ -0,0 +1,70 @@
+---
+title: Cache Storage API Calls
+impact: LOW-MEDIUM
+impactDescription: reduces expensive I/O
+tags: javascript, localStorage, storage, caching, performance
+---
+
+## Cache Storage API Calls
+
+`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
+
+**Incorrect (reads storage on every call):**
+
+```typescript
+function getTheme() {
+ return localStorage.getItem('theme') ?? 'light'
+}
+// Called 10 times = 10 storage reads
+```
+
+**Correct (Map cache):**
+
+```typescript
+const storageCache = new Map<string, string | null>()
+
+function getLocalStorage(key: string) {
+ if (!storageCache.has(key)) {
+ storageCache.set(key, localStorage.getItem(key))
+ }
+ return storageCache.get(key)
+}
+
+function setLocalStorage(key: string, value: string) {
+ localStorage.setItem(key, value)
+ storageCache.set(key, value) // keep cache in sync
+}
+```
+
+Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
+
+**Cookie caching:**
+
+```typescript
+let cookieCache: Record<string, string> | null = null
+
+function getCookie(name: string) {
+ if (!cookieCache) {
+ cookieCache = Object.fromEntries(
+ document.cookie.split('; ').map(c => c.split('='))
+ )
+ }
+ return cookieCache[name]
+}
+```
+
+**Important (invalidate on external changes):**
+
+If storage can change externally (another tab, server-set cookies), invalidate cache:
+
+```typescript
+window.addEventListener('storage', (e) => {
+ if (e.key) storageCache.delete(e.key)
+})
+
+document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'visible') {
+ storageCache.clear()
+ }
+})
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md b/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md
new file mode 100644
index 00000000..044d017e
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md
@@ -0,0 +1,32 @@
+---
+title: Combine Multiple Array Iterations
+impact: LOW-MEDIUM
+impactDescription: reduces iterations
+tags: javascript, arrays, loops, performance
+---
+
+## Combine Multiple Array Iterations
+
+Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
+
+**Incorrect (3 iterations):**
+
+```typescript
+const admins = users.filter(u => u.isAdmin)
+const testers = users.filter(u => u.isTester)
+const inactive = users.filter(u => !u.isActive)
+```
+
+**Correct (1 iteration):**
+
+```typescript
+const admins: User[] = []
+const testers: User[] = []
+const inactive: User[] = []
+
+for (const user of users) {
+ if (user.isAdmin) admins.push(user)
+ if (user.isTester) testers.push(user)
+ if (!user.isActive) inactive.push(user)
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md b/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md
new file mode 100644
index 00000000..f46cb89c
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md
@@ -0,0 +1,50 @@
+---
+title: Early Return from Functions
+impact: LOW-MEDIUM
+impactDescription: avoids unnecessary computation
+tags: javascript, functions, optimization, early-return
+---
+
+## Early Return from Functions
+
+Return early when result is determined to skip unnecessary processing.
+
+**Incorrect (processes all items even after finding answer):**
+
+```typescript
+function validateUsers(users: User[]) {
+ let hasError = false
+ let errorMessage = ''
+
+ for (const user of users) {
+ if (!user.email) {
+ hasError = true
+ errorMessage = 'Email required'
+ }
+ if (!user.name) {
+ hasError = true
+ errorMessage = 'Name required'
+ }
+ // Continues checking all users even after error found
+ }
+
+ return hasError ? { valid: false, error: errorMessage } : { valid: true }
+}
+```
+
+**Correct (returns immediately on first error):**
+
+```typescript
+function validateUsers(users: User[]) {
+ for (const user of users) {
+ if (!user.email) {
+ return { valid: false, error: 'Email required' }
+ }
+ if (!user.name) {
+ return { valid: false, error: 'Name required' }
+ }
+ }
+
+ return { valid: true }
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md b/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md
new file mode 100644
index 00000000..ee0edf0d
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md
@@ -0,0 +1,60 @@
+---
+title: Use flatMap to Map and Filter in One Pass
+impact: LOW-MEDIUM
+impactDescription: eliminates intermediate array
+tags: javascript, arrays, flatMap, filter, performance
+---
+
+## Use flatMap to Map and Filter in One Pass
+
+**Impact: LOW-MEDIUM (eliminates intermediate array)**
+
+Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
+
+**Incorrect (2 iterations, intermediate array):**
+
+```typescript
+const userNames = users
+ .map(user => user.isActive ? user.name : null)
+ .filter(Boolean)
+```
+
+**Correct (1 iteration, no intermediate array):**
+
+```typescript
+const userNames = users.flatMap(user =>
+ user.isActive ? [user.name] : []
+)
+```
+
+**More examples:**
+
+```typescript
+// Extract valid emails from responses
+// Before
+const emails = responses
+ .map(r => r.success ? r.data.email : null)
+ .filter(Boolean)
+
+// After
+const emails = responses.flatMap(r =>
+ r.success ? [r.data.email] : []
+)
+
+// Parse and filter valid numbers
+// Before
+const numbers = strings
+ .map(s => parseInt(s, 10))
+ .filter(n => !isNaN(n))
+
+// After
+const numbers = strings.flatMap(s => {
+ const n = parseInt(s, 10)
+ return isNaN(n) ? [] : [n]
+})
+```
+
+**When to use:**
+- Transforming items while filtering some out
+- Conditional mapping where some inputs produce no output
+- Parsing/validating where invalid inputs should be skipped
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md b/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md
new file mode 100644
index 00000000..dae3fefd
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md
@@ -0,0 +1,45 @@
+---
+title: Hoist RegExp Creation
+impact: LOW-MEDIUM
+impactDescription: avoids recreation
+tags: javascript, regexp, optimization, memoization
+---
+
+## Hoist RegExp Creation
+
+Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
+
+**Incorrect (new RegExp every render):**
+
+```tsx
+function Highlighter({ text, query }: Props) {
+ const regex = new RegExp(`(${query})`, 'gi')
+ const parts = text.split(regex)
+ return <>{parts.map((part, i) => ...)}</>
+}
+```
+
+**Correct (memoize or hoist):**
+
+```tsx
+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
+
+function Highlighter({ text, query }: Props) {
+ const regex = useMemo(
+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
+ [query]
+ )
+ const parts = text.split(regex)
+ return <>{parts.map((part, i) => ...)}</>
+}
+```
+
+**Warning (global regex has mutable state):**
+
+Global regex (`/g`) has mutable `lastIndex` state:
+
+```typescript
+const regex = /foo/g
+regex.test('foo') // true, lastIndex = 3
+regex.test('foo') // false, lastIndex = 0
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md b/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md
new file mode 100644
index 00000000..9d357a00
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md
@@ -0,0 +1,37 @@
+---
+title: Build Index Maps for Repeated Lookups
+impact: LOW-MEDIUM
+impactDescription: 1M ops to 2K ops
+tags: javascript, map, indexing, optimization, performance
+---
+
+## Build Index Maps for Repeated Lookups
+
+Multiple `.find()` calls by the same key should use a Map.
+
+**Incorrect (O(n) per lookup):**
+
+```typescript
+function processOrders(orders: Order[], users: User[]) {
+ return orders.map(order => ({
+ ...order,
+ user: users.find(u => u.id === order.userId)
+ }))
+}
+```
+
+**Correct (O(1) per lookup):**
+
+```typescript
+function processOrders(orders: Order[], users: User[]) {
+ const userById = new Map(users.map(u => [u.id, u]))
+
+ return orders.map(order => ({
+ ...order,
+ user: userById.get(order.userId)
+ }))
+}
+```
+
+Build map once (O(n)), then all lookups are O(1).
+For 1000 orders × 1000 users: 1M ops → 2K ops.
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md b/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md
new file mode 100644
index 00000000..8b895736
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md
@@ -0,0 +1,49 @@
+---
+title: Early Length Check for Array Comparisons
+impact: MEDIUM-HIGH
+impactDescription: avoids expensive operations when lengths differ
+tags: javascript, arrays, performance, optimization, comparison
+---
+
+## Early Length Check for Array Comparisons
+
+When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
+
+In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
+
+**Incorrect (always runs expensive comparison):**
+
+```typescript
+function hasChanges(current: string[], original: string[]) {
+ // Always sorts and joins, even when lengths differ
+ return current.sort().join() !== original.sort().join()
+}
+```
+
+Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
+
+**Correct (O(1) length check first):**
+
+```typescript
+function hasChanges(current: string[], original: string[]) {
+ // Early return if lengths differ
+ if (current.length !== original.length) {
+ return true
+ }
+ // Only sort when lengths match
+ const currentSorted = current.toSorted()
+ const originalSorted = original.toSorted()
+ for (let i = 0; i < currentSorted.length; i++) {
+ if (currentSorted[i] !== originalSorted[i]) {
+ return true
+ }
+ }
+ return false
+}
+```
+
+This new approach is more efficient because:
+- It avoids the overhead of sorting and joining the arrays when lengths differ
+- It avoids consuming memory for the joined strings (especially important for large arrays)
+- It avoids mutating the original arrays
+- It returns early when a difference is found
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md b/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md
new file mode 100644
index 00000000..4b6656e9
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md
@@ -0,0 +1,82 @@
+---
+title: Use Loop for Min/Max Instead of Sort
+impact: LOW
+impactDescription: O(n) instead of O(n log n)
+tags: javascript, arrays, performance, sorting, algorithms
+---
+
+## Use Loop for Min/Max Instead of Sort
+
+Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
+
+**Incorrect (O(n log n) - sort to find latest):**
+
+```typescript
+interface Project {
+ id: string
+ name: string
+ updatedAt: number
+}
+
+function getLatestProject(projects: Project[]) {
+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
+ return sorted[0]
+}
+```
+
+Sorts the entire array just to find the maximum value.
+
+**Incorrect (O(n log n) - sort for oldest and newest):**
+
+```typescript
+function getOldestAndNewest(projects: Project[]) {
+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
+}
+```
+
+Still sorts unnecessarily when only min/max are needed.
+
+**Correct (O(n) - single loop):**
+
+```typescript
+function getLatestProject(projects: Project[]) {
+ if (projects.length === 0) return null
+
+ let latest = projects[0]
+
+ for (let i = 1; i < projects.length; i++) {
+ if (projects[i].updatedAt > latest.updatedAt) {
+ latest = projects[i]
+ }
+ }
+
+ return latest
+}
+
+function getOldestAndNewest(projects: Project[]) {
+ if (projects.length === 0) return { oldest: null, newest: null }
+
+ let oldest = projects[0]
+ let newest = projects[0]
+
+ for (let i = 1; i < projects.length; i++) {
+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
+ }
+
+ return { oldest, newest }
+}
+```
+
+Single pass through the array, no copying, no sorting.
+
+**Alternative (Math.min/Math.max for small arrays):**
+
+```typescript
+const numbers = [5, 2, 8, 1, 9]
+const min = Math.min(...numbers)
+const max = Math.max(...numbers)
+```
+
+This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md b/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md
new file mode 100644
index 00000000..d81927e5
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md
@@ -0,0 +1,105 @@
+---
+title: Defer Non-Critical Work with requestIdleCallback
+impact: MEDIUM
+impactDescription: keeps UI responsive during background tasks
+tags: javascript, performance, idle, scheduling, analytics
+---
+
+## Defer Non-Critical Work with requestIdleCallback
+
+**Impact: MEDIUM (keeps UI responsive during background tasks)**
+
+Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
+
+**Incorrect (blocks main thread during user interaction):**
+
+```typescript
+function handleSearch(query: string) {
+ const results = searchItems(query)
+ setResults(results)
+
+ // These block the main thread immediately
+ analytics.track('search', { query })
+ saveToRecentSearches(query)
+ prefetchTopResults(results.slice(0, 3))
+}
+```
+
+**Correct (defers non-critical work to idle time):**
+
+```typescript
+function handleSearch(query: string) {
+ const results = searchItems(query)
+ setResults(results)
+
+ // Defer non-critical work to idle periods
+ requestIdleCallback(() => {
+ analytics.track('search', { query })
+ })
+
+ requestIdleCallback(() => {
+ saveToRecentSearches(query)
+ })
+
+ requestIdleCallback(() => {
+ prefetchTopResults(results.slice(0, 3))
+ })
+}
+```
+
+**With timeout for required work:**
+
+```typescript
+// Ensure analytics fires within 2 seconds even if browser stays busy
+requestIdleCallback(
+ () => analytics.track('page_view', { path: location.pathname }),
+ { timeout: 2000 }
+)
+```
+
+**Chunking large tasks:**
+
+```typescript
+function processLargeDataset(items: Item[]) {
+ let index = 0
+
+ function processChunk(deadline: IdleDeadline) {
+ // Process items while we have idle time (aim for <50ms chunks)
+ while (index < items.length && deadline.timeRemaining() > 0) {
+ processItem(items[index])
+ index++
+ }
+
+ // Schedule next chunk if more items remain
+ if (index < items.length) {
+ requestIdleCallback(processChunk)
+ }
+ }
+
+ requestIdleCallback(processChunk)
+}
+```
+
+**With fallback for unsupported browsers:**
+
+```typescript
+const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
+
+scheduleIdleWork(() => {
+ // Non-critical work
+})
+```
+
+**When to use:**
+
+- Analytics and telemetry
+- Saving state to localStorage/IndexedDB
+- Prefetching resources for likely next actions
+- Processing non-urgent data transformations
+- Lazy initialization of non-critical features
+
+**When NOT to use:**
+
+- User-initiated actions that need immediate feedback
+- Rendering updates the user is waiting for
+- Time-sensitive operations
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md b/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md
new file mode 100644
index 00000000..680a4892
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md
@@ -0,0 +1,24 @@
+---
+title: Use Set/Map for O(1) Lookups
+impact: LOW-MEDIUM
+impactDescription: O(n) to O(1)
+tags: javascript, set, map, data-structures, performance
+---
+
+## Use Set/Map for O(1) Lookups
+
+Convert arrays to Set/Map for repeated membership checks.
+
+**Incorrect (O(n) per check):**
+
+```typescript
+const allowedIds = ['a', 'b', 'c', ...]
+items.filter(item => allowedIds.includes(item.id))
+```
+
+**Correct (O(1) per check):**
+
+```typescript
+const allowedIds = new Set(['a', 'b', 'c', ...])
+items.filter(item => allowedIds.has(item.id))
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md b/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md
new file mode 100644
index 00000000..eae8b3f8
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md
@@ -0,0 +1,57 @@
+---
+title: Use toSorted() Instead of sort() for Immutability
+impact: MEDIUM-HIGH
+impactDescription: prevents mutation bugs in React state
+tags: javascript, arrays, immutability, react, state, mutation
+---
+
+## Use toSorted() Instead of sort() for Immutability
+
+`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
+
+**Incorrect (mutates original array):**
+
+```typescript
+function UserList({ users }: { users: User[] }) {
+ // Mutates the users prop array!
+ const sorted = useMemo(
+ () => users.sort((a, b) => a.name.localeCompare(b.name)),
+ [users]
+ )
+ return <div>{sorted.map(renderUser)}</div>
+}
+```
+
+**Correct (creates new array):**
+
+```typescript
+function UserList({ users }: { users: User[] }) {
+ // Creates new sorted array, original unchanged
+ const sorted = useMemo(
+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),
+ [users]
+ )
+ return <div>{sorted.map(renderUser)}</div>
+}
+```
+
+**Why this matters in React:**
+
+1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
+2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
+
+**Browser support (fallback for older browsers):**
+
+`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
+
+```typescript
+// Fallback for older browsers
+const sorted = [...items].sort((a, b) => a.value - b.value)
+```
+
+**Other immutable array methods:**
+
+- `.toSorted()` - immutable sort
+- `.toReversed()` - immutable reverse
+- `.toSpliced()` - immutable splice
+- `.with()` - immutable element replacement
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md b/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md
new file mode 100644
index 00000000..c957a490
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md
@@ -0,0 +1,26 @@
+---
+title: Use Activity Component for Show/Hide
+impact: MEDIUM
+impactDescription: preserves state/DOM
+tags: rendering, activity, visibility, state-preservation
+---
+
+## Use Activity Component for Show/Hide
+
+Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
+
+**Usage:**
+
+```tsx
+import { Activity } from 'react'
+
+function Dropdown({ isOpen }: Props) {
+ return (
+ <Activity mode={isOpen ? 'visible' : 'hidden'}>
+ <ExpensiveMenu />
+ </Activity>
+ )
+}
+```
+
+Avoids expensive re-renders and state loss.
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md b/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md
new file mode 100644
index 00000000..646744cb
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md
@@ -0,0 +1,47 @@
+---
+title: Animate SVG Wrapper Instead of SVG Element
+impact: LOW
+impactDescription: enables hardware acceleration
+tags: rendering, svg, css, animation, performance
+---
+
+## Animate SVG Wrapper Instead of SVG Element
+
+Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
+
+**Incorrect (animating SVG directly - no hardware acceleration):**
+
+```tsx
+function LoadingSpinner() {
+ return (
+ <svg
+ className="animate-spin"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ >
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
+ </svg>
+ )
+}
+```
+
+**Correct (animating wrapper div - hardware accelerated):**
+
+```tsx
+function LoadingSpinner() {
+ return (
+ <div className="animate-spin">
+ <svg
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ >
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
+ </svg>
+ </div>
+ )
+}
+```
+
+This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md b/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md
new file mode 100644
index 00000000..7e866f58
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md
@@ -0,0 +1,40 @@
+---
+title: Use Explicit Conditional Rendering
+impact: LOW
+impactDescription: prevents rendering 0 or NaN
+tags: rendering, conditional, jsx, falsy-values
+---
+
+## Use Explicit Conditional Rendering
+
+Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
+
+**Incorrect (renders "0" when count is 0):**
+
+```tsx
+function Badge({ count }: { count: number }) {
+ return (
+ <div>
+ {count && <span className="badge">{count}</span>}
+ </div>
+ )
+}
+
+// When count = 0, renders: <div>0</div>
+// When count = 5, renders: <div><span class="badge">5</span></div>
+```
+
+**Correct (renders nothing when count is 0):**
+
+```tsx
+function Badge({ count }: { count: number }) {
+ return (
+ <div>
+ {count > 0 ? <span className="badge">{count}</span> : null}
+ </div>
+ )
+}
+
+// When count = 0, renders: <div></div>
+// When count = 5, renders: <div><span class="badge">5</span></div>
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md b/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md
new file mode 100644
index 00000000..aa665636
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md
@@ -0,0 +1,38 @@
+---
+title: CSS content-visibility for Long Lists
+impact: HIGH
+impactDescription: faster initial render
+tags: rendering, css, content-visibility, long-lists
+---
+
+## CSS content-visibility for Long Lists
+
+Apply `content-visibility: auto` to defer off-screen rendering.
+
+**CSS:**
+
+```css
+.message-item {
+ content-visibility: auto;
+ contain-intrinsic-size: 0 80px;
+}
+```
+
+**Example:**
+
+```tsx
+function MessageList({ messages }: { messages: Message[] }) {
+ return (
+ <div className="overflow-y-auto h-screen">
+ {messages.map(msg => (
+ <div key={msg.id} className="message-item">
+ <Avatar user={msg.author} />
+ <div>{msg.content}</div>
+ </div>
+ ))}
+ </div>
+ )
+}
+```
+
+For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md
new file mode 100644
index 00000000..32d2f3fc
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md
@@ -0,0 +1,46 @@
+---
+title: Hoist Static JSX Elements
+impact: LOW
+impactDescription: avoids re-creation
+tags: rendering, jsx, static, optimization
+---
+
+## Hoist Static JSX Elements
+
+Extract static JSX outside components to avoid re-creation.
+
+**Incorrect (recreates element every render):**
+
+```tsx
+function LoadingSkeleton() {
+ return <div className="animate-pulse h-20 bg-gray-200" />
+}
+
+function Container() {
+ return (
+ <div>
+ {loading && <LoadingSkeleton />}
+ </div>
+ )
+}
+```
+
+**Correct (reuses same element):**
+
+```tsx
+const loadingSkeleton = (
+ <div className="animate-pulse h-20 bg-gray-200" />
+)
+
+function Container() {
+ return (
+ <div>
+ {loading && loadingSkeleton}
+ </div>
+ )
+}
+```
+
+This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md
new file mode 100644
index 00000000..5cf0e79b
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md
@@ -0,0 +1,82 @@
+---
+title: Prevent Hydration Mismatch Without Flickering
+impact: MEDIUM
+impactDescription: avoids visual flicker and hydration errors
+tags: rendering, ssr, hydration, localStorage, flicker
+---
+
+## Prevent Hydration Mismatch Without Flickering
+
+When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
+
+**Incorrect (breaks SSR):**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ // localStorage is not available on server - throws error
+ const theme = localStorage.getItem('theme') || 'light'
+
+ return (
+ <div className={theme}>
+ {children}
+ </div>
+ )
+}
+```
+
+Server-side rendering will fail because `localStorage` is undefined.
+
+**Incorrect (visual flickering):**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ const [theme, setTheme] = useState('light')
+
+ useEffect(() => {
+ // Runs after hydration - causes visible flash
+ const stored = localStorage.getItem('theme')
+ if (stored) {
+ setTheme(stored)
+ }
+ }, [])
+
+ return (
+ <div className={theme}>
+ {children}
+ </div>
+ )
+}
+```
+
+Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
+
+**Correct (no flicker, no hydration mismatch):**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ return (
+ <>
+ <div id="theme-wrapper">
+ {children}
+ </div>
+ <script
+ dangerouslySetInnerHTML={{
+ __html: `
+ (function() {
+ try {
+ var theme = localStorage.getItem('theme') || 'light';
+ var el = document.getElementById('theme-wrapper');
+ if (el) el.className = theme;
+ } catch (e) {}
+ })();
+ `,
+ }}
+ />
+ </>
+ )
+}
+```
+
+The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
+
+This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md
new file mode 100644
index 00000000..24ba2513
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md
@@ -0,0 +1,30 @@
+---
+title: Suppress Expected Hydration Mismatches
+impact: LOW-MEDIUM
+impactDescription: avoids noisy hydration warnings for known differences
+tags: rendering, hydration, ssr, nextjs
+---
+
+## Suppress Expected Hydration Mismatches
+
+In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
+
+**Incorrect (known mismatch warnings):**
+
+```tsx
+function Timestamp() {
+ return <span>{new Date().toLocaleString()}</span>
+}
+```
+
+**Correct (suppress expected mismatch only):**
+
+```tsx
+function Timestamp() {
+ return (
+ <span suppressHydrationWarning>
+ {new Date().toLocaleString()}
+ </span>
+ )
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md b/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md
new file mode 100644
index 00000000..1290bef0
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md
@@ -0,0 +1,85 @@
+---
+title: Use React DOM Resource Hints
+impact: HIGH
+impactDescription: reduces load time for critical resources
+tags: rendering, preload, preconnect, prefetch, resource-hints
+---
+
+## Use React DOM Resource Hints
+
+**Impact: HIGH (reduces load time for critical resources)**
+
+React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
+
+- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
+- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
+- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
+- **`preloadModule(href)`**: Fetch an ES module you'll use soon
+- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
+- **`preinitModule(href)`**: Fetch and evaluate an ES module
+
+**Example (preconnect to third-party APIs):**
+
+```tsx
+import { preconnect, prefetchDNS } from 'react-dom'
+
+export default function App() {
+ prefetchDNS('https://analytics.example.com')
+ preconnect('https://api.example.com')
+
+ return <main>{/* content */}</main>
+}
+```
+
+**Example (preload critical fonts and styles):**
+
+```tsx
+import { preload, preinit } from 'react-dom'
+
+export default function RootLayout({ children }) {
+ // Preload font file
+ preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
+
+ // Fetch and apply critical stylesheet immediately
+ preinit('/styles/critical.css', { as: 'style' })
+
+ return (
+ <html>
+ <body>{children}</body>
+ </html>
+ )
+}
+```
+
+**Example (preload modules for code-split routes):**
+
+```tsx
+import { preloadModule, preinitModule } from 'react-dom'
+
+function Navigation() {
+ const preloadDashboard = () => {
+ preloadModule('/dashboard.js', { as: 'script' })
+ }
+
+ return (
+ <nav>
+ <a href="/dashboard" onMouseEnter={preloadDashboard}>
+ Dashboard
+ </a>
+ </nav>
+ )
+}
+```
+
+**When to use each:**
+
+| API | Use case |
+|-----|----------|
+| `prefetchDNS` | Third-party domains you'll connect to later |
+| `preconnect` | APIs or CDNs you'll fetch from immediately |
+| `preload` | Critical resources needed for current page |
+| `preloadModule` | JS modules for likely next navigation |
+| `preinit` | Stylesheets/scripts that must execute early |
+| `preinitModule` | ES modules that must execute early |
+
+Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md b/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md
new file mode 100644
index 00000000..ee275ed1
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md
@@ -0,0 +1,68 @@
+---
+title: Use defer or async on Script Tags
+impact: HIGH
+impactDescription: eliminates render-blocking
+tags: rendering, script, defer, async, performance
+---
+
+## Use defer or async on Script Tags
+
+**Impact: HIGH (eliminates render-blocking)**
+
+Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
+
+- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
+- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
+
+Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
+
+**Incorrect (blocks rendering):**
+
+```tsx
+export default function Document() {
+ return (
+ <html>
+ <head>
+ <script src="https://example.com/analytics.js" />
+ <script src="/scripts/utils.js" />
+ </head>
+ <body>{/* content */}</body>
+ </html>
+ )
+}
+```
+
+**Correct (non-blocking):**
+
+```tsx
+export default function Document() {
+ return (
+ <html>
+ <head>
+ {/* Independent script - use async */}
+ <script src="https://example.com/analytics.js" async />
+ {/* DOM-dependent script - use defer */}
+ <script src="/scripts/utils.js" defer />
+ </head>
+ <body>{/* content */}</body>
+ </html>
+ )
+}
+```
+
+**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
+
+```tsx
+import Script from 'next/script'
+
+export default function Page() {
+ return (
+ <>
+ <Script src="https://example.com/analytics.js" strategy="afterInteractive" />
+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />
+ </>
+ )
+}
+```
+
+Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md b/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md
new file mode 100644
index 00000000..6d771286
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md
@@ -0,0 +1,28 @@
+---
+title: Optimize SVG Precision
+impact: LOW
+impactDescription: reduces file size
+tags: rendering, svg, optimization, svgo
+---
+
+## Optimize SVG Precision
+
+Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
+
+**Incorrect (excessive precision):**
+
+```svg
+<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
+```
+
+**Correct (1 decimal place):**
+
+```svg
+<path d="M 10.3 20.8 L 30.9 40.2" />
+```
+
+**Automate with SVGO:**
+
+```bash
+npx svgo --precision=1 --multipass icon.svg
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md b/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md
new file mode 100644
index 00000000..0c1b0b98
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md
@@ -0,0 +1,75 @@
+---
+title: Use useTransition Over Manual Loading States
+impact: LOW
+impactDescription: reduces re-renders and improves code clarity
+tags: rendering, transitions, useTransition, loading, state
+---
+
+## Use useTransition Over Manual Loading States
+
+Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
+
+**Incorrect (manual loading state):**
+
+```tsx
+function SearchResults() {
+ const [query, setQuery] = useState('')
+ const [results, setResults] = useState([])
+ const [isLoading, setIsLoading] = useState(false)
+
+ const handleSearch = async (value: string) => {
+ setIsLoading(true)
+ setQuery(value)
+ const data = await fetchResults(value)
+ setResults(data)
+ setIsLoading(false)
+ }
+
+ return (
+ <>
+ <input onChange={(e) => handleSearch(e.target.value)} />
+ {isLoading && <Spinner />}
+ <ResultsList results={results} />
+ </>
+ )
+}
+```
+
+**Correct (useTransition with built-in pending state):**
+
+```tsx
+import { useTransition, useState } from 'react'
+
+function SearchResults() {
+ const [query, setQuery] = useState('')
+ const [results, setResults] = useState([])
+ const [isPending, startTransition] = useTransition()
+
+ const handleSearch = (value: string) => {
+ setQuery(value) // Update input immediately
+
+ startTransition(async () => {
+ // Fetch and update results
+ const data = await fetchResults(value)
+ setResults(data)
+ })
+ }
+
+ return (
+ <>
+ <input onChange={(e) => handleSearch(e.target.value)} />
+ {isPending && <Spinner />}
+ <ResultsList results={results} />
+ </>
+ )
+}
+```
+
+**Benefits:**
+
+- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
+- **Error resilience**: Pending state correctly resets even if the transition throws
+- **Better responsiveness**: Keeps the UI responsive during updates
+- **Interrupt handling**: New transitions automatically cancel pending ones
+
+Reference: [useTransition](https://react.dev/reference/react/useTransition)
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md b/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md
new file mode 100644
index 00000000..e867c95f
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md
@@ -0,0 +1,39 @@
+---
+title: Defer State Reads to Usage Point
+impact: MEDIUM
+impactDescription: avoids unnecessary subscriptions
+tags: rerender, searchParams, localStorage, optimization
+---
+
+## Defer State Reads to Usage Point
+
+Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
+
+**Incorrect (subscribes to all searchParams changes):**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const searchParams = useSearchParams()
+
+ const handleShare = () => {
+ const ref = searchParams.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return <button onClick={handleShare}>Share</button>
+}
+```
+
+**Correct (reads on demand, no subscription):**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const handleShare = () => {
+ const params = new URLSearchParams(window.location.search)
+ const ref = params.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return <button onClick={handleShare}>Share</button>
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md
new file mode 100644
index 00000000..47a4d926
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md
@@ -0,0 +1,45 @@
+---
+title: Narrow Effect Dependencies
+impact: LOW
+impactDescription: minimizes effect re-runs
+tags: rerender, useEffect, dependencies, optimization
+---
+
+## Narrow Effect Dependencies
+
+Specify primitive dependencies instead of objects to minimize effect re-runs.
+
+**Incorrect (re-runs on any user field change):**
+
+```tsx
+useEffect(() => {
+ console.log(user.id)
+}, [user])
+```
+
+**Correct (re-runs only when id changes):**
+
+```tsx
+useEffect(() => {
+ console.log(user.id)
+}, [user.id])
+```
+
+**For derived state, compute outside effect:**
+
+```tsx
+// Incorrect: runs on width=767, 766, 765...
+useEffect(() => {
+ if (width < 768) {
+ enableMobileMode()
+ }
+}, [width])
+
+// Correct: runs only on boolean transition
+const isMobile = width < 768
+useEffect(() => {
+ if (isMobile) {
+ enableMobileMode()
+ }
+}, [isMobile])
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md
new file mode 100644
index 00000000..3d9fe405
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md
@@ -0,0 +1,40 @@
+---
+title: Calculate Derived State During Rendering
+impact: MEDIUM
+impactDescription: avoids redundant renders and state drift
+tags: rerender, derived-state, useEffect, state
+---
+
+## Calculate Derived State During Rendering
+
+If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
+
+**Incorrect (redundant state and effect):**
+
+```tsx
+function Form() {
+ const [firstName, setFirstName] = useState('First')
+ const [lastName, setLastName] = useState('Last')
+ const [fullName, setFullName] = useState('')
+
+ useEffect(() => {
+ setFullName(firstName + ' ' + lastName)
+ }, [firstName, lastName])
+
+ return <p>{fullName}</p>
+}
+```
+
+**Correct (derive during render):**
+
+```tsx
+function Form() {
+ const [firstName, setFirstName] = useState('First')
+ const [lastName, setLastName] = useState('Last')
+ const fullName = firstName + ' ' + lastName
+
+ return <p>{fullName}</p>
+}
+```
+
+References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md
new file mode 100644
index 00000000..e5c899f6
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md
@@ -0,0 +1,29 @@
+---
+title: Subscribe to Derived State
+impact: MEDIUM
+impactDescription: reduces re-render frequency
+tags: rerender, derived-state, media-query, optimization
+---
+
+## Subscribe to Derived State
+
+Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
+
+**Incorrect (re-renders on every pixel change):**
+
+```tsx
+function Sidebar() {
+ const width = useWindowWidth() // updates continuously
+ const isMobile = width < 768
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
+}
+```
+
+**Correct (re-renders only when boolean changes):**
+
+```tsx
+function Sidebar() {
+ const isMobile = useMediaQuery('(max-width: 767px)')
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md b/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md
new file mode 100644
index 00000000..b004ef45
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md
@@ -0,0 +1,74 @@
+---
+title: Use Functional setState Updates
+impact: MEDIUM
+impactDescription: prevents stale closures and unnecessary callback recreations
+tags: react, hooks, useState, useCallback, callbacks, closures
+---
+
+## Use Functional setState Updates
+
+When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
+
+**Incorrect (requires state as dependency):**
+
+```tsx
+function TodoList() {
+ const [items, setItems] = useState(initialItems)
+
+ // Callback must depend on items, recreated on every items change
+ const addItems = useCallback((newItems: Item[]) => {
+ setItems([...items, ...newItems])
+ }, [items]) // ❌ items dependency causes recreations
+
+ // Risk of stale closure if dependency is forgotten
+ const removeItem = useCallback((id: string) => {
+ setItems(items.filter(item => item.id !== id))
+ }, []) // ❌ Missing items dependency - will use stale items!
+
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
+}
+```
+
+The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
+
+**Correct (stable callbacks, no stale closures):**
+
+```tsx
+function TodoList() {
+ const [items, setItems] = useState(initialItems)
+
+ // Stable callback, never recreated
+ const addItems = useCallback((newItems: Item[]) => {
+ setItems(curr => [...curr, ...newItems])
+ }, []) // ✅ No dependencies needed
+
+ // Always uses latest state, no stale closure risk
+ const removeItem = useCallback((id: string) => {
+ setItems(curr => curr.filter(item => item.id !== id))
+ }, []) // ✅ Safe and stable
+
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
+}
+```
+
+**Benefits:**
+
+1. **Stable callback references** - Callbacks don't need to be recreated when state changes
+2. **No stale closures** - Always operates on the latest state value
+3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
+4. **Prevents bugs** - Eliminates the most common source of React closure bugs
+
+**When to use functional updates:**
+
+- Any setState that depends on the current state value
+- Inside useCallback/useMemo when state is needed
+- Event handlers that reference state
+- Async operations that update state
+
+**When direct updates are fine:**
+
+- Setting state to a static value: `setCount(0)`
+- Setting state from props/arguments only: `setName(newName)`
+- State doesn't depend on previous value
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md b/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md
new file mode 100644
index 00000000..4ecb350f
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md
@@ -0,0 +1,58 @@
+---
+title: Use Lazy State Initialization
+impact: MEDIUM
+impactDescription: wasted computation on every render
+tags: react, hooks, useState, performance, initialization
+---
+
+## Use Lazy State Initialization
+
+Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
+
+**Incorrect (runs on every render):**
+
+```tsx
+function FilteredList({ items }: { items: Item[] }) {
+ // buildSearchIndex() runs on EVERY render, even after initialization
+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
+ const [query, setQuery] = useState('')
+
+ // When query changes, buildSearchIndex runs again unnecessarily
+ return <SearchResults index={searchIndex} query={query} />
+}
+
+function UserProfile() {
+ // JSON.parse runs on every render
+ const [settings, setSettings] = useState(
+ JSON.parse(localStorage.getItem('settings') || '{}')
+ )
+
+ return <SettingsForm settings={settings} onChange={setSettings} />
+}
+```
+
+**Correct (runs only once):**
+
+```tsx
+function FilteredList({ items }: { items: Item[] }) {
+ // buildSearchIndex() runs ONLY on initial render
+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
+ const [query, setQuery] = useState('')
+
+ return <SearchResults index={searchIndex} query={query} />
+}
+
+function UserProfile() {
+ // JSON.parse runs only on initial render
+ const [settings, setSettings] = useState(() => {
+ const stored = localStorage.getItem('settings')
+ return stored ? JSON.parse(stored) : {}
+ })
+
+ return <SettingsForm settings={settings} onChange={setSettings} />
+}
+```
+
+Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
+
+For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md b/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md
new file mode 100644
index 00000000..63570491
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md
@@ -0,0 +1,38 @@
+---
+
+title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
+impact: MEDIUM
+impactDescription: restores memoization by using a constant for default value
+tags: rerender, memo, optimization
+
+---
+
+## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
+
+When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
+
+To address this issue, extract the default value into a constant.
+
+**Incorrect (`onClick` has different values on every rerender):**
+
+```tsx
+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
+ // ...
+})
+
+// Used without optional onClick
+<UserAvatar />
+```
+
+**Correct (stable default value):**
+
+```tsx
+const NOOP = () => {};
+
+const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
+ // ...
+})
+
+// Used without optional onClick
+<UserAvatar />
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md b/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md
new file mode 100644
index 00000000..f8982ab6
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md
@@ -0,0 +1,44 @@
+---
+title: Extract to Memoized Components
+impact: MEDIUM
+impactDescription: enables early returns
+tags: rerender, memo, useMemo, optimization
+---
+
+## Extract to Memoized Components
+
+Extract expensive work into memoized components to enable early returns before computation.
+
+**Incorrect (computes avatar even when loading):**
+
+```tsx
+function Profile({ user, loading }: Props) {
+ const avatar = useMemo(() => {
+ const id = computeAvatarId(user)
+ return <Avatar id={id} />
+ }, [user])
+
+ if (loading) return <Skeleton />
+ return <div>{avatar}</div>
+}
+```
+
+**Correct (skips computation when loading):**
+
+```tsx
+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
+ const id = useMemo(() => computeAvatarId(user), [user])
+ return <Avatar id={id} />
+})
+
+function Profile({ user, loading }: Props) {
+ if (loading) return <Skeleton />
+ return (
+ <div>
+ <UserAvatar user={user} />
+ </div>
+ )
+}
+```
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md b/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md
new file mode 100644
index 00000000..dd58a1af
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md
@@ -0,0 +1,45 @@
+---
+title: Put Interaction Logic in Event Handlers
+impact: MEDIUM
+impactDescription: avoids effect re-runs and duplicate side effects
+tags: rerender, useEffect, events, side-effects, dependencies
+---
+
+## Put Interaction Logic in Event Handlers
+
+If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
+
+**Incorrect (event modeled as state + effect):**
+
+```tsx
+function Form() {
+ const [submitted, setSubmitted] = useState(false)
+ const theme = useContext(ThemeContext)
+
+ useEffect(() => {
+ if (submitted) {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+ }, [submitted, theme])
+
+ return <button onClick={() => setSubmitted(true)}>Submit</button>
+}
+```
+
+**Correct (do it in the handler):**
+
+```tsx
+function Form() {
+ const theme = useContext(ThemeContext)
+
+ function handleSubmit() {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+
+ return <button onClick={handleSubmit}>Submit</button>
+}
+```
+
+Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md b/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md
new file mode 100644
index 00000000..d97592ac
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md
@@ -0,0 +1,82 @@
+---
+title: Don't Define Components Inside Components
+impact: HIGH
+impactDescription: prevents remount on every render
+tags: rerender, components, remount, performance
+---
+
+## Don't Define Components Inside Components
+
+**Impact: HIGH (prevents remount on every render)**
+
+Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
+
+A common reason developers do this is to access parent variables without passing props. Always pass props instead.
+
+**Incorrect (remounts on every render):**
+
+```tsx
+function UserProfile({ user, theme }) {
+ // Defined inside to access `theme` - BAD
+ const Avatar = () => (
+ <img
+ src={user.avatarUrl}
+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
+ />
+ )
+
+ // Defined inside to access `user` - BAD
+ const Stats = () => (
+ <div>
+ <span>{user.followers} followers</span>
+ <span>{user.posts} posts</span>
+ </div>
+ )
+
+ return (
+ <div>
+ <Avatar />
+ <Stats />
+ </div>
+ )
+}
+```
+
+Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
+
+**Correct (pass props instead):**
+
+```tsx
+function Avatar({ src, theme }: { src: string; theme: string }) {
+ return (
+ <img
+ src={src}
+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
+ />
+ )
+}
+
+function Stats({ followers, posts }: { followers: number; posts: number }) {
+ return (
+ <div>
+ <span>{followers} followers</span>
+ <span>{posts} posts</span>
+ </div>
+ )
+}
+
+function UserProfile({ user, theme }) {
+ return (
+ <div>
+ <Avatar src={user.avatarUrl} theme={theme} />
+ <Stats followers={user.followers} posts={user.posts} />
+ </div>
+ )
+}
+```
+
+**Symptoms of this bug:**
+- Input fields lose focus on every keystroke
+- Animations restart unexpectedly
+- `useEffect` cleanup/setup runs on every parent render
+- Scroll position resets inside the component
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md b/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md
new file mode 100644
index 00000000..59dfab0f
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md
@@ -0,0 +1,35 @@
+---
+title: Do not wrap a simple expression with a primitive result type in useMemo
+impact: LOW-MEDIUM
+impactDescription: wasted computation on every render
+tags: rerender, useMemo, optimization
+---
+
+## Do not wrap a simple expression with a primitive result type in useMemo
+
+When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
+Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
+
+**Incorrect:**
+
+```tsx
+function Header({ user, notifications }: Props) {
+ const isLoading = useMemo(() => {
+ return user.isLoading || notifications.isLoading
+ }, [user.isLoading, notifications.isLoading])
+
+ if (isLoading) return <Skeleton />
+ // return some markup
+}
+```
+
+**Correct:**
+
+```tsx
+function Header({ user, notifications }: Props) {
+ const isLoading = user.isLoading || notifications.isLoading
+
+ if (isLoading) return <Skeleton />
+ // return some markup
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md b/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md
new file mode 100644
index 00000000..89d80564
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md
@@ -0,0 +1,64 @@
+---
+title: Split Combined Hook Computations
+impact: MEDIUM
+impactDescription: avoids recomputing independent steps
+tags: rerender, useMemo, useEffect, dependencies, optimization
+---
+
+## Split Combined Hook Computations
+
+When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
+
+**Incorrect (changing `sortOrder` recomputes filtering):**
+
+```tsx
+const sortedProducts = useMemo(() => {
+ const filtered = products.filter((p) => p.category === category)
+ const sorted = filtered.toSorted((a, b) =>
+ sortOrder === "asc" ? a.price - b.price : b.price - a.price
+ )
+ return sorted
+}, [products, category, sortOrder])
+```
+
+**Correct (filtering only recomputes when products or category change):**
+
+```tsx
+const filteredProducts = useMemo(
+ () => products.filter((p) => p.category === category),
+ [products, category]
+)
+
+const sortedProducts = useMemo(
+ () =>
+ filteredProducts.toSorted((a, b) =>
+ sortOrder === "asc" ? a.price - b.price : b.price - a.price
+ ),
+ [filteredProducts, sortOrder]
+)
+```
+
+This pattern also applies to `useEffect` when combining unrelated side effects:
+
+**Incorrect (both effects run when either dependency changes):**
+
+```tsx
+useEffect(() => {
+ analytics.trackPageView(pathname)
+ document.title = `${pageTitle} | My App`
+}, [pathname, pageTitle])
+```
+
+**Correct (effects run independently):**
+
+```tsx
+useEffect(() => {
+ analytics.trackPageView(pathname)
+}, [pathname])
+
+useEffect(() => {
+ document.title = `${pageTitle} | My App`
+}, [pageTitle])
+```
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md b/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md
new file mode 100644
index 00000000..d99f43f7
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md
@@ -0,0 +1,40 @@
+---
+title: Use Transitions for Non-Urgent Updates
+impact: MEDIUM
+impactDescription: maintains UI responsiveness
+tags: rerender, transitions, startTransition, performance
+---
+
+## Use Transitions for Non-Urgent Updates
+
+Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
+
+**Incorrect (blocks UI on every scroll):**
+
+```tsx
+function ScrollTracker() {
+ const [scrollY, setScrollY] = useState(0)
+ useEffect(() => {
+ const handler = () => setScrollY(window.scrollY)
+ window.addEventListener('scroll', handler, { passive: true })
+ return () => window.removeEventListener('scroll', handler)
+ }, [])
+}
+```
+
+**Correct (non-blocking updates):**
+
+```tsx
+import { startTransition } from 'react'
+
+function ScrollTracker() {
+ const [scrollY, setScrollY] = useState(0)
+ useEffect(() => {
+ const handler = () => {
+ startTransition(() => setScrollY(window.scrollY))
+ }
+ window.addEventListener('scroll', handler, { passive: true })
+ return () => window.removeEventListener('scroll', handler)
+ }, [])
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md b/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md
new file mode 100644
index 00000000..619c04b0
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md
@@ -0,0 +1,59 @@
+---
+title: Use useDeferredValue for Expensive Derived Renders
+impact: MEDIUM
+impactDescription: keeps input responsive during heavy computation
+tags: rerender, useDeferredValue, optimization, concurrent
+---
+
+## Use useDeferredValue for Expensive Derived Renders
+
+When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
+
+**Incorrect (input feels laggy while filtering):**
+
+```tsx
+function Search({ items }: { items: Item[] }) {
+ const [query, setQuery] = useState('')
+ const filtered = items.filter(item => fuzzyMatch(item, query))
+
+ return (
+ <>
+ <input value={query} onChange={e => setQuery(e.target.value)} />
+ <ResultsList results={filtered} />
+ </>
+ )
+}
+```
+
+**Correct (input stays snappy, results render when ready):**
+
+```tsx
+function Search({ items }: { items: Item[] }) {
+ const [query, setQuery] = useState('')
+ const deferredQuery = useDeferredValue(query)
+ const filtered = useMemo(
+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),
+ [items, deferredQuery]
+ )
+ const isStale = query !== deferredQuery
+
+ return (
+ <>
+ <input value={query} onChange={e => setQuery(e.target.value)} />
+ <div style={{ opacity: isStale ? 0.7 : 1 }}>
+ <ResultsList results={filtered} />
+ </div>
+ </>
+ )
+}
+```
+
+**When to use:**
+
+- Filtering/searching large lists
+- Expensive visualizations (charts, graphs) reacting to input
+- Any derived state that causes noticeable render delays
+
+**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
+
+Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)
diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md b/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md
new file mode 100644
index 00000000..cf04b81f
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md
@@ -0,0 +1,73 @@
+---
+title: Use useRef for Transient Values
+impact: MEDIUM
+impactDescription: avoids unnecessary re-renders on frequent updates
+tags: rerender, useref, state, performance
+---
+
+## Use useRef for Transient Values
+
+When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
+
+**Incorrect (renders every update):**
+
+```tsx
+function Tracker() {
+ const [lastX, setLastX] = useState(0)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => setLastX(e.clientX)
+ window.addEventListener('mousemove', onMove)
+ return () => window.removeEventListener('mousemove', onMove)
+ }, [])
+
+ return (
+ <div
+ style={{
+ position: 'fixed',
+ top: 0,
+ left: lastX,
+ width: 8,
+ height: 8,
+ background: 'black',
+ }}
+ />
+ )
+}
+```
+
+**Correct (no re-render for tracking):**
+
+```tsx
+function Tracker() {
+ const lastXRef = useRef(0)
+ const dotRef = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => {
+ lastXRef.current = e.clientX
+ const node = dotRef.current
+ if (node) {
+ node.style.transform = `translateX(${e.clientX}px)`
+ }
+ }
+ window.addEventListener('mousemove', onMove)
+ return () => window.removeEventListener('mousemove', onMove)
+ }, [])
+
+ return (
+ <div
+ ref={dotRef}
+ style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ width: 8,
+ height: 8,
+ background: 'black',
+ transform: 'translateX(0px)',
+ }}
+ />
+ )
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md b/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md
new file mode 100644
index 00000000..e8f5b260
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md
@@ -0,0 +1,73 @@
+---
+title: Use after() for Non-Blocking Operations
+impact: MEDIUM
+impactDescription: faster response times
+tags: server, async, logging, analytics, side-effects
+---
+
+## Use after() for Non-Blocking Operations
+
+Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
+
+**Incorrect (blocks response):**
+
+```tsx
+import { logUserAction } from '@/app/utils'
+
+export async function POST(request: Request) {
+ // Perform mutation
+ await updateDatabase(request)
+
+ // Logging blocks the response
+ const userAgent = request.headers.get('user-agent') || 'unknown'
+ await logUserAction({ userAgent })
+
+ return new Response(JSON.stringify({ status: 'success' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' }
+ })
+}
+```
+
+**Correct (non-blocking):**
+
+```tsx
+import { after } from 'next/server'
+import { headers, cookies } from 'next/headers'
+import { logUserAction } from '@/app/utils'
+
+export async function POST(request: Request) {
+ // Perform mutation
+ await updateDatabase(request)
+
+ // Log after response is sent
+ after(async () => {
+ const userAgent = (await headers()).get('user-agent') || 'unknown'
+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
+
+ logUserAction({ sessionCookie, userAgent })
+ })
+
+ return new Response(JSON.stringify({ status: 'success' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' }
+ })
+}
+```
+
+The response is sent immediately while logging happens in the background.
+
+**Common use cases:**
+
+- Analytics tracking
+- Audit logging
+- Sending notifications
+- Cache invalidation
+- Cleanup tasks
+
+**Important notes:**
+
+- `after()` runs even if the response fails or redirects
+- Works in Server Actions, Route Handlers, and Server Components
+
+Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md b/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md
new file mode 100644
index 00000000..ee82c044
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md
@@ -0,0 +1,96 @@
+---
+title: Authenticate Server Actions Like API Routes
+impact: CRITICAL
+impactDescription: prevents unauthorized access to server mutations
+tags: server, server-actions, authentication, security, authorization
+---
+
+## Authenticate Server Actions Like API Routes
+
+**Impact: CRITICAL (prevents unauthorized access to server mutations)**
+
+Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
+
+Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
+
+**Incorrect (no authentication check):**
+
+```typescript
+'use server'
+
+export async function deleteUser(userId: string) {
+ // Anyone can call this! No auth check
+ await db.user.delete({ where: { id: userId } })
+ return { success: true }
+}
+```
+
+**Correct (authentication inside the action):**
+
+```typescript
+'use server'
+
+import { verifySession } from '@/lib/auth'
+import { unauthorized } from '@/lib/errors'
+
+export async function deleteUser(userId: string) {
+ // Always check auth inside the action
+ const session = await verifySession()
+
+ if (!session) {
+ throw unauthorized('Must be logged in')
+ }
+
+ // Check authorization too
+ if (session.user.role !== 'admin' && session.user.id !== userId) {
+ throw unauthorized('Cannot delete other users')
+ }
+
+ await db.user.delete({ where: { id: userId } })
+ return { success: true }
+}
+```
+
+**With input validation:**
+
+```typescript
+'use server'
+
+import { verifySession } from '@/lib/auth'
+import { z } from 'zod'
+
+const updateProfileSchema = z.object({
+ userId: z.string().uuid(),
+ name: z.string().min(1).max(100),
+ email: z.string().email()
+})
+
+export async function updateProfile(data: unknown) {
+ // Validate input first
+ const validated = updateProfileSchema.parse(data)
+
+ // Then authenticate
+ const session = await verifySession()
+ if (!session) {
+ throw new Error('Unauthorized')
+ }
+
+ // Then authorize
+ if (session.user.id !== validated.userId) {
+ throw new Error('Can only update own profile')
+ }
+
+ // Finally perform the mutation
+ await db.user.update({
+ where: { id: validated.userId },
+ data: {
+ name: validated.name,
+ email: validated.email
+ }
+ })
+
+ return { success: true }
+}
+```
+
+Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md
new file mode 100644
index 00000000..ef6938aa
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md
@@ -0,0 +1,41 @@
+---
+title: Cross-Request LRU Caching
+impact: HIGH
+impactDescription: caches across requests
+tags: server, cache, lru, cross-request
+---
+
+## Cross-Request LRU Caching
+
+`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
+
+**Implementation:**
+
+```typescript
+import { LRUCache } from 'lru-cache'
+
+const cache = new LRUCache<string, any>({
+ max: 1000,
+ ttl: 5 * 60 * 1000 // 5 minutes
+})
+
+export async function getUser(id: string) {
+ const cached = cache.get(id)
+ if (cached) return cached
+
+ const user = await db.user.findUnique({ where: { id } })
+ cache.set(id, user)
+ return user
+}
+
+// Request 1: DB query, result cached
+// Request 2: cache hit, no DB query
+```
+
+Use when sequential user actions hit multiple endpoints needing the same data within seconds.
+
+**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
+
+**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
+
+Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md
new file mode 100644
index 00000000..87c9ca33
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md
@@ -0,0 +1,76 @@
+---
+title: Per-Request Deduplication with React.cache()
+impact: MEDIUM
+impactDescription: deduplicates within request
+tags: server, cache, react-cache, deduplication
+---
+
+## Per-Request Deduplication with React.cache()
+
+Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
+
+**Usage:**
+
+```typescript
+import { cache } from 'react'
+
+export const getCurrentUser = cache(async () => {
+ const session = await auth()
+ if (!session?.user?.id) return null
+ return await db.user.findUnique({
+ where: { id: session.user.id }
+ })
+})
+```
+
+Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
+
+**Avoid inline objects as arguments:**
+
+`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
+
+**Incorrect (always cache miss):**
+
+```typescript
+const getUser = cache(async (params: { uid: number }) => {
+ return await db.user.findUnique({ where: { id: params.uid } })
+})
+
+// Each call creates new object, never hits cache
+getUser({ uid: 1 })
+getUser({ uid: 1 }) // Cache miss, runs query again
+```
+
+**Correct (cache hit):**
+
+```typescript
+const getUser = cache(async (uid: number) => {
+ return await db.user.findUnique({ where: { id: uid } })
+})
+
+// Primitive args use value equality
+getUser(1)
+getUser(1) // Cache hit, returns cached result
+```
+
+If you must pass objects, pass the same reference:
+
+```typescript
+const params = { uid: 1 }
+getUser(params) // Query runs
+getUser(params) // Cache hit (same reference)
+```
+
+**Next.js-Specific Note:**
+
+In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
+
+- Database queries (Prisma, Drizzle, etc.)
+- Heavy computations
+- Authentication checks
+- File system operations
+- Any non-fetch async work
+
+Use `React.cache()` to deduplicate these operations across your component tree.
+
+Reference: [React.cache documentation](https://react.dev/reference/react/cache)
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md b/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md
new file mode 100644
index 00000000..fb24a256
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md
@@ -0,0 +1,65 @@
+---
+title: Avoid Duplicate Serialization in RSC Props
+impact: LOW
+impactDescription: reduces network payload by avoiding duplicate serialization
+tags: server, rsc, serialization, props, client-components
+---
+
+## Avoid Duplicate Serialization in RSC Props
+
+**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
+
+RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
+
+**Incorrect (duplicates array):**
+
+```tsx
+// RSC: sends 6 strings (2 arrays × 3 items)
+<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
+```
+
+**Correct (sends 3 strings):**
+
+```tsx
+// RSC: send once
+<ClientList usernames={usernames} />
+
+// Client: transform there
+'use client'
+const sorted = useMemo(() => [...usernames].sort(), [usernames])
+```
+
+**Nested deduplication behavior:**
+
+Deduplication works recursively. Impact varies by data type:
+
+- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
+- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
+
+```tsx
+// string[] - duplicates everything
+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
+
+// object[] - duplicates array structure only
+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
+```
+
+**Operations breaking deduplication (create new references):**
+
+- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
+- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
+
+**More examples:**
+
+```tsx
+// ❌ Bad
+<C users={users} active={users.filter(u => u.active)} />
+<C product={product} productName={product.name} />
+
+// ✅ Good
+<C users={users} />
+<C product={product} />
+// Do filtering/destructuring in client
+```
+
+**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md b/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md
new file mode 100644
index 00000000..25205c2f
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md
@@ -0,0 +1,149 @@
+---
+title: Hoist Static I/O to Module Level
+impact: HIGH
+impactDescription: avoids repeated file/network I/O per request
+tags: server, io, performance, next.js, route-handlers, og-image
+---
+
+## Hoist Static I/O to Module Level
+
+**Impact: HIGH (avoids repeated file/network I/O per request)**
+
+When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
+
+**Incorrect (reads font file on every request):**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+
+export async function GET(request: Request) {
+ // Runs on EVERY request - expensive!
+ const fontData = await fetch(
+ new URL('./fonts/Inter.ttf', import.meta.url)
+ ).then(res => res.arrayBuffer())
+
+ const logoData = await fetch(
+ new URL('./images/logo.png', import.meta.url)
+ ).then(res => res.arrayBuffer())
+
+ return new ImageResponse(
+ <div style={{ fontFamily: 'Inter' }}>
+ <img src={logoData} />
+ Hello World
+ </div>,
+ { fonts: [{ name: 'Inter', data: fontData }] }
+ )
+}
+```
+
+**Correct (loads once at module initialization):**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+
+// Module-level: runs ONCE when module is first imported
+const fontData = fetch(
+ new URL('./fonts/Inter.ttf', import.meta.url)
+).then(res => res.arrayBuffer())
+
+const logoData = fetch(
+ new URL('./images/logo.png', import.meta.url)
+).then(res => res.arrayBuffer())
+
+export async function GET(request: Request) {
+ // Await the already-started promises
+ const [font, logo] = await Promise.all([fontData, logoData])
+
+ return new ImageResponse(
+ <div style={{ fontFamily: 'Inter' }}>
+ <img src={logo} />
+ Hello World
+ </div>,
+ { fonts: [{ name: 'Inter', data: font }] }
+ )
+}
+```
+
+**Correct (synchronous fs at module level):**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+import { readFileSync } from 'fs'
+import { join } from 'path'
+
+// Synchronous read at module level - blocks only during module init
+const fontData = readFileSync(
+ join(process.cwd(), 'public/fonts/Inter.ttf')
+)
+
+const logoData = readFileSync(
+ join(process.cwd(), 'public/images/logo.png')
+)
+
+export async function GET(request: Request) {
+ return new ImageResponse(
+ <div style={{ fontFamily: 'Inter' }}>
+ <img src={logoData} />
+ Hello World
+ </div>,
+ { fonts: [{ name: 'Inter', data: fontData }] }
+ )
+}
+```
+
+**Incorrect (reads config on every call):**
+
+```typescript
+import fs from 'node:fs/promises'
+
+export async function processRequest(data: Data) {
+ const config = JSON.parse(
+ await fs.readFile('./config.json', 'utf-8')
+ )
+ const template = await fs.readFile('./template.html', 'utf-8')
+
+ return render(template, data, config)
+}
+```
+
+**Correct (hoists config and template to module level):**
+
+```typescript
+import fs from 'node:fs/promises'
+
+const configPromise = fs
+ .readFile('./config.json', 'utf-8')
+ .then(JSON.parse)
+const templatePromise = fs.readFile('./template.html', 'utf-8')
+
+export async function processRequest(data: Data) {
+ const [config, template] = await Promise.all([
+ configPromise,
+ templatePromise,
+ ])
+
+ return render(template, data, config)
+}
+```
+
+When to use this pattern:
+
+- Loading fonts for OG image generation
+- Loading static logos, icons, or watermarks
+- Reading configuration files that don't change at runtime
+- Loading email templates or other static templates
+- Any static asset that's the same across all requests
+
+When not to use this pattern:
+
+- Assets that vary per request or user
+- Files that may change during runtime (use caching with TTL instead)
+- Large files that would consume too much memory if kept loaded
+- Sensitive data that shouldn't persist in memory
+
+With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
+
+In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md b/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md
new file mode 100644
index 00000000..ff7d9f29
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md
@@ -0,0 +1,50 @@
+---
+title: Avoid Shared Module State for Request Data
+impact: HIGH
+impactDescription: prevents concurrency bugs and request data leaks
+tags: server, rsc, ssr, concurrency, security, state
+---
+
+## Avoid Shared Module State for Request Data
+
+For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.
+
+Treat module scope on the server as process-wide shared memory, not request-local state.
+
+**Incorrect (request data leaks across concurrent renders):**
+
+```tsx
+let currentUser: User | null = null
+
+export default async function Page() {
+ currentUser = await auth()
+ return <Dashboard />
+}
+
+async function Dashboard() {
+ return <div>{currentUser?.name}</div>
+}
+```
+
+If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.
+
+**Correct (keep request data local to the render tree):**
+
+```tsx
+export default async function Page() {
+ const user = await auth()
+ return <Dashboard user={user} />
+}
+
+function Dashboard({ user }: { user: User | null }) {
+ return <div>{user?.name}</div>
+}
+```
+
+Safe exceptions:
+
+- Immutable static assets or config loaded once at module scope
+- Shared caches intentionally designed for cross-request reuse and keyed correctly
+- Process-wide singletons that do not store request- or user-specific mutable data
+
+For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md b/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md
new file mode 100644
index 00000000..1affc835
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md
@@ -0,0 +1,83 @@
+---
+title: Parallel Data Fetching with Component Composition
+impact: CRITICAL
+impactDescription: eliminates server-side waterfalls
+tags: server, rsc, parallel-fetching, composition
+---
+
+## Parallel Data Fetching with Component Composition
+
+React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
+
+**Incorrect (Sidebar waits for Page's fetch to complete):**
+
+```tsx
+export default async function Page() {
+ const header = await fetchHeader()
+ return (
+ <div>
+ <div>{header}</div>
+ <Sidebar />
+ </div>
+ )
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return <nav>{items.map(renderItem)}</nav>
+}
+```
+
+**Correct (both fetch simultaneously):**
+
+```tsx
+async function Header() {
+ const data = await fetchHeader()
+ return <div>{data}</div>
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return <nav>{items.map(renderItem)}</nav>
+}
+
+export default function Page() {
+ return (
+ <div>
+ <Header />
+ <Sidebar />
+ </div>
+ )
+}
+```
+
+**Alternative with children prop:**
+
+```tsx
+async function Header() {
+ const data = await fetchHeader()
+ return <div>{data}</div>
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return <nav>{items.map(renderItem)}</nav>
+}
+
+function Layout({ children }: { children: ReactNode }) {
+ return (
+ <div>
+ <Header />
+ {children}
+ </div>
+ )
+}
+
+export default function Page() {
+ return (
+ <Layout>
+ <Sidebar />
+ </Layout>
+ )
+}
+```
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md b/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md
new file mode 100644
index 00000000..be1dc250
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md
@@ -0,0 +1,34 @@
+---
+title: Parallel Nested Data Fetching
+impact: CRITICAL
+impactDescription: eliminates server-side waterfalls
+tags: server, rsc, parallel-fetching, promise-chaining
+---
+
+## Parallel Nested Data Fetching
+
+When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.
+
+**Incorrect (a single slow item blocks all nested fetches):**
+
+```tsx
+const chats = await Promise.all(
+ chatIds.map(id => getChat(id))
+)
+
+const chatAuthors = await Promise.all(
+ chats.map(chat => getUser(chat.author))
+)
+```
+
+If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.
+
+**Correct (each item chains its own nested fetch):**
+
+```tsx
+const chatAuthors = await Promise.all(
+ chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
+)
+```
+
+Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.
diff --git a/.agents/skills/vercel-react-best-practices/rules/server-serialization.md b/.agents/skills/vercel-react-best-practices/rules/server-serialization.md
new file mode 100644
index 00000000..39c5c416
--- /dev/null
+++ b/.agents/skills/vercel-react-best-practices/rules/server-serialization.md
@@ -0,0 +1,38 @@
+---
+title: Minimize Serialization at RSC Boundaries
+impact: HIGH
+impactDescription: reduces data transfer size
+tags: server, rsc, serialization, props
+---
+
+## Minimize Serialization at RSC Boundaries
+
+The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
+
+**Incorrect (serializes all 50 fields):**
+
+```tsx
+async function Page() {
+ const user = await fetchUser() // 50 fields
+ return <Profile user={user} />
+}
+
+'use client'
+function Profile({ user }: { user: User }) {
+ return <div>{user.name}</div> // uses 1 field
+}
+```
+
+**Correct (serializes only 1 field):**
+
+```tsx
+async function Page() {
+ const user = await fetchUser()
+ return <Profile name={user.name} />
+}
+
+'use client'
+function Profile({ name }: { name: string }) {
+ return <div>{name}</div>
+}
+```
diff --git a/.agents/skills/web-design-guidelines/SKILL.md b/.agents/skills/web-design-guidelines/SKILL.md
new file mode 100644
index 00000000..ceae92ab
--- /dev/null
+++ b/.agents/skills/web-design-guidelines/SKILL.md
@@ -0,0 +1,39 @@
+---
+name: web-design-guidelines
+description: Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".
+metadata:
+ author: vercel
+ version: "1.0.0"
+ argument-hint: <file-or-pattern>
+---
+
+# Web Interface Guidelines
+
+Review files for compliance with Web Interface Guidelines.
+
+## How It Works
+
+1. Fetch the latest guidelines from the source URL below
+2. Read the specified files (or prompt user for files/pattern)
+3. Check against all rules in the fetched guidelines
+4. Output findings in the terse `file:line` format
+
+## Guidelines Source
+
+Fetch fresh guidelines before each review:
+
+```
+https://raw.githubusercontent.com/vercel-labs/web-interface-guidelines/main/command.md
+```
+
+Use WebFetch to retrieve the latest rules. The fetched content contains all the rules and output format instructions.
+
+## Usage
+
+When a user provides a file or pattern argument:
+1. Fetch guidelines from the source URL above
+2. Read the specified files
+3. Apply all rules from the fetched guidelines
+4. Output findings using the format specified in the guidelines
+
+If no files specified, ask the user which files to review.
diff --git a/.claude/settings.json b/.claude/settings.json
new file mode 100644
index 00000000..4bfc5569
--- /dev/null
+++ b/.claude/settings.json
@@ -0,0 +1,3 @@
+{
+ "worktree": { "bgIsolation": "none" }
+}
diff --git a/.claude/skills/better-auth-best-practices b/.claude/skills/better-auth-best-practices
new file mode 120000
index 00000000..d28d6bd7
--- /dev/null
+++ b/.claude/skills/better-auth-best-practices
@@ -0,0 +1 @@
+../../.agents/skills/better-auth-best-practices
\ No newline at end of file
diff --git a/.claude/skills/eve b/.claude/skills/eve
new file mode 120000
index 00000000..c1d54684
--- /dev/null
+++ b/.claude/skills/eve
@@ -0,0 +1 @@
+../../.agents/skills/eve
\ No newline at end of file
diff --git a/.claude/skills/nestjs-best-practices b/.claude/skills/nestjs-best-practices
new file mode 120000
index 00000000..ed0955ad
--- /dev/null
+++ b/.claude/skills/nestjs-best-practices
@@ -0,0 +1 @@
+../../.agents/skills/nestjs-best-practices
\ No newline at end of file
diff --git a/.claude/skills/no-use-effect b/.claude/skills/no-use-effect
new file mode 120000
index 00000000..7e259d03
--- /dev/null
+++ b/.claude/skills/no-use-effect
@@ -0,0 +1 @@
+../../.agents/skills/no-use-effect
\ No newline at end of file
diff --git a/.claude/skills/nuqs b/.claude/skills/nuqs
new file mode 120000
index 00000000..2e031211
--- /dev/null
+++ b/.claude/skills/nuqs
@@ -0,0 +1 @@
+../../.agents/skills/nuqs
\ No newline at end of file
diff --git a/.claude/skills/prisma-database-setup b/.claude/skills/prisma-database-setup
new file mode 120000
index 00000000..f188a790
--- /dev/null
+++ b/.claude/skills/prisma-database-setup
@@ -0,0 +1 @@
+../../.agents/skills/prisma-database-setup
\ No newline at end of file
diff --git a/.claude/skills/shadcn b/.claude/skills/shadcn
new file mode 120000
index 00000000..8d5af6f6
--- /dev/null
+++ b/.claude/skills/shadcn
@@ -0,0 +1 @@
+../../.agents/skills/shadcn
\ No newline at end of file
diff --git a/.claude/skills/skill-creator b/.claude/skills/skill-creator
new file mode 120000
index 00000000..b8745549
--- /dev/null
+++ b/.claude/skills/skill-creator
@@ -0,0 +1 @@
+../../.agents/skills/skill-creator
\ No newline at end of file
diff --git a/.claude/skills/turborepo b/.claude/skills/turborepo
new file mode 120000
index 00000000..b69a7d9e
--- /dev/null
+++ b/.claude/skills/turborepo
@@ -0,0 +1 @@
+../../.agents/skills/turborepo
\ No newline at end of file
diff --git a/.claude/skills/typescript-advanced-types b/.claude/skills/typescript-advanced-types
new file mode 120000
index 00000000..4d2e5230
--- /dev/null
+++ b/.claude/skills/typescript-advanced-types
@@ -0,0 +1 @@
+../../.agents/skills/typescript-advanced-types
\ No newline at end of file
diff --git a/.claude/skills/vercel-composition-patterns b/.claude/skills/vercel-composition-patterns
new file mode 120000
index 00000000..55a19e8f
--- /dev/null
+++ b/.claude/skills/vercel-composition-patterns
@@ -0,0 +1 @@
+../../.agents/skills/vercel-composition-patterns
\ No newline at end of file
diff --git a/.claude/skills/vercel-react-best-practices b/.claude/skills/vercel-react-best-practices
new file mode 120000
index 00000000..e567923b
--- /dev/null
+++ b/.claude/skills/vercel-react-best-practices
@@ -0,0 +1 @@
+../../.agents/skills/vercel-react-best-practices
\ No newline at end of file
diff --git a/.claude/skills/web-design-guidelines b/.claude/skills/web-design-guidelines
new file mode 120000
index 00000000..886b26de
--- /dev/null
+++ b/.claude/skills/web-design-guidelines
@@ -0,0 +1 @@
+../../.agents/skills/web-design-guidelines
\ No newline at end of file
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..2b868a9a
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,12 @@
+# Strict rules - Always review before starting any work
+
+You should always check and see if there are any relevant skill files you should review before starting a task e.g. if you're working on better-auth, always review the better auth best practice skill - if you're working on prisma, review your prisma-database-setup skill.
+
+Please check below, if you're working on anything related review the rules and let the user know you've read them:
+
+## Design
+Read @docs/design.md
+
+## API:
+Read @docs/api.md
+
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..43c994c2
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/README.md b/README.md
index 90c19607..4ba17366 100644
--- a/README.md
+++ b/README.md
@@ -1,159 +1,216 @@
-# Turborepo starter
+# CRM
-This Turborepo starter is maintained by the Turborepo core team.
+Turborepo monorepo, managed with [Bun](https://bun.com).
-## Using this example
+## What's inside
-Run the following command:
+### Apps
-```sh
-npx create-turbo@latest
-```
+- `app` — [Next.js](https://nextjs.org/) front end, port 3000
+- `api` — [NestJS](https://nestjs.com/) API, runs on Bun, port 3001
-## What's inside?
+### Packages
-This Turborepo includes the following packages/apps:
+- `@crm/auth` — [Better Auth](https://better-auth.com) configuration (server + client)
+- `@crm/db` — Prisma schema, migrations, and the shared PostgreSQL client
+- `@crm/ui` — [shadcn/ui](https://ui.shadcn.com) `radix-nova` design system, Tailwind theme, and `cn()`
+- `@crm/typescript-config` — shared `tsconfig.json` bases
-### Apps and Packages
+These packages are just-in-time: they export TypeScript sources and are compiled
+by whatever consumes them.
-- `docs`: a [Next.js](https://nextjs.org/) app
-- `web`: another [Next.js](https://nextjs.org/) app
-- `@repo/ui`: a stub React component library shared by both `web` and `docs` applications
-- `@repo/eslint-config`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
-- `@repo/typescript-config`: `tsconfig.json`s used throughout the monorepo
+### UI
-Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
+`@crm/ui` owns the component library and the single Tailwind entry point. Apps
+import the stylesheet once and pull components from subpath exports:
-### Utilities
+```tsx
+import "@crm/ui/globals.css"; // app/layout.tsx
+import { Button } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+```
-This Turborepo has some additional tools already setup for you:
+The component set, the theme and the `cds-icon` animations are shared with the
+Comp AI MVP app so the two products look like one. That means:
-- [TypeScript](https://www.typescriptlang.org/) for static type checking
-- [ESLint](https://eslint.org/) for code linting
-- [Prettier](https://prettier.io) for code formatting
+- **shadcn style `radix-nova`**, built on [Radix](https://www.radix-ui.com)
+ (plus `sonner`, `vaul`, `cmdk`, `recharts`). Components use Radix's `asChild`
+ API — not Base UI's `render` prop.
+- **[Carbon](https://carbondesignsystem.com/libraries/icons/) icons** for
+ product chrome, imported one glyph at a time and rendered through the `Icon`
+ wrapper, which attaches the hover motion defined in `globals.css`:
-### Build
+ ```tsx
+ import Dashboard from "@carbon/icons-react/es/Dashboard";
+ import { Icon } from "@crm/ui/components/icon";
-To build all apps and packages, run the following command:
+ <Icon icon={Dashboard} />;
+ ```
-With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended):
+ Lucide is still a dependency because the vendored shadcn components use it
+ internally; prefer Carbon for anything you write.
+
+Add components with the shadcn CLI from `apps/app` — the monorepo aliases in
+`components.json` route the files into `packages/ui`:
```sh
-cd my-turborepo
-turbo build
+cd apps/app
+bunx --bun shadcn@latest add <component>
```
-Without global `turbo`, use your package manager:
+Design tokens live in `packages/ui/src/styles/globals.css`; that file also
+declares the Tailwind `@source` globs. Consuming apps re-export the shared
+PostCSS config and list `@crm/ui` in `transpilePackages`.
-```sh
-cd my-turborepo
-npx turbo build
-bun dlx turbo build
-bun exec turbo build
-```
+Files under `packages/ui/src/components` are vendored from upstream and excluded
+from Biome so `shadcn add --diff <component>` stays readable when re-syncing.
-You can build a specific package by using a [filter](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters):
+### Auth
-With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed:
+Sign-in is **Google only** — this is an internal tool, so there are no
+organizations, no passwords and no invitations.
+
+The **API** owns authentication. It mounts `/api/auth/*` through
+`@thallesp/nestjs-better-auth` and is the only process that writes session
+cookies. The **app** reads those sessions straight out of Postgres via
+`@crm/auth` (no HTTP round trip) and sends the browser to the API for sign-in
+and sign-out.
-```sh
-turbo build --filter=docs
+```
+browser ──sign in──▶ api:3001/api/auth/* ──▶ Google
+ │ │
+ │ session cookie
+ ▼ ▼
+app:3000 ──cookie──▶ Postgres (@crm/db)
+ └──── fetch /auth/me, /health ────▶ api:3001
```
-Without global `turbo`:
+Both processes therefore need the **same** `BETTER_AUTH_SECRET` and
+`DATABASE_URL`. On localhost the shared cookie works because cookies ignore
+ports; on separate subdomains set `AUTH_COOKIE_DOMAIN` to the shared parent.
-```sh
-npx turbo build --filter=docs
-bun exec turbo build --filter=docs
-bun exec turbo build --filter=docs
-```
+`apps/app/proxy.ts` does an optimistic cookie check to keep anonymous traffic
+off protected routes; `requireSession()` in `apps/app/lib/session.ts` is the
+authoritative check every protected page runs.
-### Develop
+Because Google is the only door, there is no way to get a session from a
+terminal. `bun run --filter=api dev:session [email]` writes the rows Better Auth
+would have written and prints the cookie it would have set — development only,
+and it refuses to run with `NODE_ENV=production`.
-To develop all apps and packages, run the following command:
+### Data
-With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended):
+The app talks to the API over **tRPC** (`nestjs-trpc`), mounted at `/api/trpc`.
-```sh
-cd my-turborepo
-turbo dev
+```
+apps/app ──/api/trpc──▶ app/api/[...path]/route.ts ──▶ api:3001/api/trpc
+ server components: getServerTrpc() + prefetch → <HydrateClient>
+ client components: useTRPC() + TanStack Query
```
-Without global `turbo`, use your package manager:
+The catch-all route handler is a same-origin passthrough. Without it every call
+from the browser would be a cross-origin credentialed request, with the CORS and
+cookie rules that implies; with it, `/api/trpc` is local and the session cookie
+just works.
-```sh
-cd my-turborepo
-npx turbo dev
-bun exec turbo dev
-bun exec turbo dev
-```
+`apps/api` exports the generated router type as `api/app-router`, so the app is
+type-safe from the Prisma row to the table cell. It is generated, not written:
+`bun run dev` keeps `nestjs-trpc watch` running alongside the API, and
+`bun run --filter=api trpc:generate` refreshes it once. If a new procedure is
+invisible to the app, that is what has not run.
-You can develop a specific package by using a [filter](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters):
+List URLs are state: filters, sort and page live in the query string via
+[nuqs](https://nuqs.dev), parsed once per module in a `*-search-params.ts` so
+the server prefetch and the client table cannot disagree. Copying the URL
+reproduces the view.
-With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed:
+### The agent
-```sh
-turbo dev --filter=web
-```
+Company knowledge — logo, description, industry, address, socials — is filled
+in by [Context.dev](https://context.dev) rather than typed by a human.
+`apps/api/src/enrichment` holds a thin typed client, a small in-process queue
+(concurrency 2, one retry, per-domain dedupe) and the field mapping.
-Without global `turbo`:
+It runs on company create, on a domain change, and on the "Re-enrich" button;
+"Research" reads the company's site and posts a brief to its timeline. Two
+rules the mapping never breaks: it only ever **fills gaps**, so a value a rep
+typed is never overwritten by a guess, and logos are chosen by `mode`+`type`
+rather than by taking `logos[0]`.
-```sh
-npx turbo dev --filter=web
-bun exec turbo dev --filter=web
-bun exec turbo dev --filter=web
-```
+Set `CONTEXT_DEV_API_KEY` in `apps/api/.env` to switch it on. Without it the
+agent is disabled, the API logs one warning at boot, and companies simply stay
+`PENDING` — nothing else changes.
-### Remote Caching
+### Importing from HubSpot
-> [!TIP]
-> Vercel Remote Cache is free for all plans. Get started today at [vercel.com](https://vercel.com/signup?utm_source=remote-cache-sdk&utm_campaign=free_remote_cache).
+`/import` takes a HubSpot CSV export of companies, contacts or deals. It always
+dry-runs first and shows a per-row report — outcome, the record it matched, and
+why anything was skipped — before anything is written.
-Turborepo can use a technique known as [Remote Caching](https://turborepo.dev/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
+Matching is on `domain` for companies and `email` for contacts, both unique, so
+re-running an import updates rather than duplicates. A company row with no
+domain falls back to an exact name match, and the report says so. Deals match on
+name within a company, and need the companies imported first.
-By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup?utm_source=turborepo-examples), then enter the following commands:
+### Tooling
-With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended):
+- [TypeScript](https://www.typescriptlang.org/) for static type checking
+- [Biome](https://biomejs.dev/) for linting and formatting
+
+## Getting started
```sh
-cd my-turborepo
-turbo login
-```
+bun install
-Without global `turbo`, use your package manager:
+cp packages/db/.env.example packages/db/.env
+cp apps/api/.env.example apps/api/.env
+cp apps/app/.env.example apps/app/.env
-```sh
-cd my-turborepo
-npx turbo login
-bun exec turbo login
-bun exec turbo login
+openssl rand -base64 32 # -> BETTER_AUTH_SECRET, the SAME value in both .env files
+
+bun run db:generate
+bun run db:deploy # applies the migrations
+bun run dev
```
-This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
+Then create a Google OAuth client (Google Cloud console → Credentials → OAuth
+client ID → Web application), add `http://localhost:3001/api/auth/callback/google`
+as an authorised redirect URI, and put the pair in `apps/api/.env` as
+`GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`. The API refuses to boot without
+them — Google is the only way in.
-Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
+No local Postgres? `bunx prisma dev` (from `packages/db`) starts one and prints
+a `DATABASE_URL`.
-With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed:
+## Tasks
-```sh
-turbo link
-```
+| Command | What it does |
+| ---------------------- | ------------------------------------------------ |
+| `bun run dev` | Every app in watch mode |
+| `bun run build` | Build all apps and packages |
+| `bun run lint` | `biome check` in every package |
+| `bun run check-types` | `tsc --noEmit` in every package |
+| `bun run format` | Format the whole repo with Biome |
+| `bun run db:migrate` | Create and apply a Prisma migration |
+| `bun run db:studio` | Open Prisma Studio |
+| `bun run auth:generate`| Regenerate the auth models in the Prisma schema |
+| `bun run --filter=api trpc:generate` | Regenerate the `AppRouter` type the app imports |
+| `bun run --filter=api dev:session` | Print a signed session cookie for a local user |
-Without global `turbo`:
+Scoped runs use Turborepo filters:
```sh
-npx turbo link
-bun exec turbo link
-bun exec turbo link
+bun exec turbo run dev --filter=api
```
-## Useful Links
+## Environment
-Learn more about the power of Turborepo:
+`.env` files live in the package that reads them — `packages/db/.env` for
+`DATABASE_URL`, `apps/api/.env` for the API, `apps/app/.env` for the front end.
+There is no root `.env`.
-- [Tasks](https://turborepo.dev/docs/crafting-your-repository/running-tasks)
-- [Caching](https://turborepo.dev/docs/crafting-your-repository/caching)
-- [Remote Caching](https://turborepo.dev/docs/core-concepts/remote-caching)
-- [Filtering](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters)
-- [Configuration Options](https://turborepo.dev/docs/reference/configuration)
-- [CLI Usage](https://turborepo.dev/docs/reference/command-line-reference)
+`BETTER_AUTH_SECRET`, `BETTER_AUTH_URL` and `DATABASE_URL` are duplicated across
+`apps/api/.env` and `apps/app/.env` on purpose: both processes run Better Auth
+against the same database, and they must agree or the cookie one writes will not
+verify in the other.
+# crm
diff --git a/apps/api/.env.example b/apps/api/.env.example
new file mode 100644
index 00000000..bf4568d5
--- /dev/null
+++ b/apps/api/.env.example
@@ -0,0 +1,41 @@
+NODE_ENV="development"
+PORT="3001"
+
+# Same database as packages/db.
+DATABASE_URL="postgresql://postgres:postgres@localhost:5432/crm?schema=public"
+
+# openssl rand -base64 32. Must match apps/app/.env — the API mints the session
+# cookie and the Next.js app verifies it.
+BETTER_AUTH_SECRET=""
+BETTER_AUTH_URL="http://localhost:3001"
+
+# Origins allowed to call the API with credentials (the Next.js app). Also the
+# allow-list Better Auth validates post-sign-in `callbackURL`s against.
+AUTH_TRUSTED_ORIGINS="http://localhost:3000"
+
+# Required. Google Cloud console -> Credentials -> OAuth client ID (web).
+# Authorised redirect URI: http://localhost:3001/api/auth/callback/google
+GOOGLE_CLIENT_ID=""
+GOOGLE_CLIENT_SECRET=""
+
+# Only when the API and the app are on different subdomains, e.g. ".example.com".
+# AUTH_COOKIE_DOMAIN=""
+
+# Optional. Without it the cache is per-instance and in-memory.
+# REDIS_URL="redis://localhost:6379"
+# CACHE_TTL_MS="60000"
+
+# Log every SQL statement Prisma runs (debug level, bound parameters omitted).
+# Off by default: it buries every other log line under a wall of SELECTs.
+# Log format and level are not configurable — they follow NODE_ENV.
+# PRISMA_LOG_QUERIES="true"
+
+# Context.dev, for the company enrichment agent (https://context.dev).
+# Optional: without it the agent is disabled, a warning is logged once at boot,
+# and companies stay PENDING. Server-side only — it never reaches the browser.
+CONTEXT_DEV_API_KEY=""
+
+# Where the Context.dev SDK points. Read by the SDK itself, not by our config —
+# `test/enrichment.integration.spec.ts` uses it to drive the whole pipeline
+# against a local stub. Leave unset in normal use.
+# CONTEXT_DEV_BASE_URL="https://api.context.dev/v1"
diff --git a/apps/api/.gitignore b/apps/api/.gitignore
new file mode 100644
index 00000000..695d0a16
--- /dev/null
+++ b/apps/api/.gitignore
@@ -0,0 +1,63 @@
+# compiled output
+/dist
+/node_modules
+/build
+
+# nestjs-trpc codegen. server.ts is committed so a checkout type-checks — and
+# a deploy builds — without first running the native codegen binary; everything
+# else the generator drops in here is scratch. Refresh with
+# `bun run --filter=api trpc:generate`.
+src/generated/*
+!src/generated/server.ts
+
+# Logs
+logs
+*.log
+npm-debug.log*
+pnpm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+lerna-debug.log*
+
+# OS
+.DS_Store
+
+# Tests
+/coverage
+/.nyc_output
+
+# IDEs and editors
+/.idea
+.project
+.classpath
+.c9/
+*.launch
+.settings/
+*.sublime-workspace
+
+# IDE - VSCode
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+
+# dotenv environment variable files
+.env
+.env.development.local
+.env.test.local
+.env.production.local
+.env.local
+
+# temp directory
+.temp
+.tmp
+
+# Runtime data
+pids
+*.pid
+*.seed
+*.pid.lock
+
+# Diagnostic reports (https://nodejs.org/api/report.html)
+report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
diff --git a/apps/api/README.md b/apps/api/README.md
new file mode 100644
index 00000000..0895253b
--- /dev/null
+++ b/apps/api/README.md
@@ -0,0 +1,76 @@
+# `api`
+
+NestJS API for the CRM. Runs on Bun, backed by `@crm/db` and `@crm/auth`.
+
+## Running it
+
+```sh
+cp .env.example .env
+openssl rand -base64 32 # -> BETTER_AUTH_SECRET (same value in apps/app/.env)
+
+bun run dev # watch mode on http://localhost:3001
+bun run test
+bun run build && bun run start:prod
+```
+
+Sign-in is Google-only, so `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are
+required and the process refuses to boot without them. Register
+`http://localhost:3001/api/auth/callback/google` as an authorised redirect URI.
+
+Bun is the runtime, not just the package manager: `@crm/db` and `@crm/auth`
+ship TypeScript sources, so `tsc`/`node` cannot run this app directly. `tsc` is
+used for type checking only (`bun run check-types`).
+
+## Routes
+
+| Route | Auth | Notes |
+| ---------------- | ---------- | --------------------------------------------- |
+| `/api/auth/*` | anonymous | Mounted by `@thallesp/nestjs-better-auth` |
+| `/auth/me` | required | Cached profile of the signed-in user |
+| `/auth/session` | optional | Whether the caller is signed in |
+| `/health` | anonymous | 200 with a database round-trip, 503 otherwise |
+
+## How auth is wired
+
+This process owns authentication. It mounts `/api/auth/*` and is the only one
+that writes session cookies; the Next.js app in `apps/app` reads those sessions
+straight from Postgres via `@crm/auth` and calls the routes above with
+`credentials: "include"`.
+
+`AuthModule.forRoot({ auth })` mounts the Better Auth handler and registers a
+**global** `AuthGuard`, so every route is protected unless it opts out:
+
+```ts
+@Get('public')
+@AllowAnonymous() // no session required
+@OptionalAuth() // session optional; @Session() may be undefined
+```
+
+It also calls `enableCors({ origin: trustedOrigins, credentials: true })` for
+the whole app, which is what lets the browser at `localhost:3000` talk to it —
+`AUTH_TRUSTED_ORIGINS` is the single knob for that.
+
+`main.ts` creates the app with `bodyParser: false` — Better Auth needs the raw
+request body, and the library installs its own parsers around the auth routes.
+
+`AuthHooksService` uses `@AfterUpdate("user")` to drop a cached profile the
+moment its row changes. Database hooks require `databaseHooks: {}` in the Better
+Auth options and endpoint hooks require `hooks: {}` (both set in `@crm/auth`);
+the library throws at startup without them.
+
+## Caching
+
+`AppCacheModule` registers `@nestjs/cache-manager` globally. It uses `REDIS_URL`
+when set and otherwise falls back to a per-instance in-memory store — fine for
+local development, not for more than one API instance.
+
+`AuthService.getProfile` is the reference pattern: read through the cache, write
+with an explicit TTL, invalidate on change.
+
+## Notes
+
+- Better Auth stores rate limits in the database (`rateLimit.storage`), so every
+ request to `/api/auth/*` needs a reachable Postgres. Moving this to
+ `secondaryStorage` backed by Redis would remove that dependency.
+- Environment variables are validated at boot by `src/config/env.validation.ts`.
+ The process refuses to start on a bad config.
diff --git a/apps/api/nest-cli.json b/apps/api/nest-cli.json
new file mode 100644
index 00000000..68d1974c
--- /dev/null
+++ b/apps/api/nest-cli.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://json.schemastore.org/nest-cli",
+ "collection": "@nestjs/schematics",
+ "sourceRoot": "src"
+}
diff --git a/apps/api/package.json b/apps/api/package.json
new file mode 100644
index 00000000..f73cb5ee
--- /dev/null
+++ b/apps/api/package.json
@@ -0,0 +1,58 @@
+{
+ "name": "api",
+ "version": "0.0.1",
+ "private": true,
+ "license": "UNLICENSED",
+ "exports": {
+ "./app-router": "./src/generated/server.ts"
+ },
+ "scripts": {
+ "build": "bun build src/main.ts --target=bun --outdir dist --packages=external --sourcemap",
+ "check-types": "tsc --noEmit",
+ "dev": "concurrently -n api,trpc -c blue,magenta \"bun --watch src/main.ts\" \"nestjs-trpc watch -e src/app.module.ts -r '**/*.router.ts' -o src/generated\"",
+ "dev:session": "bun scripts/dev-session.ts",
+ "lint": "biome check .",
+ "postinstall": "node scripts/chmod-trpc-binary.mjs",
+ "start": "bun src/main.ts",
+ "start:prod": "bun dist/main.js",
+ "test": "bun test",
+ "test:watch": "bun test --watch",
+ "trpc:generate": "nestjs-trpc generate -e src/app.module.ts -r \"**/*.router.ts\" -o src/generated",
+ "clean": "rm -rf .turbo dist node_modules src/generated"
+ },
+ "dependencies": {
+ "@crm/auth": "workspace:*",
+ "@crm/db": "workspace:*",
+ "@keyv/redis": "^5.1.6",
+ "@nestjs/cache-manager": "^3.1.3",
+ "@nestjs/common": "^11.0.1",
+ "@nestjs/config": "^4.0.4",
+ "@nestjs/core": "^11.0.1",
+ "@nestjs/platform-express": "^11.0.1",
+ "@thallesp/nestjs-better-auth": "^2.7.0",
+ "@trpc/server": "^11.18.0",
+ "better-auth": "^1.6.25",
+ "cache-manager": "^7.2.9",
+ "class-transformer": "^0.5.1",
+ "class-validator": "^0.15.1",
+ "context.dev": "^2.7.0",
+ "helmet": "^8.3.0",
+ "nestjs-trpc": "^2.13.0",
+ "reflect-metadata": "^0.2.2",
+ "rxjs": "^7.8.1",
+ "zod": "^4.4.3"
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@nestjs/cli": "^11.0.0",
+ "@nestjs/schematics": "^11.0.0",
+ "@nestjs/testing": "^11.0.1",
+ "@types/bun": "^1.3.14",
+ "@types/express": "^5.0.0",
+ "@types/node": "^24.0.0",
+ "@types/supertest": "^7.0.0",
+ "concurrently": "^9.1.0",
+ "supertest": "^7.0.0",
+ "typescript": "^5.9.2"
+ }
+}
diff --git a/apps/api/scripts/chmod-trpc-binary.mjs b/apps/api/scripts/chmod-trpc-binary.mjs
new file mode 100644
index 00000000..63aeed1f
--- /dev/null
+++ b/apps/api/scripts/chmod-trpc-binary.mjs
@@ -0,0 +1,50 @@
+// nestjs-trpc ships prebuilt native binaries that arrive without the execute
+// bit when Bun unpacks the tarball, so `nestjs-trpc generate` fails with EACCES
+// on a clean install. Restore it after every install.
+import { chmodSync, existsSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join, parse } from "node:path";
+
+const require = createRequire(import.meta.url);
+
+const NATIVE_TARGETS = [
+ "aarch64-apple-darwin",
+ "x86_64-apple-darwin",
+ "aarch64-unknown-linux-gnu",
+ "x86_64-unknown-linux-gnu",
+];
+
+/**
+ * The package root, found by walking up from whatever `nestjs-trpc` resolves
+ * to. `nestjs-trpc/package.json` is not in the package's `exports` map, so it
+ * cannot be resolved directly.
+ */
+function packageRoot() {
+ let dir;
+ try {
+ dir = dirname(require.resolve("nestjs-trpc"));
+ } catch {
+ return undefined;
+ }
+
+ const { root } = parse(dir);
+ while (dir !== root) {
+ if (existsSync(join(dir, "native"))) return dir;
+ dir = dirname(dir);
+ }
+ return undefined;
+}
+
+const root = packageRoot();
+
+if (root) {
+ for (const target of NATIVE_TARGETS) {
+ const binary = join(root, "native", target, "nestjs-trpc");
+ if (!existsSync(binary)) continue;
+ try {
+ chmodSync(binary, 0o755);
+ } catch {
+ // A read-only store is not a reason to fail `bun install`.
+ }
+ }
+}
diff --git a/apps/api/scripts/dev-session.ts b/apps/api/scripts/dev-session.ts
new file mode 100644
index 00000000..f97c1dc6
--- /dev/null
+++ b/apps/api/scripts/dev-session.ts
@@ -0,0 +1,83 @@
+/**
+ * Mints a signed session cookie for a local user.
+ *
+ * Google is the only sign-in method, which means there is no way to get a
+ * session from a script, a test, or a terminal — you need a browser and a real
+ * Google account. That is correct for the product and useless for development,
+ * so this writes the two rows Better Auth would have written and prints the
+ * cookie it would have set.
+ *
+ * bun run --filter=api dev:session # dev@localhost
+ * bun run --filter=api dev:session [email protected]
+ *
+ * curl -H "Cookie: $(bun run --filter=api dev:session)" localhost:3001/auth/me
+ *
+ * Refuses to run in production: it hands out a valid session for any email.
+ */
+import { db } from "@crm/db";
+
+const COOKIE_NAME = "better-auth.session_token";
+const SESSION_DAYS = 7;
+
+if (process.env.NODE_ENV === "production") {
+ throw new Error(
+ "dev-session is a development helper and mints real sessions.",
+ );
+}
+
+const secret = process.env.BETTER_AUTH_SECRET;
+if (!secret) {
+ throw new Error("BETTER_AUTH_SECRET is not set — run this from apps/api.");
+}
+
+const email = process.argv[2] ?? "dev@localhost";
+const name = email.split("@")[0] ?? "Developer";
+
+/** `value.base64(hmacSha256(secret, value))`, url-encoded — Better Auth's format. */
+async function signCookieValue(value: string): Promise<string> {
+ const key = await crypto.subtle.importKey(
+ "raw",
+ new TextEncoder().encode(secret),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ const signature = await crypto.subtle.sign(
+ "HMAC",
+ key,
+ new TextEncoder().encode(value),
+ );
+ const base64 = btoa(String.fromCharCode(...new Uint8Array(signature)));
+ return encodeURIComponent(`${value}.${base64}`);
+}
+
+const user = await db.user.upsert({
+ where: { email },
+ create: {
+ id: `dev-${Buffer.from(email).toString("hex").slice(0, 20)}`,
+ email,
+ name,
+ emailVerified: true,
+ updatedAt: new Date(),
+ },
+ update: {},
+});
+
+const token = `dev-session-${user.id}`;
+const expiresAt = new Date(Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000);
+
+await db.session.upsert({
+ where: { token },
+ create: {
+ id: token,
+ token,
+ userId: user.id,
+ expiresAt,
+ updatedAt: new Date(),
+ },
+ update: { expiresAt },
+});
+
+console.log(`${COOKIE_NAME}=${await signCookieValue(token)}`);
+
+await db.$disconnect();
diff --git a/apps/api/src/activities/activities.contracts.ts b/apps/api/src/activities/activities.contracts.ts
new file mode 100644
index 00000000..10bba6ea
--- /dev/null
+++ b/apps/api/src/activities/activities.contracts.ts
@@ -0,0 +1,114 @@
+import { ActivityType } from "@crm/db";
+import { z } from "zod";
+
+const typeEnum = z.enum(
+ Object.values(ActivityType) as [ActivityType, ...ActivityType[]],
+);
+
+/** Types a human can log. `STAGE_CHANGE` and `ENRICHMENT` are written by the
+ * system and the agent, and are not offered in the composer. */
+export const COMPOSABLE_TYPES = [
+ ActivityType.NOTE,
+ ActivityType.CALL,
+ ActivityType.EMAIL,
+ ActivityType.MEETING,
+ ActivityType.TASK,
+] as const;
+
+const composableEnum = z.enum(COMPOSABLE_TYPES);
+
+/**
+ * Which slice of a timeline to show.
+ *
+ * `history` is `all` minus the tasks that are still outstanding: the timeline
+ * pins those at the top, and an entry that appears both pinned and in the
+ * history below it reads as two different things having happened.
+ */
+export const TIMELINE_FILTERS = [
+ "all",
+ "history",
+ "notes",
+ "upcoming",
+ "done",
+] as const;
+
+export type TimelineFilter = (typeof TIMELINE_FILTERS)[number];
+
+/**
+ * Exactly one anchor. A timeline is always "everything about this thing", and
+ * a company's timeline picks up its deals' and contacts' entries for free
+ * because `companyId` is stamped on write.
+ */
+export const timelineInput = z.object({
+ companyId: z.string().optional(),
+ contactId: z.string().optional(),
+ dealId: z.string().optional(),
+ filter: z.enum(TIMELINE_FILTERS).default("all"),
+ /** Activity id to continue after — timelines page by cursor, not by offset,
+ * because new entries arrive at the top while you are reading. */
+ cursor: z.string().optional(),
+ limit: z.number().int().min(1).max(100).default(30),
+});
+
+export type TimelineInput = z.infer<typeof timelineInput>;
+
+/** The same anchor, without the paging — for the filter tab counts. */
+export const timelineCountsInput = z.object({
+ companyId: z.string().optional(),
+ contactId: z.string().optional(),
+ dealId: z.string().optional(),
+});
+
+export const activityCreateInput = z
+ .object({
+ type: composableEnum,
+ subject: z.string().trim().optional(),
+ body: z.string().trim().optional(),
+ /** ISO-8601. When it happened, for something being logged after the fact. */
+ occurredAt: z.string().optional(),
+ /** ISO-8601. When it is due, for a task. */
+ dueAt: z.string().nullable().optional(),
+ companyId: z.string().optional(),
+ contactId: z.string().optional(),
+ dealId: z.string().optional(),
+ })
+ .refine((input) => input.companyId || input.contactId || input.dealId, {
+ message: "An activity has to be about a company, a contact or a deal.",
+ })
+ .refine(
+ (input) => input.type !== ActivityType.TASK || Boolean(input.subject),
+ {
+ message: "A task needs a subject — it is the thing to do.",
+ path: ["subject"],
+ },
+ );
+
+export type ActivityCreateInput = z.infer<typeof activityCreateInput>;
+
+export const activityUpdateInput = z.object({
+ id: z.string(),
+ subject: z.string().optional(),
+ body: z.string().optional(),
+ dueAt: z.string().nullable().optional(),
+ occurredAt: z.string().nullable().optional(),
+});
+
+export type ActivityUpdateInput = z.infer<typeof activityUpdateInput>;
+
+export const activityIdInput = z.object({ id: z.string() });
+
+export const completeInput = z.object({
+ id: z.string(),
+ /** `false` reopens a task that was ticked off by mistake. */
+ completed: z.boolean().default(true),
+});
+
+export const myTasksInput = z.object({
+ /** `"overdue"`, `"upcoming"`, or `"all"` open tasks. */
+ window: z.enum(["overdue", "upcoming", "all"]).default("all"),
+ limit: z.number().int().min(1).max(100).default(25),
+});
+
+export type MyTasksInput = z.infer<typeof myTasksInput>;
+
+export { typeEnum as activityTypeEnum };
diff --git a/apps/api/src/activities/activities.module.ts b/apps/api/src/activities/activities.module.ts
new file mode 100644
index 00000000..2f8079e3
--- /dev/null
+++ b/apps/api/src/activities/activities.module.ts
@@ -0,0 +1,11 @@
+import { Module } from "@nestjs/common";
+import { TrpcModule } from "../trpc/trpc.module";
+import { ActivitiesRouter } from "./activities.router";
+import { ActivitiesService } from "./activities.service";
+
+@Module({
+ imports: [TrpcModule],
+ providers: [ActivitiesService, ActivitiesRouter],
+ exports: [ActivitiesService],
+})
+export class ActivitiesModule {}
diff --git a/apps/api/src/activities/activities.router.ts b/apps/api/src/activities/activities.router.ts
new file mode 100644
index 00000000..36106c4b
--- /dev/null
+++ b/apps/api/src/activities/activities.router.ts
@@ -0,0 +1,71 @@
+import { Inject } from "@nestjs/common";
+import {
+ Ctx,
+ Input,
+ Mutation,
+ Query,
+ Router,
+ UseMiddlewares,
+} from "nestjs-trpc";
+import type { z } from "zod";
+import type { AuthedTrpcContext } from "../trpc/context.types";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import {
+ activityCreateInput,
+ activityIdInput,
+ activityUpdateInput,
+ completeInput,
+ myTasksInput,
+ timelineCountsInput,
+ timelineInput,
+} from "./activities.contracts";
+import { ActivitiesService } from "./activities.service";
+
+@Router({ alias: "activities" })
+@UseMiddlewares(AuthMiddleware)
+export class ActivitiesRouter {
+ constructor(
+ @Inject(ActivitiesService) private readonly activities: ActivitiesService,
+ ) {}
+
+ @Query({ input: timelineInput })
+ async timeline(@Input() input: z.infer<typeof timelineInput>) {
+ return this.activities.timeline(input);
+ }
+
+ @Query({ input: timelineCountsInput })
+ async timelineCounts(@Input() input: z.infer<typeof timelineCountsInput>) {
+ return this.activities.timelineCounts(input);
+ }
+
+ @Query({ input: myTasksInput })
+ async myTasks(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof myTasksInput>,
+ ) {
+ return this.activities.myTasks(input, ctx.user.id);
+ }
+
+ @Mutation({ input: activityCreateInput })
+ async create(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof activityCreateInput>,
+ ) {
+ return this.activities.create(input, ctx.user.id);
+ }
+
+ @Mutation({ input: activityUpdateInput })
+ async update(@Input() input: z.infer<typeof activityUpdateInput>) {
+ return this.activities.update(input);
+ }
+
+ @Mutation({ input: completeInput })
+ async complete(@Input() input: z.infer<typeof completeInput>) {
+ return this.activities.complete(input.id, input.completed);
+ }
+
+ @Mutation({ input: activityIdInput })
+ async remove(@Input("id") id: string) {
+ return this.activities.remove(id);
+ }
+}
diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.ts
new file mode 100644
index 00000000..cc53d0de
--- /dev/null
+++ b/apps/api/src/activities/activities.service.ts
@@ -0,0 +1,328 @@
+import {
+ ActivityType,
+ type Db,
+ type Prisma,
+ Prisma as PrismaNamespace,
+} from "@crm/db";
+import {
+ BadRequestException,
+ Injectable,
+ Logger,
+ NotFoundException,
+} from "@nestjs/common";
+import { blankToNull } from "../crm/values";
+import { InjectDatabase } from "../database/database.constants";
+import type {
+ ActivityCreateInput,
+ ActivityUpdateInput,
+ MyTasksInput,
+ TimelineFilter,
+ TimelineInput,
+} from "./activities.contracts";
+
+const AUTHOR_SELECT = {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+} as const;
+
+const ENTRY_SELECT = {
+ id: true,
+ type: true,
+ subject: true,
+ body: true,
+ occurredAt: true,
+ dueAt: true,
+ completedAt: true,
+ meta: true,
+ createdAt: true,
+ createdBy: { select: AUTHOR_SELECT },
+ company: { select: { id: true, name: true } },
+ contact: { select: { id: true, firstName: true, lastName: true } },
+ deal: { select: { id: true, name: true } },
+} as const;
+
+/** Entries a `NOTE`-ish filter should keep — what someone wrote down. */
+const NOTE_TYPES = [
+ ActivityType.NOTE,
+ ActivityType.CALL,
+ ActivityType.EMAIL,
+ ActivityType.MEETING,
+];
+
+@Injectable()
+export class ActivitiesService {
+ private readonly logger = new Logger(ActivitiesService.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ /**
+ * A record's timeline, newest first, paged by cursor.
+ *
+ * Cursor rather than offset because entries are added at the top while
+ * someone is reading: page two of an offset query would repeat whatever the
+ * new entry pushed down.
+ */
+ async timeline(input: TimelineInput) {
+ const where = this.anchor(input);
+ Object.assign(where, filterClause(input.filter));
+
+ const rows = await this.db.activity.findMany({
+ where,
+ // One more than asked for, so we know whether there is another page
+ // without a second count query.
+ take: input.limit + 1,
+ ...(input.cursor ? { cursor: { id: input.cursor }, skip: 1 } : {}),
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
+ select: ENTRY_SELECT,
+ });
+
+ const hasMore = rows.length > input.limit;
+ const entries = hasMore ? rows.slice(0, input.limit) : rows;
+
+ return {
+ entries: entries.map(serializeEntry),
+ nextCursor: hasMore ? (entries[entries.length - 1]?.id ?? null) : null,
+ };
+ }
+
+ /**
+ * Counts for the timeline's filter tabs, over the same anchor.
+ *
+ * Separate from `timeline` so paging does not re-count on every scroll.
+ */
+ async timelineCounts(
+ input: Pick<TimelineInput, "companyId" | "contactId" | "dealId">,
+ ) {
+ const anchor = this.anchor(input);
+
+ const [all, notes, upcoming, done] = await Promise.all([
+ this.db.activity.count({ where: anchor }),
+ this.db.activity.count({
+ where: { ...anchor, ...filterClause("notes") },
+ }),
+ this.db.activity.count({
+ where: { ...anchor, ...filterClause("upcoming") },
+ }),
+ this.db.activity.count({ where: { ...anchor, ...filterClause("done") } }),
+ ]);
+
+ return { all, notes, upcoming, done };
+ }
+
+ async create(input: ActivityCreateInput, actingUserId: string) {
+ // A deal or contact activity is stamped with its company too, so a company
+ // timeline is one indexed range scan instead of three joins.
+ const companyId = await this.resolveCompanyId(input);
+
+ const isTask = input.type === ActivityType.TASK;
+
+ const activity = await this.db.activity.create({
+ data: {
+ type: input.type,
+ subject: blankToNull(input.subject ?? ""),
+ body: blankToNull(input.body ?? ""),
+ // A task is scheduled, not logged; everything else already happened
+ // unless the composer says otherwise.
+ occurredAt: isTask ? null : (parseDate(input.occurredAt) ?? new Date()),
+ dueAt: isTask ? parseDate(input.dueAt) : null,
+ companyId,
+ contactId: input.contactId ?? null,
+ dealId: input.dealId ?? null,
+ createdById: actingUserId,
+ },
+ select: ENTRY_SELECT,
+ });
+
+ this.logger.log({
+ message: "Activity logged",
+ activityId: activity.id,
+ type: activity.type,
+ });
+
+ return serializeEntry(activity);
+ }
+
+ async update(input: ActivityUpdateInput) {
+ const data: Prisma.ActivityUpdateInput = {};
+
+ if (input.subject !== undefined) data.subject = blankToNull(input.subject);
+ if (input.body !== undefined) data.body = blankToNull(input.body);
+ if (input.dueAt !== undefined) data.dueAt = parseDate(input.dueAt);
+ if (input.occurredAt !== undefined) {
+ data.occurredAt = parseDate(input.occurredAt);
+ }
+
+ try {
+ const activity = await this.db.activity.update({
+ where: { id: input.id },
+ data,
+ select: ENTRY_SELECT,
+ });
+ return serializeEntry(activity);
+ } catch (error) {
+ throw this.translate(error, input.id);
+ }
+ }
+
+ /** Ticks a task off, or puts it back. */
+ async complete(id: string, completed: boolean) {
+ const activity = await this.db.activity.findUnique({
+ where: { id },
+ select: { type: true },
+ });
+
+ if (!activity) {
+ throw new NotFoundException(`No activity with id ${id}.`);
+ }
+
+ if (activity.type !== ActivityType.TASK) {
+ throw new BadRequestException("Only tasks can be completed.");
+ }
+
+ const updated = await this.db.activity.update({
+ where: { id },
+ data: { completedAt: completed ? new Date() : null },
+ select: ENTRY_SELECT,
+ });
+
+ return serializeEntry(updated);
+ }
+
+ async remove(id: string): Promise<{ id: string }> {
+ try {
+ await this.db.activity.delete({ where: { id } });
+ } catch (error) {
+ throw this.translate(error, id);
+ }
+ return { id };
+ }
+
+ /** Open tasks assigned to whoever is asking. */
+ async myTasks(input: MyTasksInput, actingUserId: string) {
+ const now = new Date();
+ const where: Prisma.ActivityWhereInput = {
+ type: ActivityType.TASK,
+ completedAt: null,
+ createdById: actingUserId,
+ };
+
+ if (input.window === "overdue") where.dueAt = { lt: now };
+ if (input.window === "upcoming") where.dueAt = { gte: now };
+
+ const tasks = await this.db.activity.findMany({
+ where,
+ take: input.limit,
+ // Undated tasks last: a task with no due date is a someday, and it
+ // should not sit above something due this afternoon.
+ orderBy: [
+ { dueAt: { sort: "asc", nulls: "last" } },
+ { createdAt: "desc" },
+ ],
+ select: ENTRY_SELECT,
+ });
+
+ return tasks.map(serializeEntry);
+ }
+
+ /** Exactly one of company/contact/deal, as the contract promises. */
+ private anchor(
+ input: Pick<TimelineInput, "companyId" | "contactId" | "dealId">,
+ ): Prisma.ActivityWhereInput {
+ if (input.dealId) return { dealId: input.dealId };
+ if (input.contactId) return { contactId: input.contactId };
+ if (input.companyId) return { companyId: input.companyId };
+ throw new BadRequestException(
+ "A timeline needs a company, a contact or a deal.",
+ );
+ }
+
+ /**
+ * The company an activity belongs to.
+ *
+ * Taken from the deal or contact when the caller did not say, which is what
+ * makes the company timeline work without joins. A contact with no company
+ * simply has no company stamp.
+ */
+ private async resolveCompanyId(
+ input: ActivityCreateInput,
+ ): Promise<string | null> {
+ if (input.companyId) return input.companyId;
+
+ if (input.dealId) {
+ const deal = await this.db.deal.findUnique({
+ where: { id: input.dealId },
+ select: { companyId: true },
+ });
+ if (!deal) {
+ throw new NotFoundException(`No deal with id ${input.dealId}.`);
+ }
+ return deal.companyId;
+ }
+
+ if (input.contactId) {
+ const contact = await this.db.contact.findUnique({
+ where: { id: input.contactId },
+ select: { companyId: true },
+ });
+ if (!contact) {
+ throw new NotFoundException(`No contact with id ${input.contactId}.`);
+ }
+ return contact.companyId;
+ }
+
+ return null;
+ }
+
+ private translate(error: unknown, id: string): unknown {
+ if (
+ error instanceof PrismaNamespace.PrismaClientKnownRequestError &&
+ error.code === "P2025"
+ ) {
+ return new NotFoundException(`No activity with id ${id}.`);
+ }
+ return error;
+ }
+}
+
+function filterClause(filter: TimelineFilter): Prisma.ActivityWhereInput {
+ switch (filter) {
+ case "notes":
+ return { type: { in: NOTE_TYPES } };
+ case "upcoming":
+ // Everything still outstanding, overdue included — "upcoming" on a
+ // timeline means "not done yet", and hiding the overdue ones is how
+ // they get forgotten.
+ return { type: ActivityType.TASK, completedAt: null };
+ case "done":
+ return { type: ActivityType.TASK, completedAt: { not: null } };
+ case "history":
+ return { NOT: { type: ActivityType.TASK, completedAt: null } };
+ case "all":
+ return {};
+ }
+}
+
+type Entry = Prisma.ActivityGetPayload<{ select: typeof ENTRY_SELECT }>;
+
+/** Dates as ISO strings so they survive JSON, and `meta` narrowed for the UI. */
+function serializeEntry(entry: Entry) {
+ return {
+ ...entry,
+ occurredAt: entry.occurredAt?.toISOString() ?? null,
+ dueAt: entry.dueAt?.toISOString() ?? null,
+ completedAt: entry.completedAt?.toISOString() ?? null,
+ createdAt: entry.createdAt.toISOString(),
+ meta: entry.meta as Record<string, unknown> | null,
+ };
+}
+
+function parseDate(value: string | null | undefined): Date | null {
+ if (value === null || value === undefined || value === "") return null;
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) {
+ throw new BadRequestException(`"${value}" is not a date.`);
+ }
+ return date;
+}
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts
new file mode 100644
index 00000000..9bf933a1
--- /dev/null
+++ b/apps/api/src/app.module.ts
@@ -0,0 +1,46 @@
+import { auth } from "@crm/auth";
+import { Module } from "@nestjs/common";
+import { ConfigModule } from "@nestjs/config";
+import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";
+import { ActivitiesModule } from "./activities/activities.module";
+import { AuthModule } from "./auth/auth.module";
+import { AppCacheModule } from "./cache/cache.module";
+import { CompaniesModule } from "./companies/companies.module";
+import { validateEnv } from "./config/env.validation";
+import { ContactsModule } from "./contacts/contacts.module";
+import { DashboardModule } from "./dashboard/dashboard.module";
+import { DatabaseModule } from "./database/database.module";
+import { DealsModule } from "./deals/deals.module";
+import { HealthModule } from "./health/health.module";
+import { ImportModule } from "./import/import.module";
+import { LoggingModule } from "./logging/logging.module";
+import { logAuthRoute } from "./logging/request-logger.middleware";
+import { SearchModule } from "./search/search.module";
+import { TrpcModule } from "./trpc/trpc.module";
+import { UsersModule } from "./users/users.module";
+
+@Module({
+ imports: [
+ LoggingModule,
+ ConfigModule.forRoot({
+ isGlobal: true,
+ cache: true,
+ validate: validateEnv,
+ }),
+ AppCacheModule,
+ DatabaseModule,
+ BetterAuthModule.forRoot({ auth, middleware: logAuthRoute }),
+ AuthModule,
+ HealthModule,
+ TrpcModule,
+ UsersModule,
+ CompaniesModule,
+ ContactsModule,
+ DealsModule,
+ ActivitiesModule,
+ DashboardModule,
+ ImportModule,
+ SearchModule,
+ ],
+})
+export class AppModule {}
diff --git a/apps/api/src/auth/auth-hooks.service.ts b/apps/api/src/auth/auth-hooks.service.ts
new file mode 100644
index 00000000..f50f96cc
--- /dev/null
+++ b/apps/api/src/auth/auth-hooks.service.ts
@@ -0,0 +1,34 @@
+import { Injectable, Logger } from "@nestjs/common";
+import { AfterUpdate, DatabaseHook } from "@thallesp/nestjs-better-auth";
+import { AuthService } from "./auth.service";
+
+/**
+ * Cached profiles are bounded by TTL; this drops one the moment its row
+ * changes, so a rename never lingers for five minutes.
+ *
+ * A database hook rather than an endpoint hook: Better Auth also writes to
+ * `user` when Google reports a changed name or avatar at sign-in, and that
+ * never goes through `/update-user`.
+ */
+@DatabaseHook()
+@Injectable()
+export class AuthHooksService {
+ private readonly logger = new Logger(AuthHooksService.name);
+
+ constructor(private readonly authService: AuthService) {}
+
+ @AfterUpdate("user")
+ async onUserUpdated(user: { id: string }): Promise<void> {
+ try {
+ await this.authService.invalidateProfile(user.id);
+ } catch (error) {
+ // This runs inside Better Auth's write pipeline: throwing here would
+ // fail the update itself. A stale profile expires on its own within
+ // the TTL, so log it and let the write stand.
+ this.logger.error(
+ { message: "Failed to invalidate cached profile", userId: user.id },
+ error instanceof Error ? error.stack : String(error),
+ );
+ }
+ }
+}
diff --git a/apps/api/src/auth/auth.controller.ts b/apps/api/src/auth/auth.controller.ts
new file mode 100644
index 00000000..3bc5f516
--- /dev/null
+++ b/apps/api/src/auth/auth.controller.ts
@@ -0,0 +1,34 @@
+import type { auth } from "@crm/auth";
+import { Controller, Get } from "@nestjs/common";
+import {
+ OptionalAuth,
+ Session,
+ type UserSession,
+} from "@thallesp/nestjs-better-auth";
+import { AuthService } from "./auth.service";
+
+type CrmSession = UserSession<typeof auth>;
+
+@Controller("auth")
+export class AuthController {
+ constructor(private readonly authService: AuthService) {}
+
+ @Get("me")
+ async getMe(@Session() session: CrmSession) {
+ return { user: await this.authService.getProfile(session.user.id) };
+ }
+
+ @Get("session")
+ @OptionalAuth()
+ getSession(@Session() session?: CrmSession) {
+ if (!session) {
+ return { authenticated: false, user: null };
+ }
+
+ return {
+ authenticated: true,
+ user: { id: session.user.id, email: session.user.email },
+ expiresAt: session.session.expiresAt,
+ };
+ }
+}
diff --git a/apps/api/src/auth/auth.module.ts b/apps/api/src/auth/auth.module.ts
new file mode 100644
index 00000000..505c5c85
--- /dev/null
+++ b/apps/api/src/auth/auth.module.ts
@@ -0,0 +1,11 @@
+import { Module } from "@nestjs/common";
+import { AuthController } from "./auth.controller";
+import { AuthService } from "./auth.service";
+import { AuthHooksService } from "./auth-hooks.service";
+
+@Module({
+ controllers: [AuthController],
+ providers: [AuthService, AuthHooksService],
+ exports: [AuthService],
+})
+export class AuthModule {}
diff --git a/apps/api/src/auth/auth.service.ts b/apps/api/src/auth/auth.service.ts
new file mode 100644
index 00000000..b69161c1
--- /dev/null
+++ b/apps/api/src/auth/auth.service.ts
@@ -0,0 +1,78 @@
+import type { Db } from "@crm/db";
+import { CACHE_MANAGER } from "@nestjs/cache-manager";
+import { Inject, Injectable, Logger, NotFoundException } from "@nestjs/common";
+import type { Cache } from "cache-manager";
+import { InjectDatabase } from "../database/database.constants";
+
+export interface UserProfile {
+ id: string;
+ name: string;
+ email: string;
+ emailVerified: boolean;
+ image: string | null;
+ /** ISO-8601: a `Date` would come back from Redis as a string anyway. */
+ createdAt: string;
+}
+
+const PROFILE_TTL_MS = 5 * 60_000;
+
+const profileKey = (userId: string) => `auth:profile:${userId}`;
+
+@Injectable()
+export class AuthService {
+ private readonly logger = new Logger(AuthService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ @Inject(CACHE_MANAGER) private readonly cache: Cache,
+ ) {}
+
+ /**
+ * The session already carries a user, but it is the snapshot taken when the
+ * cookie was minted. Reading the row means a profile change shows up within
+ * the cache TTL instead of at the next sign-in.
+ */
+ async getProfile(userId: string): Promise<UserProfile> {
+ const key = profileKey(userId);
+ const cached = await this.cache.get<UserProfile>(key);
+
+ if (cached) {
+ return cached;
+ }
+
+ this.logger.debug({ message: "Profile cache miss", userId });
+
+ const user = await this.db.user.findUnique({
+ where: { id: userId },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ emailVerified: true,
+ image: true,
+ createdAt: true,
+ },
+ });
+
+ if (!user) {
+ // A live session pointing at a deleted row: worth a warning, because
+ // it means a session outlived its user.
+ this.logger.warn({ message: "Session user no longer exists", userId });
+ throw new NotFoundException(`No user with id ${userId}.`);
+ }
+
+ const profile: UserProfile = {
+ ...user,
+ createdAt: user.createdAt.toISOString(),
+ };
+
+ await this.cache.set(key, profile, PROFILE_TTL_MS);
+
+ return profile;
+ }
+
+ async invalidateProfile(userId: string): Promise<void> {
+ await this.cache.del(profileKey(userId));
+ this.logger.debug({ message: "Invalidated cached profile", userId });
+ }
+}
diff --git a/apps/api/src/cache/cache.module.ts b/apps/api/src/cache/cache.module.ts
new file mode 100644
index 00000000..04d29290
--- /dev/null
+++ b/apps/api/src/cache/cache.module.ts
@@ -0,0 +1,39 @@
+import KeyvRedis from "@keyv/redis";
+import { CacheModule, type CacheOptions } from "@nestjs/cache-manager";
+import { Logger, Module } from "@nestjs/common";
+import { ConfigService } from "@nestjs/config";
+import type { EnvironmentVariables } from "../config/env.validation";
+
+const DEFAULT_TTL_MS = 60_000;
+
+@Module({
+ imports: [
+ CacheModule.registerAsync({
+ isGlobal: true,
+ inject: [ConfigService],
+ useFactory: (
+ config: ConfigService<EnvironmentVariables, true>,
+ ): CacheOptions => {
+ const logger = new Logger("CacheModule");
+ const redisUrl = config.get("REDIS_URL", { infer: true });
+ const ttl =
+ config.get("CACHE_TTL_MS", { infer: true }) ?? DEFAULT_TTL_MS;
+
+ if (!redisUrl) {
+ logger.warn({
+ message:
+ "REDIS_URL is not set — falling back to a per-instance in-memory cache.",
+ ttl,
+ });
+ return { ttl };
+ }
+
+ logger.log({ message: "Cache backed by Redis", ttl });
+
+ return { ttl, stores: [new KeyvRedis(redisUrl)] };
+ },
+ }),
+ ],
+ exports: [CacheModule],
+})
+export class AppCacheModule {}
diff --git a/apps/api/src/companies/companies.contracts.ts b/apps/api/src/companies/companies.contracts.ts
new file mode 100644
index 00000000..9a09ae21
--- /dev/null
+++ b/apps/api/src/companies/companies.contracts.ts
@@ -0,0 +1,69 @@
+import { z } from "zod";
+import { listInput } from "../trpc/list-input";
+
+/**
+ * The companies list adds three facets to the shared list input. Each defaults
+ * to `"all"`, which is also what the URL parsers on the front end send when a
+ * dropdown is untouched — so an unfiltered request and an unfiltered URL are
+ * the same request.
+ */
+export const companyListInput = listInput.extend({
+ /** A user id, `"unassigned"`, or `"all"`. */
+ owner: z.string().default("all"),
+ industry: z.string().default("all"),
+ /** An `EnrichmentStatus`, or `"all"`. */
+ enrichment: z.string().default("all"),
+});
+
+export type CompanyListInput = z.infer<typeof companyListInput>;
+
+/**
+ * Creating a company asks for the three things a human actually knows. The
+ * logo, description, industry, address and socials are the agent's job.
+ */
+export const companyCreateInput = z.object({
+ name: z.string().trim().min(1, "A company needs a name."),
+ domain: z.string().trim().optional(),
+ ownerId: z.string().nullable().optional(),
+});
+
+export type CompanyCreateInput = z.infer<typeof companyCreateInput>;
+
+/**
+ * Every field is optional and `undefined` means "leave it alone", so the inline
+ * editors on the detail page can send one field at a time. An empty string
+ * clears a value; `null` on `ownerId` unassigns.
+ */
+export const companyUpdateInput = z.object({
+ name: z.string().trim().min(1).optional(),
+ domain: z.string().optional(),
+ website: z.string().optional(),
+ description: z.string().optional(),
+ industry: z.string().optional(),
+ city: z.string().optional(),
+ stateCode: z.string().optional(),
+ country: z.string().optional(),
+ phone: z.string().optional(),
+ email: z.string().optional(),
+ linkedinUrl: z.string().optional(),
+ ownerId: z.string().nullable().optional(),
+});
+
+export type CompanyUpdateInput = z.infer<typeof companyUpdateInput>;
+
+export const companyUpdateArgs = z.object({
+ id: z.string(),
+ data: companyUpdateInput,
+});
+
+export const companyIdInput = z.object({ id: z.string() });
+
+export const setPrimaryContactInput = z.object({
+ companyId: z.string(),
+ contactId: z.string().nullable(),
+});
+
+/** Free-text filter for the company picker; `""` means "the first hundred". */
+export const companyOptionsInput = z.object({
+ q: z.string().default(""),
+});
diff --git a/apps/api/src/companies/companies.module.ts b/apps/api/src/companies/companies.module.ts
new file mode 100644
index 00000000..6a958a6d
--- /dev/null
+++ b/apps/api/src/companies/companies.module.ts
@@ -0,0 +1,12 @@
+import { Module } from "@nestjs/common";
+import { EnrichmentModule } from "../enrichment/enrichment.module";
+import { TrpcModule } from "../trpc/trpc.module";
+import { CompaniesRouter } from "./companies.router";
+import { CompaniesService } from "./companies.service";
+
+@Module({
+ imports: [TrpcModule, EnrichmentModule],
+ providers: [CompaniesService, CompaniesRouter],
+ exports: [CompaniesService],
+})
+export class CompaniesModule {}
diff --git a/apps/api/src/companies/companies.router.ts b/apps/api/src/companies/companies.router.ts
new file mode 100644
index 00000000..838ea93e
--- /dev/null
+++ b/apps/api/src/companies/companies.router.ts
@@ -0,0 +1,79 @@
+import { Inject } from "@nestjs/common";
+import {
+ Ctx,
+ Input,
+ Mutation,
+ Query,
+ Router,
+ UseMiddlewares,
+} from "nestjs-trpc";
+import type { z } from "zod";
+import type { AuthedTrpcContext } from "../trpc/context.types";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import {
+ companyCreateInput,
+ companyIdInput,
+ companyListInput,
+ companyOptionsInput,
+ companyUpdateArgs,
+ setPrimaryContactInput,
+} from "./companies.contracts";
+import { CompaniesService } from "./companies.service";
+
+@Router({ alias: "companies" })
+@UseMiddlewares(AuthMiddleware)
+export class CompaniesRouter {
+ constructor(
+ @Inject(CompaniesService) private readonly companies: CompaniesService,
+ ) {}
+
+ @Query({ input: companyListInput })
+ async list(@Input() input: z.infer<typeof companyListInput>) {
+ return this.companies.list(input);
+ }
+
+ @Query({ input: companyIdInput })
+ async byId(@Input("id") id: string) {
+ return this.companies.byId(id);
+ }
+
+ /** Company pickers and facet labels. */
+ @Query({ input: companyOptionsInput })
+ async options(@Input("q") q: string) {
+ return this.companies.options(q);
+ }
+
+ @Mutation({ input: companyCreateInput })
+ async create(@Input() input: z.infer<typeof companyCreateInput>) {
+ return this.companies.create(input);
+ }
+
+ @Mutation({ input: companyUpdateArgs })
+ async update(@Input() input: z.infer<typeof companyUpdateArgs>) {
+ return this.companies.update(input.id, input.data);
+ }
+
+ @Mutation({ input: companyIdInput })
+ async remove(@Input("id") id: string) {
+ return this.companies.remove(id);
+ }
+
+ /** Re-runs the brand lookup, ignoring Context.dev's cache. */
+ @Mutation({ input: companyIdInput })
+ async enrich(@Input("id") id: string) {
+ return this.companies.enrich(id);
+ }
+
+ /** Reads the company's site and posts a brief to its timeline. */
+ @Mutation({ input: companyIdInput })
+ async research(@Ctx() ctx: AuthedTrpcContext, @Input("id") id: string) {
+ return this.companies.research(id, ctx.user.id);
+ }
+
+ @Mutation({ input: setPrimaryContactInput })
+ async setPrimaryContact(
+ @Input() input: z.infer<typeof setPrimaryContactInput>,
+ ) {
+ return this.companies.setPrimaryContact(input.companyId, input.contactId);
+ }
+}
diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.ts
new file mode 100644
index 00000000..1821d356
--- /dev/null
+++ b/apps/api/src/companies/companies.service.ts
@@ -0,0 +1,510 @@
+import {
+ type Db,
+ type EnrichmentStatus,
+ type Prisma,
+ Prisma as PrismaNamespace,
+} from "@crm/db";
+import {
+ BadRequestException,
+ ConflictException,
+ Injectable,
+ Logger,
+ NotFoundException,
+} from "@nestjs/common";
+import { blankToNull, toCents } from "../crm/values";
+import { InjectDatabase } from "../database/database.constants";
+import { OPEN_DEAL_STAGES } from "../deals/deal-stage";
+import { EnrichmentService } from "../enrichment/enrichment.service";
+import {
+ countsByKey,
+ FACET_ALL,
+ FACET_UNASSIGNED,
+ type ListResult,
+ ownerFilter,
+ paginate,
+ resolveOrderBy,
+} from "../trpc/list-input";
+import type {
+ CompanyCreateInput,
+ CompanyListInput,
+ CompanyUpdateInput,
+} from "./companies.contracts";
+import { normalizeDomain } from "./domain";
+
+const OWNER_SELECT = {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+} as const;
+
+/** One row of the companies table. */
+export type CompanyRow = {
+ id: string;
+ name: string;
+ domain: string | null;
+ iconUrl: string | null;
+ logoUrl: string | null;
+ brandColor: string | null;
+ industry: string | null;
+ enrichmentStatus: EnrichmentStatus;
+ owner: {
+ id: string;
+ name: string;
+ email: string;
+ image: string | null;
+ } | null;
+ contactCount: number;
+ openDealCount: number;
+ /** ISO-8601, or null when nothing has happened yet. */
+ lastActivityAt: string | null;
+};
+
+/**
+ * Columns `?sort=` may name, and the Prisma ordering each one means.
+ *
+ * Spelled out rather than derived from the column id so `?sort=` can never
+ * reach Prisma as an arbitrary field name — and because ordering by a relation
+ * count is not a flat `{ [id]: dir }`.
+ *
+ * Contacts and open deals sort by relation count, which Prisma can do. Last
+ * activity cannot: ordering by `max(activity.createdAt)` is an aggregate over a
+ * relation, which has no Prisma ordering, so that column is display-only.
+ */
+const SORTABLE: Record<
+ string,
+ (dir: Prisma.SortOrder) => Prisma.CompanyOrderByWithRelationInput
+> = {
+ name: (dir) => ({ name: dir }),
+ domain: (dir) => ({ domain: dir }),
+ industry: (dir) => ({ industry: dir }),
+ createdAt: (dir) => ({ createdAt: dir }),
+ contacts: (dir) => ({ contacts: { _count: dir } }),
+ deals: (dir) => ({ deals: { _count: dir } }),
+};
+
+@Injectable()
+export class CompaniesService {
+ private readonly logger = new Logger(CompaniesService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly enrichment: EnrichmentService,
+ ) {}
+
+ async list(input: CompanyListInput): Promise<ListResult<CompanyRow>> {
+ const where = this.buildWhere(input);
+ const { skip, take } = paginate(input);
+
+ const [rows, total, facetCounts] = await Promise.all([
+ this.db.company.findMany({
+ where,
+ skip,
+ take,
+ orderBy: resolveOrderBy(input, SORTABLE, { name: "asc" }),
+ select: {
+ id: true,
+ name: true,
+ domain: true,
+ iconUrl: true,
+ logoUrl: true,
+ brandColor: true,
+ industry: true,
+ enrichmentStatus: true,
+ owner: { select: OWNER_SELECT },
+ _count: {
+ select: {
+ contacts: true,
+ deals: { where: { stage: { in: [...OPEN_DEAL_STAGES] } } },
+ },
+ },
+ // One row per company via a lateral join — cheap at a page of 25,
+ // and the only way to get "last activity" without an aggregate
+ // Prisma cannot express.
+ activities: {
+ take: 1,
+ orderBy: { createdAt: "desc" },
+ select: { createdAt: true },
+ },
+ },
+ }),
+ this.db.company.count({ where }),
+ this.facetCounts(input),
+ ]);
+
+ return {
+ rows: rows.map((row) => ({
+ id: row.id,
+ name: row.name,
+ domain: row.domain,
+ iconUrl: row.iconUrl,
+ logoUrl: row.logoUrl,
+ brandColor: row.brandColor,
+ industry: row.industry,
+ enrichmentStatus: row.enrichmentStatus,
+ owner: row.owner,
+ contactCount: row._count.contacts,
+ openDealCount: row._count.deals,
+ lastActivityAt: row.activities[0]?.createdAt.toISOString() ?? null,
+ })),
+ total,
+ facetCounts,
+ };
+ }
+
+ async byId(id: string) {
+ const company = await this.db.company.findUnique({
+ where: { id },
+ select: {
+ id: true,
+ name: true,
+ domain: true,
+ website: true,
+ description: true,
+ logoUrl: true,
+ logoDarkUrl: true,
+ iconUrl: true,
+ brandColor: true,
+ industry: true,
+ subIndustry: true,
+ city: true,
+ stateCode: true,
+ country: true,
+ countryCode: true,
+ phone: true,
+ email: true,
+ linkedinUrl: true,
+ twitterUrl: true,
+ githubUrl: true,
+ pricingUrl: true,
+ careersUrl: true,
+ enrichmentStatus: true,
+ enrichedAt: true,
+ enrichmentError: true,
+ createdAt: true,
+ owner: { select: OWNER_SELECT },
+ primaryContact: {
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ email: true,
+ phone: true,
+ title: true,
+ },
+ },
+ contacts: {
+ orderBy: [{ lastName: "asc" }, { firstName: "asc" }],
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ email: true,
+ title: true,
+ owner: { select: OWNER_SELECT },
+ },
+ },
+ deals: {
+ orderBy: [{ stage: "asc" }, { expectedCloseDate: "asc" }],
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ amount: true,
+ currency: true,
+ expectedCloseDate: true,
+ owner: { select: OWNER_SELECT },
+ },
+ },
+ },
+ });
+
+ if (!company) {
+ throw new NotFoundException(`No company with id ${id}.`);
+ }
+
+ const { deals, primaryContact, enrichedAt, createdAt, ...rest } = company;
+
+ return {
+ ...rest,
+ createdAt: createdAt.toISOString(),
+ enrichedAt: enrichedAt?.toISOString() ?? null,
+ primaryContactId: primaryContact?.id ?? null,
+ primaryContact,
+ deals: deals.map((deal) => ({
+ ...deal,
+ amount: undefined,
+ amountCents: toCents(deal.amount),
+ expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,
+ })),
+ };
+ }
+
+ /**
+ * Companies for a picker or a facet label — id, name and enough to draw the
+ * logo, nothing else.
+ *
+ * Capped at 100 and searchable, so the "which company?" dropdown on a contact
+ * or a deal stays a dropdown rather than becoming a second list view.
+ */
+ async options(q: string) {
+ return this.db.company.findMany({
+ where: this.searchFilter(q),
+ select: { id: true, name: true, domain: true, iconUrl: true },
+ orderBy: { name: "asc" },
+ take: 100,
+ });
+ }
+
+ async create(input: CompanyCreateInput) {
+ const domain = normalizeDomain(input.domain);
+
+ if (domain) {
+ const existing = await this.db.company.findUnique({
+ where: { domain },
+ select: { id: true, name: true },
+ });
+ if (existing) {
+ throw new ConflictException(
+ `${existing.name} already uses the domain ${domain}.`,
+ );
+ }
+ }
+
+ const company = await this.db.company.create({
+ data: {
+ name: input.name.trim(),
+ domain,
+ website: domain ? `https://${domain}` : null,
+ ownerId: input.ownerId ?? null,
+ },
+ select: { id: true, name: true, domain: true },
+ });
+
+ this.logger.log({
+ message: "Company created",
+ companyId: company.id,
+ domain: company.domain,
+ });
+
+ // Fire-and-forget: a cold lookup is several seconds, and the create form
+ // should not wait on it. The detail page polls until it settles.
+ this.enrichment.enqueueCompany(company.id);
+
+ return company;
+ }
+
+ async update(id: string, input: CompanyUpdateInput) {
+ const data: Prisma.CompanyUpdateInput = {};
+
+ if (input.name !== undefined) data.name = input.name.trim();
+ if (input.website !== undefined) data.website = blankToNull(input.website);
+ if (input.description !== undefined) {
+ data.description = blankToNull(input.description);
+ }
+ if (input.industry !== undefined)
+ data.industry = blankToNull(input.industry);
+ if (input.city !== undefined) data.city = blankToNull(input.city);
+ if (input.stateCode !== undefined) {
+ data.stateCode = blankToNull(input.stateCode);
+ }
+ if (input.country !== undefined) data.country = blankToNull(input.country);
+ if (input.phone !== undefined) data.phone = blankToNull(input.phone);
+ if (input.email !== undefined) data.email = blankToNull(input.email);
+ if (input.linkedinUrl !== undefined) {
+ data.linkedinUrl = blankToNull(input.linkedinUrl);
+ }
+ if (input.ownerId !== undefined) {
+ data.owner = input.ownerId
+ ? { connect: { id: input.ownerId } }
+ : { disconnect: true };
+ }
+
+ if (input.domain !== undefined) {
+ const domain = normalizeDomain(input.domain);
+ if (input.domain.trim() && !domain) {
+ throw new BadRequestException(
+ `"${input.domain}" is not a domain — try something like "stripe.com".`,
+ );
+ }
+ data.domain = domain;
+ // A new domain means the enrichment we have is for the wrong company.
+ // Phase 6 picks PENDING rows up; until then this is honest bookkeeping.
+ const current = await this.db.company.findUnique({
+ where: { id },
+ select: { domain: true },
+ });
+ if (current && current.domain !== domain) {
+ data.enrichmentStatus = "PENDING";
+ data.enrichmentError = null;
+ }
+ }
+
+ try {
+ const updated = await this.db.company.update({
+ where: { id },
+ data,
+ select: { id: true, name: true, domain: true },
+ });
+
+ if (data.enrichmentStatus === "PENDING") {
+ this.enrichment.enqueueCompany(id);
+ }
+
+ return updated;
+ } catch (error) {
+ throw this.translate(error, id);
+ }
+ }
+
+ /**
+ * The "Re-enrich" button.
+ *
+ * `force` bypasses Context.dev's ~90-day cache, which is the whole reason
+ * someone would press it.
+ */
+ async enrich(id: string): Promise<{ id: string; queued: boolean }> {
+ const company = await this.db.company.findUnique({
+ where: { id },
+ select: { id: true },
+ });
+
+ if (!company) {
+ throw new NotFoundException(`No company with id ${id}.`);
+ }
+
+ return { id, queued: this.enrichment.enqueueCompany(id, { force: true }) };
+ }
+
+ /** Reads the company's site and posts a brief to its timeline. */
+ async research(id: string, actingUserId: string) {
+ const result = await this.enrichment.researchCompany(id, actingUserId);
+ if (!result.ok) {
+ throw new BadRequestException(result.reason);
+ }
+ return result;
+ }
+
+ async remove(id: string): Promise<{ id: string }> {
+ try {
+ await this.db.company.delete({ where: { id } });
+ } catch (error) {
+ throw this.translate(error, id);
+ }
+ this.logger.log({ message: "Company deleted", companyId: id });
+ return { id };
+ }
+
+ /**
+ * Points a company at the person to call.
+ *
+ * The contact has to already belong to the company: a "primary contact" who
+ * works somewhere else is a data-entry accident, not a relationship.
+ */
+ async setPrimaryContact(companyId: string, contactId: string | null) {
+ if (contactId) {
+ const contact = await this.db.contact.findUnique({
+ where: { id: contactId },
+ select: { companyId: true },
+ });
+ if (!contact) {
+ throw new NotFoundException(`No contact with id ${contactId}.`);
+ }
+ if (contact.companyId !== companyId) {
+ throw new BadRequestException(
+ "That contact does not work at this company.",
+ );
+ }
+ }
+
+ try {
+ return await this.db.company.update({
+ where: { id: companyId },
+ data: { primaryContactId: contactId },
+ select: { id: true, primaryContactId: true },
+ });
+ } catch (error) {
+ throw this.translate(error, companyId);
+ }
+ }
+
+ /** `q` matches the name or the domain — the two things a rep would type. */
+ private searchFilter(q: string): Prisma.CompanyWhereInput {
+ const term = q.trim();
+ if (!term) return {};
+
+ return {
+ OR: [
+ { name: { contains: term, mode: "insensitive" } },
+ { domain: { contains: term, mode: "insensitive" } },
+ ],
+ };
+ }
+
+ private buildWhere(input: CompanyListInput): Prisma.CompanyWhereInput {
+ const where: Prisma.CompanyWhereInput = {
+ ...this.searchFilter(input.q),
+ ...ownerFilter(input.owner),
+ };
+
+ if (input.industry !== FACET_ALL) {
+ where.industry = input.industry;
+ }
+
+ if (input.enrichment !== FACET_ALL) {
+ where.enrichmentStatus = input.enrichment as EnrichmentStatus;
+ }
+
+ return where;
+ }
+
+ /**
+ * Counts for the facet dropdowns.
+ *
+ * Computed against the search term only, not the other facets: counts that
+ * shift every time you touch a different dropdown are hard to read, and
+ * options that vanish are worse.
+ */
+ private async facetCounts(input: CompanyListInput) {
+ const where = this.searchFilter(input.q);
+
+ const [owners, industries, enrichment] = await Promise.all([
+ this.db.company.groupBy({
+ by: ["ownerId"],
+ where,
+ _count: { _all: true },
+ }),
+ this.db.company.groupBy({
+ by: ["industry"],
+ where,
+ _count: { _all: true },
+ }),
+ this.db.company.groupBy({
+ by: ["enrichmentStatus"],
+ where,
+ _count: { _all: true },
+ }),
+ ]);
+
+ return {
+ owner: countsByKey(owners, "ownerId", FACET_UNASSIGNED),
+ industry: countsByKey(industries, "industry"),
+ enrichment: countsByKey(enrichment, "enrichmentStatus"),
+ };
+ }
+
+ /** Prisma's constraint errors, said in a way a rep can act on. */
+ private translate(error: unknown, id: string): unknown {
+ if (error instanceof PrismaNamespace.PrismaClientKnownRequestError) {
+ if (error.code === "P2025") {
+ return new NotFoundException(`No company with id ${id}.`);
+ }
+ if (error.code === "P2002") {
+ return new ConflictException(
+ "Another company already uses that domain.",
+ );
+ }
+ }
+ return error;
+ }
+}
diff --git a/apps/api/src/companies/domain.ts b/apps/api/src/companies/domain.ts
new file mode 100644
index 00000000..2010c545
--- /dev/null
+++ b/apps/api/src/companies/domain.ts
@@ -0,0 +1,73 @@
+/**
+ * Reduces whatever a human typed to the bare host: "https://www.Stripe.com/pricing"
+ * → "stripe.com".
+ *
+ * `Company.domain` is unique and is the enrichment key, so the same company
+ * typed three ways has to collapse to one value — otherwise the constraint
+ * never fires and we pay Context.dev twice for the same lookup.
+ *
+ * Returns `null` for anything that is not plausibly a hostname, so a typo
+ * clears the field rather than creating a junk record that blocks the real one.
+ */
+export function normalizeDomain(
+ input: string | null | undefined,
+): string | null {
+ const trimmed = input?.trim().toLowerCase();
+ if (!trimmed) return null;
+
+ // `new URL` needs a scheme, and bare "stripe.com" is the common case.
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//.test(trimmed)
+ ? trimmed
+ : `https://${trimmed}`;
+
+ let host: string;
+ try {
+ host = new URL(withScheme).hostname;
+ } catch {
+ return null;
+ }
+
+ const bare = host.replace(/^www\./, "");
+
+ // At least one dot, and nothing but host characters — enough to reject
+ // "localhost", "my company" and a pasted email address.
+ return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(bare) ? bare : null;
+}
+
+/** The domain part of a work email, or `null` for a free or malformed address. */
+export function domainFromEmail(
+ email: string | null | undefined,
+): string | null {
+ const at = email?.trim().toLowerCase().lastIndexOf("@") ?? -1;
+ if (at < 1) return null;
+ const domain = normalizeDomain(email?.slice(at + 1));
+ return domain && !FREE_EMAIL_DOMAINS.has(domain) ? domain : null;
+}
+
+/**
+ * Addresses that say nothing about where someone works. Creating a "Gmail"
+ * company because a lead used a personal address is the classic CRM junk row.
+ */
+const FREE_EMAIL_DOMAINS = new Set([
+ "gmail.com",
+ "googlemail.com",
+ "yahoo.com",
+ "yahoo.co.uk",
+ "hotmail.com",
+ "hotmail.co.uk",
+ "outlook.com",
+ "live.com",
+ "msn.com",
+ "icloud.com",
+ "me.com",
+ "mac.com",
+ "aol.com",
+ "proton.me",
+ "protonmail.com",
+ "gmx.com",
+ "gmx.de",
+ "mail.com",
+ "yandex.ru",
+ "qq.com",
+ "163.com",
+]);
diff --git a/apps/api/src/config/env.validation.ts b/apps/api/src/config/env.validation.ts
new file mode 100644
index 00000000..f5ed930d
--- /dev/null
+++ b/apps/api/src/config/env.validation.ts
@@ -0,0 +1,108 @@
+import { plainToInstance, Type } from "class-transformer";
+import {
+ IsEnum,
+ IsInt,
+ IsOptional,
+ IsString,
+ IsUrl,
+ Max,
+ Min,
+ MinLength,
+ validateSync,
+} from "class-validator";
+
+export enum NodeEnv {
+ Development = "development",
+ Production = "production",
+ Test = "test",
+}
+
+export class EnvironmentVariables {
+ @IsEnum(NodeEnv)
+ NODE_ENV: NodeEnv = NodeEnv.Development;
+
+ @Type(() => Number)
+ @IsInt()
+ @Min(1)
+ @Max(65535)
+ PORT = 3001;
+
+ @IsString()
+ @MinLength(1)
+ DATABASE_URL!: string;
+
+ @IsString()
+ @MinLength(32, {
+ message:
+ "BETTER_AUTH_SECRET must be at least 32 characters (openssl rand -base64 32).",
+ })
+ BETTER_AUTH_SECRET!: string;
+
+ @IsUrl({ require_tld: false })
+ BETTER_AUTH_URL!: string;
+
+ @IsOptional()
+ @IsString()
+ AUTH_TRUSTED_ORIGINS?: string;
+
+ // Google is the only way in, so unlike @crm/auth — which stays loadable
+ // without credentials for `better-auth generate` — the process that serves
+ // the auth routes refuses to start without them.
+ @IsString()
+ @MinLength(1, {
+ message:
+ "GOOGLE_CLIENT_ID is required — Google is the only sign-in method. Create an OAuth client ID in the Google Cloud console.",
+ })
+ GOOGLE_CLIENT_ID!: string;
+
+ @IsString()
+ @MinLength(1, { message: "GOOGLE_CLIENT_SECRET is required." })
+ GOOGLE_CLIENT_SECRET!: string;
+
+ /** Parent domain for session cookies when the API and app differ. */
+ @IsOptional()
+ @IsString()
+ AUTH_COOKIE_DOMAIN?: string;
+
+ @IsOptional()
+ @IsString()
+ REDIS_URL?: string;
+
+ /**
+ * Context.dev, for company enrichment. Optional: without it the agent is
+ * disabled, a warning is logged once at boot, and companies stay `PENDING`.
+ * Server-side only — it never reaches the browser.
+ */
+ @IsOptional()
+ @IsString()
+ CONTEXT_DEV_API_KEY?: string;
+
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ CACHE_TTL_MS?: number;
+}
+
+export function validateEnv(
+ config: Record<string, unknown>,
+): EnvironmentVariables {
+ const validated = plainToInstance(EnvironmentVariables, config, {
+ enableImplicitConversion: true,
+ exposeDefaultValues: true,
+ });
+
+ const errors = validateSync(validated, {
+ skipMissingProperties: false,
+ whitelist: false,
+ });
+
+ if (errors.length > 0) {
+ const details = errors
+ .map((error) => Object.values(error.constraints ?? {}).join(", "))
+ .join("\n - ");
+ throw new Error(`Invalid environment configuration:\n - ${details}`);
+ }
+
+ return validated;
+}
diff --git a/apps/api/src/contacts/contacts.contracts.ts b/apps/api/src/contacts/contacts.contracts.ts
new file mode 100644
index 00000000..4219aca6
--- /dev/null
+++ b/apps/api/src/contacts/contacts.contracts.ts
@@ -0,0 +1,49 @@
+import { z } from "zod";
+import { listInput } from "../trpc/list-input";
+
+export const contactListInput = listInput.extend({
+ /** A user id, `"unassigned"`, or `"all"`. */
+ owner: z.string().default("all"),
+ /** A company id, `"none"`, or `"all"`. */
+ company: z.string().default("all"),
+});
+
+export type ContactListInput = z.infer<typeof contactListInput>;
+
+/**
+ * `email` is unique across the whole table, matching HubSpot, so an import can
+ * be re-run without duplicating people. It is optional because a name and a
+ * phone number is a real lead.
+ */
+export const contactCreateInput = z.object({
+ firstName: z.string().trim().min(1, "A contact needs a first name."),
+ lastName: z.string().trim().optional(),
+ email: z.email("That is not an email address.").optional().or(z.literal("")),
+ phone: z.string().trim().optional(),
+ title: z.string().trim().optional(),
+ companyId: z.string().nullable().optional(),
+ ownerId: z.string().nullable().optional(),
+});
+
+export type ContactCreateInput = z.infer<typeof contactCreateInput>;
+
+/** `undefined` leaves a field alone; `""` clears it. */
+export const contactUpdateInput = z.object({
+ firstName: z.string().trim().min(1).optional(),
+ lastName: z.string().optional(),
+ email: z.string().optional(),
+ phone: z.string().optional(),
+ title: z.string().optional(),
+ linkedinUrl: z.string().optional(),
+ companyId: z.string().nullable().optional(),
+ ownerId: z.string().nullable().optional(),
+});
+
+export type ContactUpdateInput = z.infer<typeof contactUpdateInput>;
+
+export const contactUpdateArgs = z.object({
+ id: z.string(),
+ data: contactUpdateInput,
+});
+
+export const contactIdInput = z.object({ id: z.string() });
diff --git a/apps/api/src/contacts/contacts.module.ts b/apps/api/src/contacts/contacts.module.ts
new file mode 100644
index 00000000..18f2f279
--- /dev/null
+++ b/apps/api/src/contacts/contacts.module.ts
@@ -0,0 +1,12 @@
+import { Module } from "@nestjs/common";
+import { EnrichmentModule } from "../enrichment/enrichment.module";
+import { TrpcModule } from "../trpc/trpc.module";
+import { ContactsRouter } from "./contacts.router";
+import { ContactsService } from "./contacts.service";
+
+@Module({
+ imports: [TrpcModule, EnrichmentModule],
+ providers: [ContactsService, ContactsRouter],
+ exports: [ContactsService],
+})
+export class ContactsModule {}
diff --git a/apps/api/src/contacts/contacts.router.ts b/apps/api/src/contacts/contacts.router.ts
new file mode 100644
index 00000000..b57d1853
--- /dev/null
+++ b/apps/api/src/contacts/contacts.router.ts
@@ -0,0 +1,44 @@
+import { Inject } from "@nestjs/common";
+import { Input, Mutation, Query, Router, UseMiddlewares } from "nestjs-trpc";
+import type { z } from "zod";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import {
+ contactCreateInput,
+ contactIdInput,
+ contactListInput,
+ contactUpdateArgs,
+} from "./contacts.contracts";
+import { ContactsService } from "./contacts.service";
+
+@Router({ alias: "contacts" })
+@UseMiddlewares(AuthMiddleware)
+export class ContactsRouter {
+ constructor(
+ @Inject(ContactsService) private readonly contacts: ContactsService,
+ ) {}
+
+ @Query({ input: contactListInput })
+ async list(@Input() input: z.infer<typeof contactListInput>) {
+ return this.contacts.list(input);
+ }
+
+ @Query({ input: contactIdInput })
+ async byId(@Input("id") id: string) {
+ return this.contacts.byId(id);
+ }
+
+ @Mutation({ input: contactCreateInput })
+ async create(@Input() input: z.infer<typeof contactCreateInput>) {
+ return this.contacts.create(input);
+ }
+
+ @Mutation({ input: contactUpdateArgs })
+ async update(@Input() input: z.infer<typeof contactUpdateArgs>) {
+ return this.contacts.update(input.id, input.data);
+ }
+
+ @Mutation({ input: contactIdInput })
+ async remove(@Input("id") id: string) {
+ return this.contacts.remove(id);
+ }
+}
diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.ts
new file mode 100644
index 00000000..6a0c4696
--- /dev/null
+++ b/apps/api/src/contacts/contacts.service.ts
@@ -0,0 +1,340 @@
+import { type Db, type Prisma, Prisma as PrismaNamespace } from "@crm/db";
+import {
+ ConflictException,
+ Injectable,
+ Logger,
+ NotFoundException,
+} from "@nestjs/common";
+import { blankToNull, toCents } from "../crm/values";
+import { InjectDatabase } from "../database/database.constants";
+import { EnrichmentService } from "../enrichment/enrichment.service";
+import {
+ countsByKey,
+ FACET_ALL,
+ FACET_UNASSIGNED,
+ type ListResult,
+ ownerFilter,
+ paginate,
+ resolveOrderBy,
+} from "../trpc/list-input";
+import type {
+ ContactCreateInput,
+ ContactListInput,
+ ContactUpdateInput,
+} from "./contacts.contracts";
+
+const OWNER_SELECT = {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+} as const;
+
+const COMPANY_SELECT = {
+ id: true,
+ name: true,
+ domain: true,
+ iconUrl: true,
+ logoUrl: true,
+} as const;
+
+/** The facet value for a contact who works nowhere we know of. */
+const NO_COMPANY = "none";
+
+export type ContactRow = {
+ id: string;
+ firstName: string;
+ lastName: string | null;
+ email: string | null;
+ title: string | null;
+ company: {
+ id: string;
+ name: string;
+ domain: string | null;
+ iconUrl: string | null;
+ logoUrl: string | null;
+ } | null;
+ owner: {
+ id: string;
+ name: string;
+ email: string;
+ image: string | null;
+ } | null;
+ lastActivityAt: string | null;
+};
+
+/**
+ * Orderings are arrays so every column can carry a tiebreak: without one,
+ * everybody at the same company comes back in whatever order Postgres feels
+ * like, and the order changes between pages of the same query.
+ */
+const SORTABLE: Record<
+ string,
+ (dir: Prisma.SortOrder) => Prisma.ContactOrderByWithRelationInput[]
+> = {
+ // Surname first — a list of people sorted by first name is a list nobody can
+ // scan.
+ name: (dir) => [{ lastName: dir }, { firstName: dir }],
+ email: (dir) => [{ email: dir }],
+ title: (dir) => [{ title: dir }, { lastName: "asc" }],
+ company: (dir) => [{ company: { name: dir } }, { lastName: "asc" }],
+ createdAt: (dir) => [{ createdAt: dir }],
+};
+
+@Injectable()
+export class ContactsService {
+ private readonly logger = new Logger(ContactsService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly enrichment: EnrichmentService,
+ ) {}
+
+ async list(input: ContactListInput): Promise<ListResult<ContactRow>> {
+ const where = this.buildWhere(input);
+ const { skip, take } = paginate(input);
+
+ const [rows, total, facetCounts] = await Promise.all([
+ this.db.contact.findMany({
+ where,
+ skip,
+ take,
+ orderBy: resolveOrderBy(input, SORTABLE, [
+ { lastName: "asc" },
+ { firstName: "asc" },
+ ]),
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ email: true,
+ title: true,
+ company: { select: COMPANY_SELECT },
+ owner: { select: OWNER_SELECT },
+ activities: {
+ take: 1,
+ orderBy: { createdAt: "desc" },
+ select: { createdAt: true },
+ },
+ },
+ }),
+ this.db.contact.count({ where }),
+ this.facetCounts(input),
+ ]);
+
+ return {
+ rows: rows.map(({ activities, ...row }) => ({
+ ...row,
+ lastActivityAt: activities[0]?.createdAt.toISOString() ?? null,
+ })),
+ total,
+ facetCounts,
+ };
+ }
+
+ async byId(id: string) {
+ const contact = await this.db.contact.findUnique({
+ where: { id },
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ email: true,
+ phone: true,
+ title: true,
+ linkedinUrl: true,
+ createdAt: true,
+ company: {
+ select: { ...COMPANY_SELECT, industry: true, primaryContactId: true },
+ },
+ owner: { select: OWNER_SELECT },
+ deals: {
+ select: {
+ role: true,
+ deal: {
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ amount: true,
+ currency: true,
+ expectedCloseDate: true,
+ owner: { select: OWNER_SELECT },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!contact) {
+ throw new NotFoundException(`No contact with id ${id}.`);
+ }
+
+ const { deals, createdAt, company, ...rest } = contact;
+
+ return {
+ ...rest,
+ company,
+ createdAt: createdAt.toISOString(),
+ /** True when this is the person to call at their company. */
+ isPrimaryContact: company?.primaryContactId === contact.id,
+ deals: deals.map(({ role, deal }) => ({
+ ...deal,
+ role,
+ amount: undefined,
+ amountCents: toCents(deal.amount),
+ expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,
+ })),
+ };
+ }
+
+ async create(input: ContactCreateInput) {
+ const email = blankToNull(input.email ?? "");
+
+ if (email) {
+ const existing = await this.db.contact.findUnique({
+ where: { email },
+ select: { id: true, firstName: true, lastName: true },
+ });
+ if (existing) {
+ throw new ConflictException(
+ `${[existing.firstName, existing.lastName].filter(Boolean).join(" ")} already uses ${email}.`,
+ );
+ }
+ }
+
+ // A work address tells us where someone works. Awaited rather than queued,
+ // unlike company enrichment: the contact should arrive already attached to
+ // the right company, not attach itself a few seconds later.
+ const companyId =
+ input.companyId ??
+ (email ? await this.enrichment.companyForEmail(email) : null);
+
+ const contact = await this.db.contact.create({
+ data: {
+ firstName: input.firstName.trim(),
+ lastName: blankToNull(input.lastName ?? ""),
+ email,
+ phone: blankToNull(input.phone ?? ""),
+ title: blankToNull(input.title ?? ""),
+ companyId,
+ ownerId: input.ownerId ?? null,
+ },
+ select: { id: true, firstName: true, lastName: true },
+ });
+
+ this.logger.log({ message: "Contact created", contactId: contact.id });
+
+ return contact;
+ }
+
+ async update(id: string, input: ContactUpdateInput) {
+ const data: Prisma.ContactUpdateInput = {};
+
+ if (input.firstName !== undefined) data.firstName = input.firstName.trim();
+ if (input.lastName !== undefined)
+ data.lastName = blankToNull(input.lastName);
+ if (input.email !== undefined) data.email = blankToNull(input.email);
+ if (input.phone !== undefined) data.phone = blankToNull(input.phone);
+ if (input.title !== undefined) data.title = blankToNull(input.title);
+ if (input.linkedinUrl !== undefined) {
+ data.linkedinUrl = blankToNull(input.linkedinUrl);
+ }
+ if (input.companyId !== undefined) {
+ data.company = input.companyId
+ ? { connect: { id: input.companyId } }
+ : { disconnect: true };
+ }
+ if (input.ownerId !== undefined) {
+ data.owner = input.ownerId
+ ? { connect: { id: input.ownerId } }
+ : { disconnect: true };
+ }
+
+ try {
+ return await this.db.contact.update({
+ where: { id },
+ data,
+ select: { id: true, firstName: true, lastName: true },
+ });
+ } catch (error) {
+ throw this.translate(error, id);
+ }
+ }
+
+ async remove(id: string): Promise<{ id: string }> {
+ try {
+ await this.db.contact.delete({ where: { id } });
+ } catch (error) {
+ throw this.translate(error, id);
+ }
+ this.logger.log({ message: "Contact deleted", contactId: id });
+ return { id };
+ }
+
+ /** `q` matches a name, an email address, or where they work. */
+ private searchFilter(q: string): Prisma.ContactWhereInput {
+ const term = q.trim();
+ if (!term) return {};
+
+ return {
+ OR: [
+ { firstName: { contains: term, mode: "insensitive" } },
+ { lastName: { contains: term, mode: "insensitive" } },
+ { email: { contains: term, mode: "insensitive" } },
+ { company: { name: { contains: term, mode: "insensitive" } } },
+ ],
+ };
+ }
+
+ private buildWhere(input: ContactListInput): Prisma.ContactWhereInput {
+ const where: Prisma.ContactWhereInput = {
+ ...this.searchFilter(input.q),
+ ...ownerFilter(input.owner),
+ };
+
+ if (input.company !== FACET_ALL) {
+ where.companyId = input.company === NO_COMPANY ? null : input.company;
+ }
+
+ return where;
+ }
+
+ /** Counts against the search term only — see `CompaniesService.facetCounts`. */
+ private async facetCounts(input: ContactListInput) {
+ const where = this.searchFilter(input.q);
+
+ const [owners, companies] = await Promise.all([
+ this.db.contact.groupBy({
+ by: ["ownerId"],
+ where,
+ _count: { _all: true },
+ }),
+ this.db.contact.groupBy({
+ by: ["companyId"],
+ where,
+ _count: { _all: true },
+ }),
+ ]);
+
+ return {
+ owner: countsByKey(owners, "ownerId", FACET_UNASSIGNED),
+ company: countsByKey(companies, "companyId", NO_COMPANY),
+ };
+ }
+
+ private translate(error: unknown, id: string): unknown {
+ if (error instanceof PrismaNamespace.PrismaClientKnownRequestError) {
+ if (error.code === "P2025") {
+ return new NotFoundException(`No contact with id ${id}.`);
+ }
+ if (error.code === "P2002") {
+ return new ConflictException(
+ "Another contact already uses that email address.",
+ );
+ }
+ }
+ return error;
+ }
+}
diff --git a/apps/api/src/crm/values.ts b/apps/api/src/crm/values.ts
new file mode 100644
index 00000000..3a999660
--- /dev/null
+++ b/apps/api/src/crm/values.ts
@@ -0,0 +1,30 @@
+import type { Prisma } from "@crm/db";
+
+/**
+ * Money crosses the wire as integer cents.
+ *
+ * Prisma's `Decimal` has no JSON representation, and a float would make summing
+ * a pipeline lossy. Cents are exact integers well inside
+ * `Number.MAX_SAFE_INTEGER` for anything `Decimal(14, 2)` can hold, and
+ * `formatMoney` in `@crm/ui` already takes them.
+ */
+export function toCents(amount: Prisma.Decimal | null): number | null {
+ return amount === null ? null : amount.times(100).toNumber();
+}
+
+/** Cents back to the column's scale, for a write. */
+export function fromCents(cents: number | null | undefined): number | null {
+ return cents === null || cents === undefined ? null : cents / 100;
+}
+
+/**
+ * `""` means "clear this", `" x "` means `"x"`.
+ *
+ * Inline editors send whatever is in the box, and storing an empty string would
+ * make "no phone number" and "a phone number that is blank" two different
+ * states that render identically.
+ */
+export function blankToNull(value: string): string | null {
+ const trimmed = value.trim();
+ return trimmed === "" ? null : trimmed;
+}
diff --git a/apps/api/src/dashboard/dashboard.module.ts b/apps/api/src/dashboard/dashboard.module.ts
new file mode 100644
index 00000000..8150e508
--- /dev/null
+++ b/apps/api/src/dashboard/dashboard.module.ts
@@ -0,0 +1,10 @@
+import { Module } from "@nestjs/common";
+import { TrpcModule } from "../trpc/trpc.module";
+import { DashboardRouter } from "./dashboard.router";
+import { DashboardService } from "./dashboard.service";
+
+@Module({
+ imports: [TrpcModule],
+ providers: [DashboardService, DashboardRouter],
+})
+export class DashboardModule {}
diff --git a/apps/api/src/dashboard/dashboard.router.ts b/apps/api/src/dashboard/dashboard.router.ts
new file mode 100644
index 00000000..856c485a
--- /dev/null
+++ b/apps/api/src/dashboard/dashboard.router.ts
@@ -0,0 +1,19 @@
+import { Inject } from "@nestjs/common";
+import { Ctx, Query, Router, UseMiddlewares } from "nestjs-trpc";
+import type { AuthedTrpcContext } from "../trpc/context.types";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { DashboardService } from "./dashboard.service";
+
+@Router({ alias: "dashboard" })
+@UseMiddlewares(AuthMiddleware)
+export class DashboardRouter {
+ constructor(
+ @Inject(DashboardService) private readonly dashboard: DashboardService,
+ ) {}
+
+ /** Pipeline by stage, deals closing this month, my overdue tasks, recent activity. */
+ @Query()
+ async summary(@Ctx() ctx: AuthedTrpcContext) {
+ return this.dashboard.summary(ctx.user.id);
+ }
+}
diff --git a/apps/api/src/dashboard/dashboard.service.ts b/apps/api/src/dashboard/dashboard.service.ts
new file mode 100644
index 00000000..f392aa8c
--- /dev/null
+++ b/apps/api/src/dashboard/dashboard.service.ts
@@ -0,0 +1,143 @@
+import { ActivityType, type Db, type DealStage } from "@crm/db";
+import { Injectable } from "@nestjs/common";
+import { toCents } from "../crm/values";
+import { InjectDatabase } from "../database/database.constants";
+import { OPEN_DEAL_STAGES } from "../deals/deal-stage";
+
+const OWNER_SELECT = {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+} as const;
+
+@Injectable()
+export class DashboardService {
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ /**
+ * What a rep wants on opening the app: where the pipeline is, what closes
+ * this month, what they are late on, and what just happened.
+ *
+ * Everything is aggregated in Postgres. The alternative — fetching deals and
+ * summing them here — is a page that gets slower every quarter.
+ */
+ async summary(actingUserId: string) {
+ const now = new Date();
+ const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
+ const startOfNextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
+
+ const [
+ byStage,
+ closingThisMonth,
+ overdueTasks,
+ recentActivity,
+ wonThisMonth,
+ ] = await Promise.all([
+ this.db.deal.groupBy({
+ by: ["stage"],
+ where: { stage: { in: [...OPEN_DEAL_STAGES] } },
+ _count: { _all: true },
+ _sum: { amount: true },
+ }),
+ this.db.deal.findMany({
+ where: {
+ stage: { in: [...OPEN_DEAL_STAGES] },
+ expectedCloseDate: { gte: startOfMonth, lt: startOfNextMonth },
+ },
+ orderBy: [{ expectedCloseDate: "asc" }],
+ take: 10,
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ amount: true,
+ currency: true,
+ expectedCloseDate: true,
+ company: { select: { id: true, name: true, iconUrl: true } },
+ owner: { select: OWNER_SELECT },
+ },
+ }),
+ this.db.activity.findMany({
+ where: {
+ type: ActivityType.TASK,
+ completedAt: null,
+ dueAt: { lt: now },
+ createdById: actingUserId,
+ },
+ orderBy: [{ dueAt: "asc" }],
+ take: 10,
+ select: {
+ id: true,
+ subject: true,
+ dueAt: true,
+ company: { select: { id: true, name: true } },
+ deal: { select: { id: true, name: true } },
+ },
+ }),
+ this.db.activity.findMany({
+ orderBy: [{ createdAt: "desc" }],
+ take: 12,
+ select: {
+ id: true,
+ type: true,
+ subject: true,
+ body: true,
+ createdAt: true,
+ meta: true,
+ createdBy: { select: OWNER_SELECT },
+ company: { select: { id: true, name: true } },
+ deal: { select: { id: true, name: true } },
+ },
+ }),
+ this.db.deal.aggregate({
+ where: {
+ stage: "CLOSED_WON",
+ closedAt: { gte: startOfMonth, lt: startOfNextMonth },
+ },
+ _count: { _all: true },
+ _sum: { amount: true },
+ }),
+ ]);
+
+ const stages = OPEN_DEAL_STAGES.map((stage) => {
+ const group = byStage.find((row) => row.stage === stage);
+ return {
+ stage: stage as DealStage,
+ count: group?._count._all ?? 0,
+ valueCents: toCents(group?._sum.amount ?? null) ?? 0,
+ };
+ });
+
+ return {
+ pipeline: {
+ stages,
+ totalCents: stages.reduce(
+ (total, stage) => total + stage.valueCents,
+ 0,
+ ),
+ totalDeals: stages.reduce((total, stage) => total + stage.count, 0),
+ },
+ wonThisMonth: {
+ count: wonThisMonth._count._all,
+ valueCents: toCents(wonThisMonth._sum.amount) ?? 0,
+ },
+ closingThisMonth: closingThisMonth.map(
+ ({ amount, expectedCloseDate, ...deal }) => ({
+ ...deal,
+ amountCents: toCents(amount),
+ expectedCloseDate: expectedCloseDate?.toISOString() ?? null,
+ }),
+ ),
+ overdueTasks: overdueTasks.map(({ dueAt, ...task }) => ({
+ ...task,
+ dueAt: dueAt?.toISOString() ?? null,
+ })),
+ recentActivity: recentActivity.map(({ createdAt, meta, ...entry }) => ({
+ ...entry,
+ createdAt: createdAt.toISOString(),
+ meta: meta as Record<string, unknown> | null,
+ })),
+ };
+ }
+}
diff --git a/apps/api/src/database/database.constants.ts b/apps/api/src/database/database.constants.ts
new file mode 100644
index 00000000..49ff962b
--- /dev/null
+++ b/apps/api/src/database/database.constants.ts
@@ -0,0 +1,5 @@
+import { Inject } from "@nestjs/common";
+
+export const DATABASE = Symbol("DATABASE");
+
+export const InjectDatabase = () => Inject(DATABASE);
diff --git a/apps/api/src/database/database.module.ts b/apps/api/src/database/database.module.ts
new file mode 100644
index 00000000..63bf1a68
--- /dev/null
+++ b/apps/api/src/database/database.module.ts
@@ -0,0 +1,43 @@
+import { type Db, db } from "@crm/db";
+import {
+ Global,
+ Logger,
+ Module,
+ type OnApplicationShutdown,
+ type OnModuleInit,
+} from "@nestjs/common";
+import { DATABASE, InjectDatabase } from "./database.constants";
+
+@Global()
+@Module({
+ providers: [{ provide: DATABASE, useValue: db }],
+ exports: [DATABASE],
+})
+export class DatabaseModule implements OnModuleInit, OnApplicationShutdown {
+ private readonly logger = new Logger(DatabaseModule.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ /**
+ * Prisma connects lazily on first query, which turns a bad `DATABASE_URL`
+ * into a confusing 500 on some unrelated endpoint. Connecting at startup
+ * fails the boot instead.
+ */
+ async onModuleInit(): Promise<void> {
+ try {
+ await this.db.$connect();
+ this.logger.log({ message: "Database connected" });
+ } catch (error) {
+ this.logger.fatal(
+ { message: "Database connection failed" },
+ error instanceof Error ? error.stack : String(error),
+ );
+ throw error;
+ }
+ }
+
+ async onApplicationShutdown(signal?: string): Promise<void> {
+ await this.db.$disconnect();
+ this.logger.log({ message: "Database disconnected", signal });
+ }
+}
diff --git a/apps/api/src/deals/deal-stage.ts b/apps/api/src/deals/deal-stage.ts
new file mode 100644
index 00000000..9be10ca1
--- /dev/null
+++ b/apps/api/src/deals/deal-stage.ts
@@ -0,0 +1,39 @@
+import { DealStage } from "@crm/db";
+
+/**
+ * Stages a deal can still be won from. Pipeline value and the forecast are the
+ * sum over these.
+ */
+export const OPEN_DEAL_STAGES = [
+ DealStage.DEMO_BOOKED,
+ DealStage.QUALIFIED_TO_BUY,
+ DealStage.DECISION_MAKER_BOUGHT_IN,
+ DealStage.CONTRACT_SENT,
+] as const;
+
+/**
+ * Stages a deal is finished in. `UNQUALIFIED_TO_BUY` belongs here rather than
+ * mid-funnel: it is a disqualification, not a step forward, and counting it as
+ * open would inflate the pipeline with deals nobody is working.
+ */
+export const CLOSED_DEAL_STAGES = [
+ DealStage.CLOSED_WON,
+ DealStage.CLOSED_LOST,
+ DealStage.UNQUALIFIED_TO_BUY,
+] as const;
+
+/** Closed stages that need a reason typed in. */
+export const LOSING_DEAL_STAGES = [
+ DealStage.CLOSED_LOST,
+ DealStage.UNQUALIFIED_TO_BUY,
+] as const;
+
+const CLOSED = new Set<DealStage>(CLOSED_DEAL_STAGES);
+
+export function isClosedStage(stage: DealStage): boolean {
+ return CLOSED.has(stage);
+}
+
+export function isOpenStage(stage: DealStage): boolean {
+ return !CLOSED.has(stage);
+}
diff --git a/apps/api/src/deals/deals.board.ts b/apps/api/src/deals/deals.board.ts
new file mode 100644
index 00000000..fdb795d7
--- /dev/null
+++ b/apps/api/src/deals/deals.board.ts
@@ -0,0 +1,18 @@
+import { z } from "zod";
+
+/**
+ * The board shows the open pipeline only.
+ *
+ * A closed column would be an ever-growing list of things nobody is working,
+ * and dragging a card into it needs a reason typed in — which is a dialog, not
+ * a drop target. Closing happens from the row menu or the deal page.
+ */
+export const boardInput = z.object({
+ q: z.string().default(""),
+ /** A user id, or `"all"`. */
+ owner: z.string().default("all"),
+ /** Cards per column. The count is always the true total. */
+ limit: z.number().int().min(1).max(100).default(50),
+});
+
+export type BoardInput = z.infer<typeof boardInput>;
diff --git a/apps/api/src/deals/deals.contracts.ts b/apps/api/src/deals/deals.contracts.ts
new file mode 100644
index 00000000..14bc65b3
--- /dev/null
+++ b/apps/api/src/deals/deals.contracts.ts
@@ -0,0 +1,95 @@
+import { DealStage } from "@crm/db";
+import { z } from "zod";
+import { listInput } from "../trpc/list-input";
+
+/** Buckets for the "closing" facet. */
+export const CLOSING_WINDOWS = [
+ "overdue",
+ "this-month",
+ "next-month",
+ "later",
+ "none",
+] as const;
+
+export type ClosingWindow = (typeof CLOSING_WINDOWS)[number];
+
+export const dealListInput = listInput.extend({
+ /**
+ * The tab: `"open"`, `"closed"` or `"all"`.
+ *
+ * Open and closed rather than one tab per stage — a rep wants "what am I
+ * working" and "what happened", and the stage facet covers the rest.
+ */
+ status: z.string().default("all"),
+ /**
+ * A user id, or `"all"`. `"unassigned"` is accepted so every list speaks the
+ * same facet language, but a deal always has an owner, so it matches nothing.
+ */
+ owner: z.string().default("all"),
+ /** A `DealStage`, or `"all"`. */
+ stage: z.string().default("all"),
+ /** A `ClosingWindow`, or `"all"`. */
+ closing: z.string().default("all"),
+});
+
+export type DealListInput = z.infer<typeof dealListInput>;
+
+const stageEnum = z.enum(
+ Object.values(DealStage) as [DealStage, ...DealStage[]],
+);
+
+export const dealCreateInput = z.object({
+ name: z.string().trim().min(1, "A deal needs a name."),
+ companyId: z.string().min(1, "A deal belongs to a company."),
+ /** Required — every deal has a name against it. */
+ ownerId: z.string().min(1, "A deal needs an owner."),
+ stage: stageEnum.optional(),
+ /** Integer cents, so summing a pipeline is exact. */
+ amountCents: z.number().int().min(0).nullable().optional(),
+ currency: z.string().length(3).optional(),
+ /** ISO-8601 date. */
+ expectedCloseDate: z.string().nullable().optional(),
+});
+
+export type DealCreateInput = z.infer<typeof dealCreateInput>;
+
+/** `undefined` leaves a field alone. Stage is not here — it goes through
+ * `setStage`, which also writes the timeline entry. */
+export const dealUpdateInput = z.object({
+ name: z.string().trim().min(1).optional(),
+ companyId: z.string().optional(),
+ ownerId: z.string().optional(),
+ amountCents: z.number().int().min(0).nullable().optional(),
+ currency: z.string().length(3).optional(),
+ expectedCloseDate: z.string().nullable().optional(),
+});
+
+export type DealUpdateInput = z.infer<typeof dealUpdateInput>;
+
+export const dealUpdateArgs = z.object({
+ id: z.string(),
+ data: dealUpdateInput,
+});
+
+export const dealIdInput = z.object({ id: z.string() });
+
+export const setStageInput = z.object({
+ id: z.string(),
+ stage: stageEnum,
+ /** Why it was lost or disqualified. Required for the losing stages. */
+ closedReason: z.string().trim().optional(),
+});
+
+export type SetStageInput = z.infer<typeof setStageInput>;
+
+export const setContactsInput = z.object({
+ dealId: z.string(),
+ contacts: z.array(
+ z.object({
+ contactId: z.string(),
+ role: z.string().trim().optional(),
+ }),
+ ),
+});
+
+export type SetContactsInput = z.infer<typeof setContactsInput>;
diff --git a/apps/api/src/deals/deals.module.ts b/apps/api/src/deals/deals.module.ts
new file mode 100644
index 00000000..f35cf882
--- /dev/null
+++ b/apps/api/src/deals/deals.module.ts
@@ -0,0 +1,11 @@
+import { Module } from "@nestjs/common";
+import { TrpcModule } from "../trpc/trpc.module";
+import { DealsRouter } from "./deals.router";
+import { DealsService } from "./deals.service";
+
+@Module({
+ imports: [TrpcModule],
+ providers: [DealsService, DealsRouter],
+ exports: [DealsService],
+})
+export class DealsModule {}
diff --git a/apps/api/src/deals/deals.router.ts b/apps/api/src/deals/deals.router.ts
new file mode 100644
index 00000000..20ecf83f
--- /dev/null
+++ b/apps/api/src/deals/deals.router.ts
@@ -0,0 +1,73 @@
+import { Inject } from "@nestjs/common";
+import {
+ Ctx,
+ Input,
+ Mutation,
+ Query,
+ Router,
+ UseMiddlewares,
+} from "nestjs-trpc";
+import type { z } from "zod";
+import type { AuthedTrpcContext } from "../trpc/context.types";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { boardInput } from "./deals.board";
+import {
+ dealCreateInput,
+ dealIdInput,
+ dealListInput,
+ dealUpdateArgs,
+ setContactsInput,
+ setStageInput,
+} from "./deals.contracts";
+import { DealsService } from "./deals.service";
+
+@Router({ alias: "deals" })
+@UseMiddlewares(AuthMiddleware)
+export class DealsRouter {
+ constructor(@Inject(DealsService) private readonly deals: DealsService) {}
+
+ @Query({ input: dealListInput })
+ async list(@Input() input: z.infer<typeof dealListInput>) {
+ return this.deals.list(input);
+ }
+
+ /** The open pipeline as stage columns, for `?view=board`. */
+ @Query({ input: boardInput })
+ async board(@Input() input: z.infer<typeof boardInput>) {
+ return this.deals.board(input);
+ }
+
+ @Query({ input: dealIdInput })
+ async byId(@Input("id") id: string) {
+ return this.deals.byId(id);
+ }
+
+ @Mutation({ input: dealCreateInput })
+ async create(@Input() input: z.infer<typeof dealCreateInput>) {
+ return this.deals.create(input);
+ }
+
+ @Mutation({ input: dealUpdateArgs })
+ async update(@Input() input: z.infer<typeof dealUpdateArgs>) {
+ return this.deals.update(input.id, input.data);
+ }
+
+ /** Moves the deal and writes the `STAGE_CHANGE` activity in one transaction. */
+ @Mutation({ input: setStageInput })
+ async setStage(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof setStageInput>,
+ ) {
+ return this.deals.setStage(input, ctx.user.id);
+ }
+
+ @Mutation({ input: setContactsInput })
+ async setContacts(@Input() input: z.infer<typeof setContactsInput>) {
+ return this.deals.setContacts(input);
+ }
+
+ @Mutation({ input: dealIdInput })
+ async remove(@Input("id") id: string) {
+ return this.deals.remove(id);
+ }
+}
diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.ts
new file mode 100644
index 00000000..32b572ba
--- /dev/null
+++ b/apps/api/src/deals/deals.service.ts
@@ -0,0 +1,567 @@
+import {
+ ActivityType,
+ type Db,
+ type DealStage,
+ type Prisma,
+ Prisma as PrismaNamespace,
+} from "@crm/db";
+import {
+ BadRequestException,
+ Injectable,
+ Logger,
+ NotFoundException,
+} from "@nestjs/common";
+import { fromCents, toCents } from "../crm/values";
+import { InjectDatabase } from "../database/database.constants";
+import {
+ countsByKey,
+ FACET_ALL,
+ FACET_UNASSIGNED,
+ type ListResult,
+ paginate,
+ resolveOrderBy,
+} from "../trpc/list-input";
+import {
+ CLOSED_DEAL_STAGES,
+ isClosedStage,
+ LOSING_DEAL_STAGES,
+ OPEN_DEAL_STAGES,
+} from "./deal-stage";
+import type { BoardInput } from "./deals.board";
+import type {
+ ClosingWindow,
+ DealCreateInput,
+ DealListInput,
+ DealUpdateInput,
+ SetContactsInput,
+ SetStageInput,
+} from "./deals.contracts";
+import { CLOSING_WINDOWS } from "./deals.contracts";
+
+const OWNER_SELECT = {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+} as const;
+
+const COMPANY_SELECT = {
+ id: true,
+ name: true,
+ domain: true,
+ iconUrl: true,
+} as const;
+
+const LOSING = new Set<DealStage>(LOSING_DEAL_STAGES);
+
+const SORTABLE: Record<
+ string,
+ (dir: Prisma.SortOrder) => Prisma.DealOrderByWithRelationInput[]
+> = {
+ name: (dir) => [{ name: dir }],
+ company: (dir) => [{ company: { name: dir } }, { name: "asc" }],
+ // Enum order is declaration order in Postgres, which is pipeline order — so
+ // sorting by stage reads as "how far along", not alphabetically.
+ stage: (dir) => [{ stage: dir }, { expectedCloseDate: "asc" }],
+ amount: (dir) => [{ amount: dir }],
+ expectedCloseDate: (dir) => [{ expectedCloseDate: dir }],
+ createdAt: (dir) => [{ createdAt: dir }],
+};
+
+@Injectable()
+export class DealsService {
+ private readonly logger = new Logger(DealsService.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async list(input: DealListInput) {
+ const where = this.buildWhere(input);
+ const { skip, take } = paginate(input);
+
+ const [rows, total, facetCounts, openValue] = await Promise.all([
+ this.db.deal.findMany({
+ where,
+ skip,
+ take,
+ orderBy: resolveOrderBy(input, SORTABLE, [
+ { stage: "asc" },
+ { expectedCloseDate: "asc" },
+ ]),
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ amount: true,
+ currency: true,
+ expectedCloseDate: true,
+ closedAt: true,
+ company: { select: COMPANY_SELECT },
+ owner: { select: OWNER_SELECT },
+ activities: {
+ take: 1,
+ orderBy: { createdAt: "desc" },
+ select: { createdAt: true },
+ },
+ },
+ }),
+ this.db.deal.count({ where }),
+ this.facetCounts(input),
+ // Summed in Postgres over the *filtered* set, not the page: a footer
+ // that says "$1.2M" for the 25 rows you can see is worse than no
+ // number at all.
+ this.db.deal.aggregate({
+ where: { ...where, stage: { in: [...OPEN_DEAL_STAGES] } },
+ _sum: { amount: true },
+ }),
+ ]);
+
+ return {
+ rows: rows.map(
+ ({ activities, amount, expectedCloseDate, closedAt, ...row }) => ({
+ ...row,
+ amountCents: toCents(amount),
+ expectedCloseDate: expectedCloseDate?.toISOString() ?? null,
+ closedAt: closedAt?.toISOString() ?? null,
+ lastActivityAt: activities[0]?.createdAt.toISOString() ?? null,
+ }),
+ ),
+ total,
+ facetCounts,
+ /** Open pipeline value across everything matching the filters. */
+ openValueCents: toCents(openValue._sum.amount),
+ } satisfies ListResult<unknown> & { openValueCents: number | null };
+ }
+
+ /**
+ * The pipeline as columns.
+ *
+ * One query, grouped in memory rather than four round trips: the open
+ * pipeline is small by construction, and a board that issues a query per
+ * column gets slower every time someone adds a stage.
+ */
+ async board(input: BoardInput) {
+ const where: Prisma.DealWhereInput = {
+ ...this.searchFilter(input.q),
+ stage: { in: [...OPEN_DEAL_STAGES] },
+ };
+
+ if (input.owner !== FACET_ALL) {
+ where.ownerId = input.owner;
+ }
+
+ const [deals, totals] = await Promise.all([
+ this.db.deal.findMany({
+ where,
+ orderBy: [
+ { stage: "asc" },
+ { expectedCloseDate: "asc" },
+ { name: "asc" },
+ ],
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ amount: true,
+ currency: true,
+ expectedCloseDate: true,
+ company: { select: COMPANY_SELECT },
+ owner: { select: OWNER_SELECT },
+ },
+ }),
+ this.db.deal.groupBy({
+ by: ["stage"],
+ where,
+ _count: { _all: true },
+ _sum: { amount: true },
+ }),
+ ]);
+
+ const columns = OPEN_DEAL_STAGES.map((stage) => {
+ const group = totals.find((row) => row.stage === stage);
+ const cards = deals
+ .filter((deal) => deal.stage === stage)
+ .slice(0, input.limit)
+ .map(({ amount, expectedCloseDate, ...deal }) => ({
+ ...deal,
+ amountCents: toCents(amount),
+ expectedCloseDate: expectedCloseDate?.toISOString() ?? null,
+ }));
+
+ return {
+ stage,
+ cards,
+ /** The whole column, even when only `limit` cards are shown. */
+ total: group?._count._all ?? 0,
+ valueCents: toCents(group?._sum.amount ?? null) ?? 0,
+ };
+ });
+
+ return { columns };
+ }
+
+ async byId(id: string) {
+ const deal = await this.db.deal.findUnique({
+ where: { id },
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ stageChangedAt: true,
+ amount: true,
+ currency: true,
+ expectedCloseDate: true,
+ closedAt: true,
+ closedReason: true,
+ createdAt: true,
+ company: { select: { ...COMPANY_SELECT, industry: true } },
+ owner: { select: OWNER_SELECT },
+ contacts: {
+ select: {
+ role: true,
+ contact: {
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ email: true,
+ title: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!deal) {
+ throw new NotFoundException(`No deal with id ${id}.`);
+ }
+
+ const { contacts, amount, ...rest } = deal;
+
+ return {
+ ...rest,
+ amountCents: toCents(amount),
+ stageChangedAt: deal.stageChangedAt.toISOString(),
+ expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,
+ closedAt: deal.closedAt?.toISOString() ?? null,
+ createdAt: deal.createdAt.toISOString(),
+ contacts: contacts.map(({ role, contact }) => ({ ...contact, role })),
+ };
+ }
+
+ async create(input: DealCreateInput) {
+ const stage = input.stage ?? "DEMO_BOOKED";
+ const closed = isClosedStage(stage);
+ const now = new Date();
+
+ try {
+ const deal = await this.db.deal.create({
+ data: {
+ name: input.name.trim(),
+ companyId: input.companyId,
+ ownerId: input.ownerId,
+ stage,
+ stageChangedAt: now,
+ closedAt: closed ? now : null,
+ amount: fromCents(input.amountCents),
+ currency: input.currency ?? "USD",
+ expectedCloseDate: parseDate(input.expectedCloseDate),
+ },
+ select: { id: true, name: true, companyId: true },
+ });
+
+ this.logger.log({ message: "Deal created", dealId: deal.id, stage });
+
+ return deal;
+ } catch (error) {
+ throw this.translateRelations(error);
+ }
+ }
+
+ async update(id: string, input: DealUpdateInput) {
+ const data: Prisma.DealUpdateInput = {};
+
+ if (input.name !== undefined) data.name = input.name.trim();
+ if (input.companyId !== undefined) {
+ data.company = { connect: { id: input.companyId } };
+ }
+ if (input.ownerId !== undefined) {
+ data.owner = { connect: { id: input.ownerId } };
+ }
+ if (input.amountCents !== undefined) {
+ data.amount = fromCents(input.amountCents);
+ }
+ if (input.currency !== undefined) data.currency = input.currency;
+ if (input.expectedCloseDate !== undefined) {
+ data.expectedCloseDate = parseDate(input.expectedCloseDate);
+ }
+
+ try {
+ return await this.db.deal.update({
+ where: { id },
+ data,
+ select: { id: true, name: true },
+ });
+ } catch (error) {
+ throw this.translate(error, id);
+ }
+ }
+
+ /**
+ * Moves a deal and records that it moved.
+ *
+ * One transaction, because a stage change with no timeline entry is a deal
+ * nobody can explain a week later — and a timeline entry for a change that
+ * did not commit is worse.
+ */
+ async setStage(input: SetStageInput, actingUserId: string) {
+ const deal = await this.db.deal.findUnique({
+ where: { id: input.id },
+ select: { id: true, stage: true, companyId: true },
+ });
+
+ if (!deal) {
+ throw new NotFoundException(`No deal with id ${input.id}.`);
+ }
+
+ if (deal.stage === input.stage) {
+ return { id: deal.id, stage: deal.stage, changed: false };
+ }
+
+ const closedReason = input.closedReason?.trim();
+ if (LOSING.has(input.stage) && !closedReason) {
+ throw new BadRequestException(
+ "Say why it was lost — a closed-lost deal with no reason teaches nobody anything.",
+ );
+ }
+
+ const now = new Date();
+ const closed = isClosedStage(input.stage);
+
+ const [updated] = await this.db.$transaction([
+ this.db.deal.update({
+ where: { id: input.id },
+ data: {
+ stage: input.stage,
+ stageChangedAt: now,
+ closedAt: closed ? now : null,
+ closedReason: closed ? (closedReason ?? null) : null,
+ },
+ select: { id: true, stage: true },
+ }),
+ this.db.activity.create({
+ data: {
+ type: ActivityType.STAGE_CHANGE,
+ subject: "Stage changed",
+ body: closedReason ?? null,
+ occurredAt: now,
+ // Stamped with the company as well as the deal, so this shows on
+ // the company timeline without a join.
+ companyId: deal.companyId,
+ dealId: deal.id,
+ createdById: actingUserId,
+ meta: { from: deal.stage, to: input.stage },
+ },
+ }),
+ ]);
+
+ this.logger.log({
+ message: "Deal stage changed",
+ dealId: deal.id,
+ from: deal.stage,
+ to: input.stage,
+ });
+
+ return { ...updated, changed: true };
+ }
+
+ /** Replaces the people on a deal wholesale — the UI edits the whole set. */
+ async setContacts(input: SetContactsInput) {
+ const deal = await this.db.deal.findUnique({
+ where: { id: input.dealId },
+ select: { companyId: true },
+ });
+
+ if (!deal) {
+ throw new NotFoundException(`No deal with id ${input.dealId}.`);
+ }
+
+ const contactIds = [...new Set(input.contacts.map((c) => c.contactId))];
+
+ if (contactIds.length > 0) {
+ const belong = await this.db.contact.count({
+ where: { id: { in: contactIds }, companyId: deal.companyId },
+ });
+ if (belong !== contactIds.length) {
+ throw new BadRequestException(
+ "Every contact on a deal has to work at the company the deal is with.",
+ );
+ }
+ }
+
+ await this.db.$transaction([
+ this.db.dealContact.deleteMany({ where: { dealId: input.dealId } }),
+ this.db.dealContact.createMany({
+ data: input.contacts.map((contact) => ({
+ dealId: input.dealId,
+ contactId: contact.contactId,
+ role: contact.role || null,
+ })),
+ skipDuplicates: true,
+ }),
+ ]);
+
+ return { dealId: input.dealId, count: contactIds.length };
+ }
+
+ async remove(id: string): Promise<{ id: string }> {
+ try {
+ await this.db.deal.delete({ where: { id } });
+ } catch (error) {
+ throw this.translate(error, id);
+ }
+ this.logger.log({ message: "Deal deleted", dealId: id });
+ return { id };
+ }
+
+ private searchFilter(q: string): Prisma.DealWhereInput {
+ const term = q.trim();
+ if (!term) return {};
+
+ return {
+ OR: [
+ { name: { contains: term, mode: "insensitive" } },
+ { company: { name: { contains: term, mode: "insensitive" } } },
+ ],
+ };
+ }
+
+ private buildWhere(input: DealListInput): Prisma.DealWhereInput {
+ const where: Prisma.DealWhereInput = this.searchFilter(input.q);
+
+ if (input.owner !== FACET_ALL) {
+ // `Deal.ownerId` is required, so unlike companies and contacts there is
+ // no null to match — "unassigned" is a filter that can only ever be
+ // empty, and `in: []` says that in Prisma's own terms.
+ where.ownerId =
+ input.owner === FACET_UNASSIGNED ? { in: [] } : input.owner;
+ }
+
+ if (input.status === "open") {
+ where.stage = { in: [...OPEN_DEAL_STAGES] };
+ } else if (input.status === "closed") {
+ where.stage = { in: [...CLOSED_DEAL_STAGES] };
+ }
+
+ // An explicit stage wins over the tab: picking "Closed won" while the
+ // "Open" tab is selected should show closed-won, not nothing.
+ if (input.stage !== FACET_ALL) {
+ where.stage = input.stage as DealStage;
+ }
+
+ if (input.closing !== FACET_ALL) {
+ Object.assign(where, closingFilter(input.closing as ClosingWindow));
+ }
+
+ return where;
+ }
+
+ private async facetCounts(input: DealListInput) {
+ const where = this.searchFilter(input.q);
+
+ const [owners, stages, ...closingCounts] = await Promise.all([
+ this.db.deal.groupBy({ by: ["ownerId"], where, _count: { _all: true } }),
+ this.db.deal.groupBy({ by: ["stage"], where, _count: { _all: true } }),
+ ...CLOSING_WINDOWS.map((window) =>
+ this.db.deal.count({ where: { ...where, ...closingFilter(window) } }),
+ ),
+ ]);
+
+ const stageCounts = countsByKey(stages, "stage");
+ const openCount = OPEN_DEAL_STAGES.reduce(
+ (total, stage) => total + (stageCounts[stage] ?? 0),
+ 0,
+ );
+ const closedCount = CLOSED_DEAL_STAGES.reduce(
+ (total, stage) => total + (stageCounts[stage] ?? 0),
+ 0,
+ );
+
+ return {
+ status: { open: openCount, closed: closedCount },
+ owner: countsByKey(owners, "ownerId", FACET_UNASSIGNED),
+ stage: stageCounts,
+ closing: Object.fromEntries(
+ CLOSING_WINDOWS.map((window, index) => [
+ window,
+ closingCounts[index] ?? 0,
+ ]),
+ ),
+ };
+ }
+
+ private translate(error: unknown, id: string): unknown {
+ if (
+ error instanceof PrismaNamespace.PrismaClientKnownRequestError &&
+ error.code === "P2025"
+ ) {
+ return new NotFoundException(`No deal with id ${id}.`);
+ }
+ return this.translateRelations(error);
+ }
+
+ /** A missing company or owner is the caller's mistake, not a 500. */
+ private translateRelations(error: unknown): unknown {
+ if (
+ error instanceof PrismaNamespace.PrismaClientKnownRequestError &&
+ (error.code === "P2003" || error.code === "P2025")
+ ) {
+ return new BadRequestException(
+ "That company or owner does not exist any more.",
+ );
+ }
+ return error;
+ }
+}
+
+/**
+ * Month boundaries are computed here rather than in SQL so the buckets follow
+ * the server's calendar rather than UTC's, which matters on the last day of a
+ * month for a team in New York.
+ */
+function closingFilter(window: ClosingWindow): Prisma.DealWhereInput {
+ const now = new Date();
+ const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
+ const startOfNextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
+ const startOfMonthAfter = new Date(now.getFullYear(), now.getMonth() + 2, 1);
+
+ switch (window) {
+ case "overdue":
+ // Only open deals can be overdue; a closed deal's date is history.
+ return {
+ expectedCloseDate: { lt: now },
+ stage: { in: [...OPEN_DEAL_STAGES] },
+ };
+ case "this-month":
+ return {
+ expectedCloseDate: { gte: startOfMonth, lt: startOfNextMonth },
+ };
+ case "next-month":
+ return {
+ expectedCloseDate: { gte: startOfNextMonth, lt: startOfMonthAfter },
+ };
+ case "later":
+ return { expectedCloseDate: { gte: startOfMonthAfter } };
+ case "none":
+ return { expectedCloseDate: null };
+ }
+}
+
+function parseDate(value: string | null | undefined): Date | null {
+ if (value === null || value === undefined || value === "") return null;
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) {
+ throw new BadRequestException(`"${value}" is not a date.`);
+ }
+ return date;
+}
diff --git a/apps/api/src/enrichment/brand-mapping.ts b/apps/api/src/enrichment/brand-mapping.ts
new file mode 100644
index 00000000..45ccdfc2
--- /dev/null
+++ b/apps/api/src/enrichment/brand-mapping.ts
@@ -0,0 +1,136 @@
+import type { Prisma } from "@crm/db";
+import type { Brand } from "./context-dev.client";
+
+/**
+ * What the agent is allowed to change about a company.
+ *
+ * Every field Context.dev returns is nullable, and a human's typed-in value
+ * always outranks a guess: this only ever *fills gaps*. Nothing here overwrites
+ * something that is already set, which is why every assignment goes through
+ * `fill`.
+ */
+export type BrandUpdate = Prisma.CompanyUpdateInput;
+
+/** The current values, so we know which gaps there are to fill. */
+export type CompanySnapshot = {
+ name: string;
+ /** True when the record was created domain-first and never named by a human. */
+ nameIsPlaceholder: boolean;
+ description: string | null;
+ logoUrl: string | null;
+ logoDarkUrl: string | null;
+ iconUrl: string | null;
+ brandColor: string | null;
+ industry: string | null;
+ subIndustry: string | null;
+ city: string | null;
+ stateCode: string | null;
+ country: string | null;
+ countryCode: string | null;
+ phone: string | null;
+ email: string | null;
+ linkedinUrl: string | null;
+ twitterUrl: string | null;
+ githubUrl: string | null;
+ pricingUrl: string | null;
+ careersUrl: string | null;
+};
+
+/**
+ * Picks a logo by `mode` and `type` rather than taking `logos[0]`.
+ *
+ * The array is not ordered by usefulness: taking the first one is how you end
+ * up with a dark-mode wordmark on a white table row.
+ */
+function pickLogo(
+ logos: Brand["logos"],
+ type: "logo" | "icon",
+ mode?: "light" | "dark",
+): string | null {
+ const candidates = (logos ?? []).filter(
+ (logo) =>
+ logo?.url &&
+ logo.type === type &&
+ (mode === undefined || logo.mode === mode),
+ );
+ return candidates[0]?.url ?? null;
+}
+
+function social(socials: Brand["socials"], type: string): string | null {
+ return (socials ?? []).find((entry) => entry?.type === type)?.url ?? null;
+}
+
+function clean(value: string | null | undefined): string | null {
+ const trimmed = value?.trim();
+ return trimmed ? trimmed : null;
+}
+
+/**
+ * Builds the Prisma update for a brand lookup.
+ *
+ * Returns only the fields that are currently empty and that the lookup actually
+ * found, so re-enriching a company a rep has been editing does not undo their
+ * work.
+ */
+export function brandToUpdate(
+ brand: Brand,
+ current: CompanySnapshot,
+): BrandUpdate {
+ const update: BrandUpdate = {};
+
+ const fill = <K extends keyof CompanySnapshot & keyof BrandUpdate>(
+ key: K,
+ value: string | null,
+ ) => {
+ if (value && current[key as keyof CompanySnapshot] === null) {
+ (update as Record<string, unknown>)[key] = value;
+ }
+ };
+
+ // The one non-null field the agent may replace: a company created from a
+ // domain alone is named after the domain until we know better.
+ const title = clean(brand.title);
+ if (title && current.nameIsPlaceholder) {
+ update.name = title;
+ }
+
+ fill("description", clean(brand.description) ?? clean(brand.slogan));
+
+ fill("logoUrl", pickLogo(brand.logos, "logo", "light"));
+ fill("logoDarkUrl", pickLogo(brand.logos, "logo", "dark"));
+ // Icons rarely declare a mode, so this one is not filtered by it.
+ fill("iconUrl", pickLogo(brand.logos, "icon"));
+
+ // `colors[].name` is generated rather than the brand's own name for it, so
+ // the hex is the only part worth storing.
+ fill("brandColor", clean(brand.colors?.[0]?.hex));
+
+ const eic = brand.industries?.eic?.[0];
+ fill("industry", clean(eic?.industry));
+ fill("subIndustry", clean(eic?.subindustry));
+
+ fill("city", clean(brand.address?.city));
+ fill("stateCode", clean(brand.address?.state_code));
+ fill("country", clean(brand.address?.country));
+ fill("countryCode", clean(brand.address?.country_code));
+
+ fill("phone", clean(brand.phone));
+ fill("email", clean(brand.email));
+
+ fill("linkedinUrl", social(brand.socials, "linkedin"));
+ fill(
+ "twitterUrl",
+ social(brand.socials, "x") ?? social(brand.socials, "twitter"),
+ );
+ fill("githubUrl", social(brand.socials, "github"));
+
+ fill("pricingUrl", clean(brand.links?.pricing));
+ fill("careersUrl", clean(brand.links?.careers));
+
+ return update;
+}
+
+/** Fields worth counting when logging what a lookup actually achieved. */
+export function filledFields(update: BrandUpdate): string[] {
+ return Object.keys(update);
+}
diff --git a/apps/api/src/enrichment/context-dev.client.ts b/apps/api/src/enrichment/context-dev.client.ts
new file mode 100644
index 00000000..2c342156
--- /dev/null
+++ b/apps/api/src/enrichment/context-dev.client.ts
@@ -0,0 +1,250 @@
+import { Injectable, Logger } from "@nestjs/common";
+import { ConfigService } from "@nestjs/config";
+import ContextDev from "context.dev";
+import { APIError } from "context.dev/core/error";
+import type { EnvironmentVariables } from "../config/env.validation";
+
+/** The Context.dev `brand` object, narrowed to the parts we map. */
+export type Brand = {
+ domain?: string | null;
+ title?: string | null;
+ description?: string | null;
+ slogan?: string | null;
+ email?: string | null;
+ phone?: string | null;
+ colors?: { hex?: string | null; name?: string | null }[] | null;
+ logos?:
+ | {
+ url?: string | null;
+ mode?: string | null;
+ type?: string | null;
+ }[]
+ | null;
+ socials?: { type?: string | null; url?: string | null }[] | null;
+ address?: {
+ city?: string | null;
+ state_code?: string | null;
+ country?: string | null;
+ country_code?: string | null;
+ } | null;
+ industries?: {
+ eic?: { industry?: string | null; subindustry?: string | null }[] | null;
+ } | null;
+ links?: {
+ pricing?: string | null;
+ careers?: string | null;
+ } | null;
+};
+
+/**
+ * Why a lookup did not produce a brand.
+ *
+ * `skipped` and `failed` are deliberately different: "there is nothing to find
+ * for this domain" is a settled answer that should stop us retrying and cost
+ * nothing, while "the call fell over" is worth another go.
+ */
+export type LookupResult =
+ | { outcome: "found"; brand: Brand; raw: unknown }
+ | { outcome: "skipped"; reason: string }
+ | { outcome: "failed"; reason: string; retryable: boolean };
+
+/** Cold lookups are p50 ≈ 7s, p90 ≈ 18s — so this is generous on purpose. */
+const TIMEOUT_MS = 60_000;
+
+@Injectable()
+export class ContextDevClient {
+ private readonly logger = new Logger(ContextDevClient.name);
+ private readonly client: ContextDev | null;
+
+ constructor(config: ConfigService<EnvironmentVariables, true>) {
+ const apiKey = config.get("CONTEXT_DEV_API_KEY", { infer: true });
+
+ if (!apiKey) {
+ // Logged once, at boot, rather than on every company that stays PENDING.
+ this.logger.warn({
+ message:
+ "CONTEXT_DEV_API_KEY is not set — enrichment is disabled and companies will stay PENDING.",
+ });
+ this.client = null;
+ return;
+ }
+
+ this.client = new ContextDev({ apiKey });
+ }
+
+ get enabled(): boolean {
+ return this.client !== null;
+ }
+
+ /** `POST /brand/retrieve` by domain. 10 credits, only on a successful match. */
+ async brandByDomain(
+ domain: string,
+ maxAgeMs?: number,
+ ): Promise<LookupResult> {
+ return this.lookup({
+ type: "by_domain",
+ domain,
+ timeoutMS: TIMEOUT_MS,
+ ...(maxAgeMs === undefined ? {} : { maxAgeMs }),
+ });
+ }
+
+ /** `POST /brand/retrieve` by work email — the domain is extracted for us. */
+ async brandByEmail(email: string): Promise<LookupResult> {
+ return this.lookup({
+ type: "by_email",
+ email,
+ timeoutMS: TIMEOUT_MS,
+ });
+ }
+
+ /**
+ * Warms the cache so a later retrieve lands sub-second. Free, and
+ * fire-and-forget: the response carries no brand data.
+ *
+ * Paid plans only — a `403` here is a plan limit, not a bug, so it is logged
+ * once and the caller falls through to a direct retrieve.
+ */
+ async prefetch(domain: string): Promise<void> {
+ if (!this.client) return;
+
+ try {
+ await this.client.utility.prefetch({
+ type: "brand",
+ identifier: { domain },
+ });
+ } catch (error) {
+ if (error instanceof APIError && error.status === 403) {
+ this.logger.debug({
+ message: "Prefetch needs a paid plan — falling through to retrieve.",
+ domain,
+ });
+ return;
+ }
+ this.logger.debug({
+ message: "Prefetch failed; falling through to retrieve.",
+ domain,
+ reason: describe(error),
+ });
+ }
+ }
+
+ /**
+ * `POST /web/extract` against a caller-defined JSON Schema.
+ *
+ * Used for the research brief, which is not a brand lookup — it is "read this
+ * company's site and answer these questions".
+ */
+ async extract(
+ url: string,
+ schema: Record<string, unknown>,
+ instructions: string,
+ ): Promise<
+ { outcome: "found"; data: unknown } | { outcome: "failed"; reason: string }
+ > {
+ if (!this.client) {
+ return { outcome: "failed", reason: "Enrichment is not configured." };
+ }
+
+ try {
+ const response = await this.client.web.extract({
+ url,
+ schema,
+ instructions,
+ maxPages: 8,
+ timeoutMS: TIMEOUT_MS,
+ });
+ return { outcome: "found", data: response.data };
+ } catch (error) {
+ return { outcome: "failed", reason: describe(error) };
+ }
+ }
+
+ private async lookup(
+ params: Parameters<ContextDev["brand"]["retrieve"]>[0],
+ ): Promise<LookupResult> {
+ if (!this.client) {
+ return {
+ outcome: "skipped",
+ reason: "Enrichment is not configured.",
+ };
+ }
+
+ try {
+ const response = await this.client.brand.retrieve(params);
+ const brand = response.brand as Brand | undefined;
+
+ if (!brand) {
+ return { outcome: "skipped", reason: "No brand matched." };
+ }
+
+ return { outcome: "found", brand, raw: response };
+ } catch (error) {
+ return classify(error);
+ }
+ }
+}
+
+/**
+ * Maps Context.dev's failures onto something the CRM can act on.
+ *
+ * The important distinction is which of these should leave a company retryable.
+ * An unknown domain never becomes known by asking again; a timeout might.
+ */
+function classify(error: unknown): LookupResult {
+ if (!(error instanceof APIError)) {
+ return { outcome: "failed", reason: describe(error), retryable: true };
+ }
+
+ const code = errorCode(error);
+
+ // 400 covers both malformed input and "we looked, there is nothing there".
+ // Neither is billed, and neither is worth retrying.
+ if (error.status === 400) {
+ if (code === "NOT_FOUND" || code === "WEBSITE_ACCESS_ERROR") {
+ return {
+ outcome: "skipped",
+ reason:
+ code === "NOT_FOUND"
+ ? "No brand matched this domain."
+ : "The site could not be reached.",
+ };
+ }
+ return { outcome: "failed", reason: describe(error), retryable: false };
+ }
+
+ // A personal or throwaway address says nothing about where someone works.
+ if (error.status === 422) {
+ return {
+ outcome: "skipped",
+ reason: "That is a personal or disposable email address.",
+ };
+ }
+
+ if (error.status === 401 || error.status === 403) {
+ return { outcome: "failed", reason: describe(error), retryable: false };
+ }
+
+ // Cold-cache timeouts and rate limits are the retryable ones.
+ if (error.status === 408 || error.status === 429) {
+ return { outcome: "failed", reason: describe(error), retryable: true };
+ }
+
+ return {
+ outcome: "failed",
+ reason: describe(error),
+ retryable: (error.status ?? 500) >= 500,
+ };
+}
+
+function errorCode(error: APIError): string | undefined {
+ const body = error.error as { error_code?: unknown } | undefined;
+ return typeof body?.error_code === "string" ? body.error_code : undefined;
+}
+
+function describe(error: unknown): string {
+ if (error instanceof APIError) {
+ return `${error.status ?? "?"} ${errorCode(error) ?? error.message}`;
+ }
+ return error instanceof Error ? error.message : String(error);
+}
diff --git a/apps/api/src/enrichment/enrichment.module.ts b/apps/api/src/enrichment/enrichment.module.ts
new file mode 100644
index 00000000..2a438e5b
--- /dev/null
+++ b/apps/api/src/enrichment/enrichment.module.ts
@@ -0,0 +1,17 @@
+import { Module } from "@nestjs/common";
+import { ContextDevClient } from "./context-dev.client";
+import { EnrichmentQueue } from "./enrichment.queue";
+import { EnrichmentService } from "./enrichment.service";
+
+/**
+ * The agent.
+ *
+ * Exports only `EnrichmentService`, so the modules that trigger enrichment
+ * (companies, contacts) depend on "enrich this" rather than on the queue or the
+ * HTTP client behind it.
+ */
+@Module({
+ providers: [ContextDevClient, EnrichmentQueue, EnrichmentService],
+ exports: [EnrichmentService],
+})
+export class EnrichmentModule {}
diff --git a/apps/api/src/enrichment/enrichment.queue.ts b/apps/api/src/enrichment/enrichment.queue.ts
new file mode 100644
index 00000000..5c2eff29
--- /dev/null
+++ b/apps/api/src/enrichment/enrichment.queue.ts
@@ -0,0 +1,129 @@
+import { Injectable, Logger, type OnApplicationShutdown } from "@nestjs/common";
+
+type Job = {
+ /** Dedupe key — the domain, so the same company queued twice runs once. */
+ key: string;
+ run: () => Promise<void>;
+};
+
+const CONCURRENCY = 2;
+
+/**
+ * A small in-process queue for enrichment work.
+ *
+ * Deliberately not a job server. Enrichment is a handful of calls per company
+ * create, the work is idempotent, and losing a queued job on deploy costs
+ * nothing — the company stays `PENDING` and the next re-enrich picks it up. A
+ * Redis-backed queue would be more machinery than the problem has.
+ *
+ * What it does buy us: at most two concurrent Context.dev calls, one retry with
+ * a backoff, and per-domain dedupe so a rep hammering "Re-enrich" does not
+ * spend ten credits doing the same lookup ten times.
+ */
+@Injectable()
+export class EnrichmentQueue implements OnApplicationShutdown {
+ private readonly logger = new Logger(EnrichmentQueue.name);
+ private readonly pending: Job[] = [];
+ private readonly inFlight = new Set<string>();
+ private running = 0;
+ private shuttingDown = false;
+
+ /**
+ * How long to wait before the single retry.
+ *
+ * A getter rather than a constant so the tests can subclass it down to a few
+ * milliseconds — Nest constructs this provider with no arguments, so a
+ * constructor parameter would need a DI token for no benefit.
+ */
+ protected get retryDelayMs(): number {
+ return 5_000;
+ }
+
+ /** Resolves when the queue is empty — the hook tests wait on this. */
+ private idle: (() => void)[] = [];
+
+ /**
+ * Queues work, unless the same key is already queued or running.
+ *
+ * Returns whether it was accepted, so a caller can tell "started" from
+ * "already in progress".
+ */
+ enqueue(key: string, run: () => Promise<void>): boolean {
+ if (this.shuttingDown) return false;
+ if (this.inFlight.has(key)) return false;
+ if (this.pending.some((job) => job.key === key)) return false;
+
+ this.pending.push({ key, run });
+ this.pump();
+ return true;
+ }
+
+ /** Waits for everything queued so far to finish. For tests and scripts. */
+ async drain(): Promise<void> {
+ if (this.running === 0 && this.pending.length === 0) return;
+ await new Promise<void>((resolve) => this.idle.push(resolve));
+ }
+
+ onApplicationShutdown(): void {
+ this.shuttingDown = true;
+ // Queued-but-not-started work is dropped rather than raced against the
+ // closing database connection. Those companies stay PENDING, which is
+ // exactly the state a retry looks for.
+ const dropped = this.pending.length;
+ this.pending.length = 0;
+ if (dropped > 0) {
+ this.logger.log({ message: "Dropped queued enrichment jobs", dropped });
+ }
+ }
+
+ private pump(): void {
+ while (this.running < CONCURRENCY && this.pending.length > 0) {
+ const job = this.pending.shift();
+ if (!job) break;
+ void this.execute(job);
+ }
+ }
+
+ private async execute(job: Job): Promise<void> {
+ this.running += 1;
+ this.inFlight.add(job.key);
+
+ try {
+ await job.run();
+ } catch (error) {
+ // One retry, after a pause. Anything that fails twice is recorded on the
+ // company as `FAILED` by the service itself; this is the safety net for
+ // an exception the service did not expect.
+ this.logger.warn({
+ message: "Enrichment job threw — retrying once",
+ key: job.key,
+ reason: error instanceof Error ? error.message : String(error),
+ });
+
+ await sleep(this.retryDelayMs);
+
+ try {
+ await job.run();
+ } catch (retryError) {
+ this.logger.error(
+ { message: "Enrichment job failed twice", key: job.key },
+ retryError instanceof Error ? retryError.stack : String(retryError),
+ );
+ }
+ } finally {
+ this.running -= 1;
+ this.inFlight.delete(job.key);
+ this.pump();
+
+ if (this.running === 0 && this.pending.length === 0) {
+ const waiters = this.idle;
+ this.idle = [];
+ for (const resolve of waiters) resolve();
+ }
+ }
+ }
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
diff --git a/apps/api/src/enrichment/enrichment.service.ts b/apps/api/src/enrichment/enrichment.service.ts
new file mode 100644
index 00000000..568dfc05
--- /dev/null
+++ b/apps/api/src/enrichment/enrichment.service.ts
@@ -0,0 +1,384 @@
+import { ActivityType, type Db, EnrichmentStatus } from "@crm/db";
+import { Injectable, Logger, NotFoundException } from "@nestjs/common";
+import { domainFromEmail, normalizeDomain } from "../companies/domain";
+import { InjectDatabase } from "../database/database.constants";
+import { brandToUpdate, filledFields } from "./brand-mapping";
+import { ContextDevClient } from "./context-dev.client";
+import { EnrichmentQueue } from "./enrichment.queue";
+
+/** The shape the research brief is extracted into. */
+const RESEARCH_SCHEMA = {
+ type: "object",
+ properties: {
+ positioning: {
+ type: "string",
+ description: "One paragraph: what they sell and who to.",
+ },
+ pricingModel: {
+ type: "string",
+ description: "How they charge — per seat, usage, flat, enterprise-only.",
+ },
+ targetCustomer: {
+ type: "string",
+ description: "The customer they describe themselves as serving.",
+ },
+ notableCustomers: {
+ type: "array",
+ items: { type: "string" },
+ description: "Named customers or logos on the site.",
+ },
+ recentNews: {
+ type: "array",
+ items: { type: "string" },
+ description: "Recent announcements, funding, or launches.",
+ },
+ },
+ required: ["positioning"],
+} as const;
+
+const RESEARCH_INSTRUCTIONS =
+ "Read this company's marketing site and answer as a salesperson preparing " +
+ "for a first call. Be specific and factual; leave a field empty rather than " +
+ "guessing.";
+
+@Injectable()
+export class EnrichmentService {
+ private readonly logger = new Logger(EnrichmentService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly context: ContextDevClient,
+ private readonly queue: EnrichmentQueue,
+ ) {}
+
+ /**
+ * Queues a company for enrichment.
+ *
+ * Fire-and-forget by design: a cold Context.dev lookup is p50 ≈ 7s, and a
+ * "New company" form that sits spinning for seven seconds is a form people
+ * stop using. The detail page polls while the status is `PENDING`/`RUNNING`.
+ */
+ enqueueCompany(
+ companyId: string,
+ options: { force?: boolean } = {},
+ ): boolean {
+ if (!this.context.enabled) return false;
+
+ return this.queue.enqueue(`company:${companyId}`, () =>
+ this.runCompany(companyId, options.force ?? false),
+ );
+ }
+
+ /**
+ * Warms Context.dev's cache for a batch of domains.
+ *
+ * Free, and the difference between a CSV import queueing a hundred cold
+ * seven-second lookups and a hundred warm sub-second ones.
+ */
+ async warm(domains: string[]): Promise<void> {
+ if (!this.context.enabled) return;
+ await Promise.all(
+ [...new Set(domains)].map((domain) => this.context.prefetch(domain)),
+ );
+ }
+
+ /** Whether the agent has an API key at all. */
+ get enabled(): boolean {
+ return this.context.enabled;
+ }
+
+ /** Waits for queued work — used by scripts and tests, not by request paths. */
+ async drain(): Promise<void> {
+ await this.queue.drain();
+ }
+
+ private async runCompany(companyId: string, force: boolean): Promise<void> {
+ const company = await this.db.company.findUnique({
+ where: { id: companyId },
+ select: {
+ id: true,
+ name: true,
+ domain: true,
+ description: true,
+ logoUrl: true,
+ logoDarkUrl: true,
+ iconUrl: true,
+ brandColor: true,
+ industry: true,
+ subIndustry: true,
+ city: true,
+ stateCode: true,
+ country: true,
+ countryCode: true,
+ phone: true,
+ email: true,
+ linkedinUrl: true,
+ twitterUrl: true,
+ githubUrl: true,
+ pricingUrl: true,
+ careersUrl: true,
+ },
+ });
+
+ if (!company) return;
+
+ const domain = normalizeDomain(company.domain);
+
+ if (!domain) {
+ await this.settle(
+ companyId,
+ EnrichmentStatus.SKIPPED,
+ "No domain to look up.",
+ );
+ return;
+ }
+
+ await this.db.company.update({
+ where: { id: companyId },
+ data: {
+ enrichmentStatus: EnrichmentStatus.RUNNING,
+ enrichmentError: null,
+ },
+ });
+
+ // Free, and turns a cold 7s lookup into a warm sub-second one.
+ await this.context.prefetch(domain);
+
+ // `maxAgeMs: 0` on a manual re-enrich: the whole point of pressing the
+ // button is to get past the ~90-day server-side cache.
+ const result = await this.context.brandByDomain(
+ domain,
+ force ? 0 : undefined,
+ );
+
+ if (result.outcome === "skipped") {
+ await this.settle(companyId, EnrichmentStatus.SKIPPED, result.reason);
+ return;
+ }
+
+ if (result.outcome === "failed") {
+ await this.settle(companyId, EnrichmentStatus.FAILED, result.reason);
+ // Let the queue's retry have a go at the retryable ones.
+ if (result.retryable) throw new Error(result.reason);
+ return;
+ }
+
+ const update = brandToUpdate(result.brand, {
+ ...company,
+ // A company created from a domain alone is named after it until the
+ // lookup tells us better.
+ nameIsPlaceholder: company.name === domain,
+ });
+
+ await this.db.$transaction([
+ this.db.company.update({
+ where: { id: companyId },
+ data: {
+ ...update,
+ enrichmentStatus: EnrichmentStatus.COMPLETE,
+ enrichedAt: new Date(),
+ enrichmentError: null,
+ },
+ }),
+ // The whole payload is kept so re-deriving a field later costs nothing
+ // and no credits.
+ this.db.companyEnrichment.upsert({
+ where: { companyId },
+ create: {
+ companyId,
+ raw: result.raw as never,
+ },
+ update: { raw: result.raw as never, fetchedAt: new Date() },
+ }),
+ ]);
+
+ this.logger.log({
+ message: "Company enriched",
+ companyId,
+ domain,
+ filled: filledFields(update),
+ });
+ }
+
+ /**
+ * Finds or creates the company a work email belongs to.
+ *
+ * Called when a contact is added with a work address and no company. Returns
+ * the company id when one was found or made, `null` when the address says
+ * nothing useful (a personal or throwaway domain).
+ */
+ async companyForEmail(email: string): Promise<string | null> {
+ const domain = domainFromEmail(email);
+ if (!domain) return null;
+
+ const existing = await this.db.company.findUnique({
+ where: { domain },
+ select: { id: true },
+ });
+ if (existing) return existing.id;
+
+ if (!this.context.enabled) return null;
+
+ const result = await this.context.brandByEmail(email);
+ if (result.outcome !== "found") {
+ this.logger.debug({
+ message: "No company for email domain",
+ domain,
+ reason: result.reason,
+ });
+ return null;
+ }
+
+ const name = result.brand.title?.trim() || domain;
+
+ // Two contacts at a new company can race here; the unique index on
+ // `domain` is what actually settles it.
+ const company = await this.db.company.upsert({
+ where: { domain },
+ create: {
+ name,
+ domain,
+ website: `https://${domain}`,
+ enrichmentStatus: EnrichmentStatus.PENDING,
+ },
+ update: {},
+ select: { id: true },
+ });
+
+ // Created from a lookup we already have — apply it rather than paying for
+ // the same brand twice.
+ this.enqueueCompany(company.id);
+
+ this.logger.log({
+ message: "Company created from a contact's email domain",
+ companyId: company.id,
+ domain,
+ });
+
+ return company.id;
+ }
+
+ /**
+ * Reads the company's site and posts what it found to the timeline.
+ *
+ * On the timeline rather than in a side panel because that is where a rep is
+ * already looking, and because it should age like everything else — a brief
+ * from six months ago is context, not current truth.
+ */
+ async researchCompany(companyId: string, actingUserId: string) {
+ const company = await this.db.company.findUnique({
+ where: { id: companyId },
+ select: { id: true, name: true, domain: true, website: true },
+ });
+
+ if (!company) {
+ throw new NotFoundException(`No company with id ${companyId}.`);
+ }
+
+ const url =
+ company.website ?? (company.domain ? `https://${company.domain}` : null);
+
+ if (!url) {
+ return { ok: false as const, reason: "This company has no website yet." };
+ }
+
+ const result = await this.context.extract(
+ url,
+ RESEARCH_SCHEMA as unknown as Record<string, unknown>,
+ RESEARCH_INSTRUCTIONS,
+ );
+
+ if (result.outcome === "failed") {
+ return { ok: false as const, reason: result.reason };
+ }
+
+ const activity = await this.db.activity.create({
+ data: {
+ type: ActivityType.ENRICHMENT,
+ subject: `Research brief — ${company.name}`,
+ body: formatBrief(result.data),
+ occurredAt: new Date(),
+ companyId: company.id,
+ createdById: actingUserId,
+ meta: {
+ source: "context.dev",
+ endpoint: "web/extract",
+ creditCost: 10,
+ },
+ },
+ select: { id: true },
+ });
+
+ this.logger.log({
+ message: "Research brief written",
+ companyId,
+ activityId: activity.id,
+ });
+
+ return { ok: true as const, activityId: activity.id };
+ }
+
+ private async settle(
+ companyId: string,
+ status: EnrichmentStatus,
+ reason: string,
+ ): Promise<void> {
+ await this.db.company.update({
+ where: { id: companyId },
+ data: {
+ enrichmentStatus: status,
+ enrichedAt: new Date(),
+ // Only a real failure is worth surfacing; "nothing to find" is a
+ // settled answer, not an error message to show a rep.
+ enrichmentError: status === EnrichmentStatus.FAILED ? reason : null,
+ },
+ });
+
+ this.logger.log({
+ message: "Enrichment settled",
+ companyId,
+ status,
+ reason,
+ });
+ }
+}
+
+/** The extracted object as prose, because a timeline entry is read, not parsed. */
+function formatBrief(data: unknown): string {
+ if (typeof data !== "object" || data === null) return String(data ?? "");
+
+ const brief = data as {
+ positioning?: unknown;
+ pricingModel?: unknown;
+ targetCustomer?: unknown;
+ notableCustomers?: unknown;
+ recentNews?: unknown;
+ };
+
+ const lines: string[] = [];
+ const text = (value: unknown) =>
+ typeof value === "string" && value.trim() ? value.trim() : null;
+ const list = (value: unknown) =>
+ Array.isArray(value)
+ ? value.filter((item): item is string => typeof item === "string")
+ : [];
+
+ const positioning = text(brief.positioning);
+ if (positioning) lines.push(positioning);
+
+ const pricing = text(brief.pricingModel);
+ if (pricing) lines.push(`Pricing: ${pricing}`);
+
+ const target = text(brief.targetCustomer);
+ if (target) lines.push(`Sells to: ${target}`);
+
+ const customers = list(brief.notableCustomers);
+ if (customers.length > 0) lines.push(`Customers: ${customers.join(", ")}`);
+
+ const news = list(brief.recentNews);
+ if (news.length > 0) {
+ lines.push(`Recently:\n${news.map((item) => `• ${item}`).join("\n")}`);
+ }
+
+ return lines.join("\n\n");
+}
diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.ts
new file mode 100644
index 00000000..5a6c2eac
--- /dev/null
+++ b/apps/api/src/generated/server.ts
@@ -0,0 +1,149 @@
+/**
+ * AUTO-GENERATED FILE - DO NOT EDIT!
+ *
+ * This file was automatically generated by nestjs-trpc.
+ * Any manual changes will be overwritten on the next generation.
+ *
+ * Command: `npx nestjs-trpc generate`
+ * Learn more: https://nestjs-trpc.io
+ */
+
+import { initTRPC } from "@trpc/server";
+import { z } from "zod";
+
+const t = initTRPC.create();
+const publicProcedure = t.procedure;
+import { timelineInput, timelineCountsInput, myTasksInput, activityCreateInput, activityUpdateInput, completeInput, activityIdInput } from "../activities/activities.contracts";
+import { companyListInput, companyIdInput, companyOptionsInput, companyCreateInput, companyUpdateArgs, setPrimaryContactInput } from "../companies/companies.contracts";
+import { contactListInput, contactIdInput, contactCreateInput, contactUpdateArgs } from "../contacts/contacts.contracts";
+import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput, setContactsInput } from "../deals/deals.contracts";
+import { boardInput } from "../deals/deals.board";
+import { importInput } from "../import/import.contracts";
+import type { ActivitiesRouter } from "../activities/activities.router";
+import type { CompaniesRouter } from "../companies/companies.router";
+import type { ContactsRouter } from "../contacts/contacts.router";
+import type { DashboardRouter } from "../dashboard/dashboard.router";
+import type { DealsRouter } from "../deals/deals.router";
+import type { ImportRouter } from "../import/import.router";
+import type { SearchRouter } from "../search/search.router";
+import type { UsersRouter } from "../users/users.router";
+
+const appRouter = t.router({
+ activities: t.router({
+ timeline: publicProcedure
+ .input(timelineInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ActivitiesRouter["timeline"]>>),
+ timelineCounts: publicProcedure
+ .input(timelineCountsInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ActivitiesRouter["timelineCounts"]>>),
+ myTasks: publicProcedure
+ .input(myTasksInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ActivitiesRouter["myTasks"]>>),
+ create: publicProcedure
+ .input(activityCreateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ActivitiesRouter["create"]>>),
+ update: publicProcedure
+ .input(activityUpdateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ActivitiesRouter["update"]>>),
+ complete: publicProcedure
+ .input(completeInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ActivitiesRouter["complete"]>>),
+ remove: publicProcedure
+ .input(activityIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ActivitiesRouter["remove"]>>)
+ }),
+ companies: t.router({
+ list: publicProcedure
+ .input(companyListInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["list"]>>),
+ byId: publicProcedure
+ .input(companyIdInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["byId"]>>),
+ options: publicProcedure
+ .input(companyOptionsInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["options"]>>),
+ create: publicProcedure
+ .input(companyCreateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["create"]>>),
+ update: publicProcedure
+ .input(companyUpdateArgs)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["update"]>>),
+ remove: publicProcedure
+ .input(companyIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["remove"]>>),
+ enrich: publicProcedure
+ .input(companyIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["enrich"]>>),
+ research: publicProcedure
+ .input(companyIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["research"]>>),
+ setPrimaryContact: publicProcedure
+ .input(setPrimaryContactInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["setPrimaryContact"]>>)
+ }),
+ contacts: t.router({
+ list: publicProcedure
+ .input(contactListInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["list"]>>),
+ byId: publicProcedure
+ .input(contactIdInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["byId"]>>),
+ create: publicProcedure
+ .input(contactCreateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["create"]>>),
+ update: publicProcedure
+ .input(contactUpdateArgs)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["update"]>>),
+ remove: publicProcedure
+ .input(contactIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["remove"]>>)
+ }),
+ dashboard: t.router({
+ summary: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DashboardRouter["summary"]>>)
+ }),
+ deals: t.router({
+ list: publicProcedure
+ .input(dealListInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["list"]>>),
+ board: publicProcedure
+ .input(boardInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["board"]>>),
+ byId: publicProcedure
+ .input(dealIdInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["byId"]>>),
+ create: publicProcedure
+ .input(dealCreateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["create"]>>),
+ update: publicProcedure
+ .input(dealUpdateArgs)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["update"]>>),
+ setStage: publicProcedure
+ .input(setStageInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["setStage"]>>),
+ setContacts: publicProcedure
+ .input(setContactsInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["setContacts"]>>),
+ remove: publicProcedure
+ .input(dealIdInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["remove"]>>)
+ }),
+ import: t.router({
+ run: publicProcedure
+ .input(importInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ImportRouter["run"]>>)
+ }),
+ search: t.router({
+ quick: publicProcedure
+ .input(z.object({ q: z.string().default("") }))
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SearchRouter["quick"]>>)
+ }),
+ users: t.router({
+ me: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<UsersRouter["me"]>>),
+ list: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<UsersRouter["list"]>>)
+ })
+});
+
+export type AppRouter = typeof appRouter;
diff --git a/apps/api/src/health/health.controller.ts b/apps/api/src/health/health.controller.ts
new file mode 100644
index 00000000..4e05a822
--- /dev/null
+++ b/apps/api/src/health/health.controller.ts
@@ -0,0 +1,52 @@
+import type { Db } from "@crm/db";
+import {
+ Controller,
+ Get,
+ Logger,
+ ServiceUnavailableException,
+} from "@nestjs/common";
+import { AllowAnonymous } from "@thallesp/nestjs-better-auth";
+import { InjectDatabase } from "../database/database.constants";
+
+/** A `SELECT 1` slower than this means the pool or the network is in trouble. */
+const SLOW_PROBE_MS = 250;
+
+@Controller("health")
+export class HealthController {
+ private readonly logger = new Logger(HealthController.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ @Get()
+ @AllowAnonymous()
+ async check() {
+ const startedAt = process.hrtime.bigint();
+
+ try {
+ await this.db.$queryRaw`SELECT 1`;
+ } catch (error) {
+ this.logger.error(
+ { message: "Database health check failed" },
+ // Passed as the stack argument: handing Nest the error object
+ // instead prints it as a second message and drops the trace.
+ error instanceof Error ? error.stack : String(error),
+ );
+ throw new ServiceUnavailableException({
+ status: "error",
+ database: "down",
+ });
+ }
+
+ const durationMs = Number(process.hrtime.bigint() - startedAt) / 1_000_000;
+
+ if (durationMs > SLOW_PROBE_MS) {
+ this.logger.warn({
+ message: "Database health check was slow",
+ durationMs: Number(durationMs.toFixed(1)),
+ thresholdMs: SLOW_PROBE_MS,
+ });
+ }
+
+ return { status: "ok", database: "up" };
+ }
+}
diff --git a/apps/api/src/health/health.module.ts b/apps/api/src/health/health.module.ts
new file mode 100644
index 00000000..e364d917
--- /dev/null
+++ b/apps/api/src/health/health.module.ts
@@ -0,0 +1,7 @@
+import { Module } from "@nestjs/common";
+import { HealthController } from "./health.controller";
+
+@Module({
+ controllers: [HealthController],
+})
+export class HealthModule {}
diff --git a/apps/api/src/import/csv.ts b/apps/api/src/import/csv.ts
new file mode 100644
index 00000000..915b8f66
--- /dev/null
+++ b/apps/api/src/import/csv.ts
@@ -0,0 +1,146 @@
+/**
+ * A CSV reader, rather than a dependency.
+ *
+ * HubSpot exports are RFC 4180: comma-separated, `"` quoting, `""` for a
+ * literal quote, and newlines allowed inside quoted fields. That is the whole
+ * grammar, and it is about forty lines — small enough that owning it beats
+ * taking a parser we would then have to keep patched.
+ */
+
+export type CsvRow = Record<string, string>;
+
+/**
+ * A row plus the line it came from.
+ *
+ * The line number is the point of the import report — "fix row 214" is only
+ * useful if 214 is what the spreadsheet shows. Blank rows are dropped from the
+ * results but still consume a line number.
+ */
+export type ParsedRow = { line: number; values: CsvRow };
+
+/** Splits a CSV document into rows of raw cells. */
+function parseRows(input: string): string[][] {
+ const rows: string[][] = [];
+ let row: string[] = [];
+ let cell = "";
+ let quoted = false;
+
+ // Normalising line endings first means the state machine below only has to
+ // think about `\n`.
+ const text = input.replace(/\r\n?/g, "\n");
+
+ for (let index = 0; index < text.length; index++) {
+ const char = text[index];
+
+ if (quoted) {
+ if (char === '"') {
+ if (text[index + 1] === '"') {
+ cell += '"';
+ index += 1;
+ } else {
+ quoted = false;
+ }
+ } else {
+ cell += char;
+ }
+ continue;
+ }
+
+ if (char === '"') {
+ quoted = true;
+ } else if (char === ",") {
+ row.push(cell);
+ cell = "";
+ } else if (char === "\n") {
+ row.push(cell);
+ rows.push(row);
+ row = [];
+ cell = "";
+ } else {
+ cell += char;
+ }
+ }
+
+ // A file that does not end in a newline still has a last row.
+ if (cell !== "" || row.length > 0) {
+ row.push(cell);
+ rows.push(row);
+ }
+
+ return rows;
+}
+
+/**
+ * Parses a CSV into objects keyed by header.
+ *
+ * Headers are lower-cased and stripped of punctuation so "First Name",
+ * "first_name" and "FIRST NAME" all land on `firstname` — HubSpot's column
+ * names differ between export types and versions, and a rep should not have to
+ * care which one they got.
+ */
+export function parseCsv(input: string): ParsedRow[] {
+ const all = parseRows(input);
+
+ // The header is the first row with anything in it; anything above it is
+ // blank padding, and it still counts towards the line numbers below.
+ const headerIndex = all.findIndex((row) =>
+ row.some((cell) => cell.trim() !== ""),
+ );
+ if (headerIndex === -1) return [];
+
+ const keys = (all[headerIndex] ?? []).map(normalizeHeader);
+ const parsed: ParsedRow[] = [];
+
+ for (let index = headerIndex + 1; index < all.length; index++) {
+ const row = all[index] ?? [];
+ if (!row.some((cell) => cell.trim() !== "")) continue;
+
+ const values: CsvRow = {};
+ for (const [column, key] of keys.entries()) {
+ if (!key) continue;
+ const value = row[column]?.trim() ?? "";
+ // A repeated header should not blank out the column that has data.
+ if (value !== "" || !(key in values)) values[key] = value;
+ }
+
+ // 1-based, counting the header — what a spreadsheet shows in the gutter.
+ parsed.push({ line: index + 1, values });
+ }
+
+ return parsed;
+}
+
+export function normalizeHeader(header: string): string {
+ return header
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]/g, "");
+}
+
+/** First non-empty value among the aliases a column might be called. */
+export function field(row: CsvRow, ...aliases: string[]): string | undefined {
+ for (const alias of aliases) {
+ const value = row[normalizeHeader(alias)];
+ if (value) return value;
+ }
+ return undefined;
+}
+
+/**
+ * HubSpot writes amounts as `1,234.50` or `$1,234.50`. Returns integer cents,
+ * or `null` when the cell is empty or not a number.
+ */
+export function parseAmountCents(value: string | undefined): number | null {
+ if (!value) return null;
+ const cleaned = value.replace(/[^0-9.-]/g, "");
+ if (cleaned === "" || cleaned === "-") return null;
+ const parsed = Number.parseFloat(cleaned);
+ return Number.isFinite(parsed) ? Math.round(parsed * 100) : null;
+}
+
+/** A date cell, or `null` — an unparseable date is dropped, not guessed at. */
+export function parseCsvDate(value: string | undefined): Date | null {
+ if (!value) return null;
+ const parsed = new Date(value);
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
+}
diff --git a/apps/api/src/import/import.contracts.ts b/apps/api/src/import/import.contracts.ts
new file mode 100644
index 00000000..3c780449
--- /dev/null
+++ b/apps/api/src/import/import.contracts.ts
@@ -0,0 +1,47 @@
+import { z } from "zod";
+
+export const IMPORT_KINDS = ["companies", "contacts", "deals"] as const;
+
+export type ImportKind = (typeof IMPORT_KINDS)[number];
+
+export const importInput = z.object({
+ kind: z.enum(IMPORT_KINDS),
+ /** The file's contents. Imports are a few thousand rows, not a data lake. */
+ csv: z.string().min(1, "That file is empty."),
+ /**
+ * A dry run reports what *would* happen and writes nothing.
+ *
+ * Defaults to `true`: an import that silently rewrites the CRM on the first
+ * click is how a bad column mapping becomes a restore-from-backup.
+ */
+ dryRun: z.boolean().default(true),
+ /** Owner for rows that do not name one. */
+ defaultOwnerId: z.string().nullable().optional(),
+});
+
+export type ImportInput = z.infer<typeof importInput>;
+
+/** What one row would do, or did. */
+export type RowOutcome = "created" | "updated" | "skipped" | "failed";
+
+export type ImportRowReport = {
+ /** 1-based, counting the header as row 1 — what a spreadsheet shows. */
+ line: number;
+ outcome: RowOutcome;
+ /** The domain, email or deal name the row was matched on. */
+ key: string | null;
+ label: string | null;
+ reason?: string;
+};
+
+export type ImportReport = {
+ kind: ImportKind;
+ dryRun: boolean;
+ total: number;
+ created: number;
+ updated: number;
+ skipped: number;
+ failed: number;
+ /** Every row, so a dry run can be read before committing to it. */
+ rows: ImportRowReport[];
+};
diff --git a/apps/api/src/import/import.module.ts b/apps/api/src/import/import.module.ts
new file mode 100644
index 00000000..3f9c2f6a
--- /dev/null
+++ b/apps/api/src/import/import.module.ts
@@ -0,0 +1,11 @@
+import { Module } from "@nestjs/common";
+import { EnrichmentModule } from "../enrichment/enrichment.module";
+import { TrpcModule } from "../trpc/trpc.module";
+import { ImportRouter } from "./import.router";
+import { ImportService } from "./import.service";
+
+@Module({
+ imports: [TrpcModule, EnrichmentModule],
+ providers: [ImportService, ImportRouter],
+})
+export class ImportModule {}
diff --git a/apps/api/src/import/import.router.ts b/apps/api/src/import/import.router.ts
new file mode 100644
index 00000000..93e4f75c
--- /dev/null
+++ b/apps/api/src/import/import.router.ts
@@ -0,0 +1,24 @@
+import { Inject } from "@nestjs/common";
+import { Input, Mutation, Router, UseMiddlewares } from "nestjs-trpc";
+import type { z } from "zod";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { importInput } from "./import.contracts";
+import { ImportService } from "./import.service";
+
+@Router({ alias: "import" })
+@UseMiddlewares(AuthMiddleware)
+export class ImportRouter {
+ constructor(@Inject(ImportService) private readonly imports: ImportService) {}
+
+ /**
+ * A mutation even when `dryRun` is true.
+ *
+ * A dry run writes nothing, but it is a POST with a body the size of a
+ * spreadsheet, and modelling it as a query would put the whole file in a URL
+ * and in the query cache.
+ */
+ @Mutation({ input: importInput })
+ async run(@Input() input: z.infer<typeof importInput>) {
+ return this.imports.run(input);
+ }
+}
diff --git a/apps/api/src/import/import.service.ts b/apps/api/src/import/import.service.ts
new file mode 100644
index 00000000..2a6de655
--- /dev/null
+++ b/apps/api/src/import/import.service.ts
@@ -0,0 +1,506 @@
+import { type Db, type DealStage, DealStage as Stage } from "@crm/db";
+import { Injectable, Logger } from "@nestjs/common";
+import { normalizeDomain } from "../companies/domain";
+import { blankToNull, fromCents } from "../crm/values";
+import { InjectDatabase } from "../database/database.constants";
+import { isClosedStage } from "../deals/deal-stage";
+import { EnrichmentService } from "../enrichment/enrichment.service";
+import {
+ type CsvRow,
+ field,
+ type ParsedRow,
+ parseAmountCents,
+ parseCsv,
+ parseCsvDate,
+} from "./csv";
+import type {
+ ImportInput,
+ ImportKind,
+ ImportReport,
+ ImportRowReport,
+} from "./import.contracts";
+
+/**
+ * HubSpot's deal stage names, lower-cased, mapped onto ours.
+ *
+ * Anything unrecognised lands in `DEMO_BOOKED` rather than failing the row: a
+ * deal in the wrong column is a two-second fix, a deal that did not import is
+ * a deal nobody knows is missing.
+ */
+const STAGE_ALIASES: Record<string, DealStage> = {
+ "demo booked": Stage.DEMO_BOOKED,
+ appointmentscheduled: Stage.DEMO_BOOKED,
+ "appointment scheduled": Stage.DEMO_BOOKED,
+ "qualified to buy": Stage.QUALIFIED_TO_BUY,
+ qualifiedtobuy: Stage.QUALIFIED_TO_BUY,
+ "unqualified to buy": Stage.UNQUALIFIED_TO_BUY,
+ unqualified: Stage.UNQUALIFIED_TO_BUY,
+ "decision maker bought in": Stage.DECISION_MAKER_BOUGHT_IN,
+ decisionmakerboughtin: Stage.DECISION_MAKER_BOUGHT_IN,
+ "contract sent": Stage.CONTRACT_SENT,
+ contractsent: Stage.CONTRACT_SENT,
+ "closed won": Stage.CLOSED_WON,
+ closedwon: Stage.CLOSED_WON,
+ "closed lost": Stage.CLOSED_LOST,
+ closedlost: Stage.CLOSED_LOST,
+};
+
+/** Rows above this are refused rather than quietly truncated. */
+const MAX_ROWS = 5_000;
+
+@Injectable()
+export class ImportService {
+ private readonly logger = new Logger(ImportService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly enrichment: EnrichmentService,
+ ) {}
+
+ async run(input: ImportInput): Promise<ImportReport> {
+ const rows = parseCsv(input.csv);
+
+ if (rows.length > MAX_ROWS) {
+ throw new Error(
+ `That file has ${rows.length} rows; the limit is ${MAX_ROWS}. Split it and import in batches.`,
+ );
+ }
+
+ const reports =
+ input.kind === "companies"
+ ? await this.importCompanies(rows, input)
+ : input.kind === "contacts"
+ ? await this.importContacts(rows, input)
+ : await this.importDeals(rows, input);
+
+ const report = summarise(input.kind, input.dryRun, reports);
+
+ this.logger.log({
+ message: input.dryRun ? "Import dry run" : "Import applied",
+ kind: input.kind,
+ total: report.total,
+ created: report.created,
+ updated: report.updated,
+ skipped: report.skipped,
+ failed: report.failed,
+ });
+
+ return report;
+ }
+
+ private async importCompanies(
+ rows: ParsedRow[],
+ input: ImportInput,
+ ): Promise<ImportRowReport[]> {
+ // Warm Context.dev's cache for the whole file before touching any of it.
+ // Prefetch is free, and it turns a queue of cold 7-second lookups into
+ // warm sub-second ones once the rows land.
+ if (!input.dryRun) {
+ await this.enrichment.warm(
+ rows
+ .map(({ values }) =>
+ normalizeDomain(
+ field(values, "domain", "Company Domain Name", "website"),
+ ),
+ )
+ .filter((domain): domain is string => domain !== null),
+ );
+ }
+
+ const reports: ImportRowReport[] = [];
+
+ for (const { line, values: row } of rows) {
+ const name = field(row, "name", "Company name");
+ const domain = normalizeDomain(
+ field(row, "domain", "Company Domain Name", "website"),
+ );
+
+ if (!name && !domain) {
+ reports.push({
+ line,
+ outcome: "skipped",
+ key: null,
+ label: null,
+ reason: "No name and no domain.",
+ });
+ continue;
+ }
+
+ // Domain is the dedupe key. Rows without one fall back to an exact,
+ // case-insensitive name match — HubSpot company exports often have no
+ // domain column, and without a fallback every re-import would duplicate
+ // those rows. The match is exact on purpose: fuzzy company names merge
+ // accounts that are not the same company.
+ const existing = domain
+ ? await this.db.company.findUnique({
+ where: { domain },
+ select: { id: true, name: true },
+ })
+ : name
+ ? await this.db.company.findFirst({
+ where: {
+ name: { equals: name, mode: "insensitive" },
+ domain: null,
+ },
+ select: { id: true, name: true },
+ })
+ : null;
+
+ // Worth saying out loud: a name match is a weaker claim than a domain
+ // match, and the reader of the report is the one who can judge it.
+ const matchedByName = existing !== null && domain === null;
+ const label = name ?? domain;
+
+ if (input.dryRun) {
+ reports.push({
+ line,
+ outcome: existing ? "updated" : "created",
+ key: domain,
+ label,
+ reason: matchedByName
+ ? "Matched on name — this row has no domain."
+ : domain
+ ? undefined
+ : "No domain, so this company cannot be matched on re-import.",
+ });
+ continue;
+ }
+
+ try {
+ if (existing) {
+ // Only fills gaps, exactly like the agent: an import should not
+ // undo edits someone made after the last one.
+ await this.db.company.update({
+ where: { id: existing.id },
+ data: {
+ phone:
+ blankToNull(field(row, "phone", "Phone Number") ?? "") ??
+ undefined,
+ city: blankToNull(field(row, "city") ?? "") ?? undefined,
+ country: blankToNull(field(row, "country") ?? "") ?? undefined,
+ industry: blankToNull(field(row, "industry") ?? "") ?? undefined,
+ },
+ });
+ reports.push({
+ line,
+ outcome: "updated",
+ key: domain,
+ label,
+ reason: matchedByName
+ ? "Matched on name — this row has no domain."
+ : undefined,
+ });
+ continue;
+ }
+
+ const company = await this.db.company.create({
+ data: {
+ name: name ?? domain ?? "Unnamed",
+ domain,
+ website: domain ? `https://${domain}` : null,
+ phone: blankToNull(field(row, "phone", "Phone Number") ?? ""),
+ city: blankToNull(field(row, "city") ?? ""),
+ country: blankToNull(field(row, "country") ?? ""),
+ industry: blankToNull(field(row, "industry") ?? ""),
+ ownerId: input.defaultOwnerId ?? null,
+ },
+ select: { id: true },
+ });
+
+ this.enrichment.enqueueCompany(company.id);
+ reports.push({ line, outcome: "created", key: domain, label });
+ } catch (error) {
+ reports.push({
+ line,
+ outcome: "failed",
+ key: domain,
+ label,
+ reason: describe(error),
+ });
+ }
+ }
+
+ return reports;
+ }
+
+ private async importContacts(
+ rows: ParsedRow[],
+ input: ImportInput,
+ ): Promise<ImportRowReport[]> {
+ const reports: ImportRowReport[] = [];
+
+ for (const { line, values: row } of rows) {
+ const email = blankToNull(
+ (field(row, "email", "Email Address") ?? "").toLowerCase(),
+ );
+ const firstName = field(row, "firstname", "First Name");
+ const lastName = field(row, "lastname", "Last Name");
+ const label = [firstName, lastName].filter(Boolean).join(" ") || email;
+
+ if (!firstName && !email) {
+ reports.push({
+ line,
+ outcome: "skipped",
+ key: null,
+ label: null,
+ reason: "No name and no email.",
+ });
+ continue;
+ }
+
+ // Dedupe on email, which is unique — this is what makes re-running an
+ // import safe.
+ const existing = email
+ ? await this.db.contact.findUnique({
+ where: { email },
+ select: { id: true },
+ })
+ : null;
+
+ if (input.dryRun) {
+ reports.push({
+ line,
+ outcome: existing ? "updated" : "created",
+ key: email,
+ label,
+ });
+ continue;
+ }
+
+ try {
+ const companyId = await this.resolveCompany(row, email);
+
+ if (existing) {
+ await this.db.contact.update({
+ where: { id: existing.id },
+ data: {
+ phone:
+ blankToNull(field(row, "phone", "Phone Number") ?? "") ??
+ undefined,
+ title:
+ blankToNull(
+ field(row, "jobtitle", "Job Title", "title") ?? "",
+ ) ?? undefined,
+ ...(companyId ? { companyId } : {}),
+ },
+ });
+ reports.push({ line, outcome: "updated", key: email, label });
+ continue;
+ }
+
+ await this.db.contact.create({
+ data: {
+ firstName: firstName ?? email ?? "Unnamed",
+ lastName: blankToNull(lastName ?? ""),
+ email,
+ phone: blankToNull(field(row, "phone", "Phone Number") ?? ""),
+ title: blankToNull(
+ field(row, "jobtitle", "Job Title", "title") ?? "",
+ ),
+ companyId,
+ ownerId: input.defaultOwnerId ?? null,
+ },
+ });
+
+ reports.push({ line, outcome: "created", key: email, label });
+ } catch (error) {
+ reports.push({
+ line,
+ outcome: "failed",
+ key: email,
+ label,
+ reason: describe(error),
+ });
+ }
+ }
+
+ return reports;
+ }
+
+ private async importDeals(
+ rows: ParsedRow[],
+ input: ImportInput,
+ ): Promise<ImportRowReport[]> {
+ const reports: ImportRowReport[] = [];
+
+ // Deals need an owner — the column is required in our schema — so a file
+ // with no owner and no default cannot be applied at all.
+ const fallbackOwnerId =
+ input.defaultOwnerId ??
+ (await this.db.user.findFirst({ select: { id: true } }))?.id ??
+ null;
+
+ for (const { line, values: row } of rows) {
+ const name = field(row, "dealname", "Deal Name", "name");
+ const companyName = field(row, "company", "Associated Company");
+ const domain = normalizeDomain(
+ field(row, "domain", "Associated Company Domain", "website"),
+ );
+ const label = name ?? null;
+
+ if (!name) {
+ reports.push({
+ line,
+ outcome: "skipped",
+ key: null,
+ label: null,
+ reason: "No deal name.",
+ });
+ continue;
+ }
+
+ const company = await this.findCompany(domain, companyName);
+
+ if (!company) {
+ reports.push({
+ line,
+ outcome: "skipped",
+ key: domain ?? companyName ?? null,
+ label,
+ reason:
+ "No matching company — import companies first, or add the domain column.",
+ });
+ continue;
+ }
+
+ if (!fallbackOwnerId) {
+ reports.push({
+ line,
+ outcome: "skipped",
+ key: name,
+ label,
+ reason: "Every deal needs an owner; pick a default.",
+ });
+ continue;
+ }
+
+ // Deals have no natural key, so "the same name at the same company" is
+ // the closest thing to one. It is what makes a re-run update rather
+ // than duplicate.
+ const existing = await this.db.deal.findFirst({
+ where: { name, companyId: company.id },
+ select: { id: true },
+ });
+
+ if (input.dryRun) {
+ reports.push({
+ line,
+ outcome: existing ? "updated" : "created",
+ key: company.id,
+ label,
+ });
+ continue;
+ }
+
+ try {
+ const stage = resolveStage(
+ field(row, "dealstage", "Deal Stage", "stage"),
+ );
+ const amountCents = parseAmountCents(field(row, "amount"));
+ const closeDate = parseCsvDate(field(row, "closedate", "Close Date"));
+ const closed = isClosedStage(stage);
+
+ const data = {
+ name,
+ companyId: company.id,
+ ownerId: fallbackOwnerId,
+ stage,
+ amount: fromCents(amountCents),
+ expectedCloseDate: closeDate,
+ closedAt: closed ? (closeDate ?? new Date()) : null,
+ };
+
+ if (existing) {
+ await this.db.deal.update({ where: { id: existing.id }, data });
+ reports.push({ line, outcome: "updated", key: company.id, label });
+ } else {
+ await this.db.deal.create({ data });
+ reports.push({ line, outcome: "created", key: company.id, label });
+ }
+ } catch (error) {
+ reports.push({
+ line,
+ outcome: "failed",
+ key: company.id,
+ label,
+ reason: describe(error),
+ });
+ }
+ }
+
+ return reports;
+ }
+
+ /** The company a contact row belongs to: an explicit column, then the email. */
+ private async resolveCompany(
+ row: CsvRow,
+ email: string | null,
+ ): Promise<string | null> {
+ const domain = normalizeDomain(
+ field(row, "domain", "Associated Company Domain", "Company Domain Name"),
+ );
+ const companyName = field(row, "company", "Associated Company");
+
+ const matched = await this.findCompany(domain, companyName);
+ if (matched) return matched.id;
+
+ // Falls back to the agent, which will find or create one from the work
+ // address — the same path a hand-added contact takes.
+ return email ? this.enrichment.companyForEmail(email) : null;
+ }
+
+ private async findCompany(domain: string | null, name: string | undefined) {
+ if (domain) {
+ const byDomain = await this.db.company.findUnique({
+ where: { domain },
+ select: { id: true },
+ });
+ if (byDomain) return byDomain;
+ }
+
+ if (name) {
+ // Name matching is a fallback, and deliberately exact — fuzzy matching
+ // on company names attaches deals to the wrong account.
+ return this.db.company.findFirst({
+ where: { name: { equals: name, mode: "insensitive" } },
+ select: { id: true },
+ });
+ }
+
+ return null;
+ }
+}
+
+function resolveStage(value: string | undefined): DealStage {
+ if (!value) return Stage.DEMO_BOOKED;
+ const key = value.trim().toLowerCase();
+ return (
+ STAGE_ALIASES[key] ??
+ STAGE_ALIASES[key.replace(/[^a-z]/g, "")] ??
+ Stage.DEMO_BOOKED
+ );
+}
+
+function summarise(
+ kind: ImportKind,
+ dryRun: boolean,
+ rows: ImportRowReport[],
+): ImportReport {
+ const count = (outcome: ImportRowReport["outcome"]) =>
+ rows.filter((row) => row.outcome === outcome).length;
+
+ return {
+ kind,
+ dryRun,
+ total: rows.length,
+ created: count("created"),
+ updated: count("updated"),
+ skipped: count("skipped"),
+ failed: count("failed"),
+ rows,
+ };
+}
+
+function describe(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
diff --git a/apps/api/src/logging/all-exceptions.filter.ts b/apps/api/src/logging/all-exceptions.filter.ts
new file mode 100644
index 00000000..7f2cc088
--- /dev/null
+++ b/apps/api/src/logging/all-exceptions.filter.ts
@@ -0,0 +1,105 @@
+import {
+ type ArgumentsHost,
+ Catch,
+ type ExceptionFilter,
+ HttpException,
+ HttpStatus,
+ Logger,
+} from "@nestjs/common";
+import type { Request, Response } from "express";
+import { getRequestContext } from "./request-context";
+
+/**
+ * Logs every exception with its request context and returns a consistent body.
+ *
+ * Nest's built-in filter logs unhandled errors, but without the request id —
+ * which is the one field that makes a production stack trace actionable. The
+ * response shape is left alone apart from `requestId`, so an operator can quote
+ * the id from a failed call and land on the exact log line.
+ */
+@Catch()
+export class AllExceptionsFilter implements ExceptionFilter {
+ private readonly logger = new Logger("ExceptionsHandler");
+
+ catch(exception: unknown, host: ArgumentsHost): void {
+ if (host.getType() !== "http") {
+ throw exception;
+ }
+
+ const http = host.switchToHttp();
+ const request = http.getRequest<Request>();
+ const response = http.getResponse<Response>();
+
+ const status =
+ exception instanceof HttpException
+ ? exception.getStatus()
+ : HttpStatus.INTERNAL_SERVER_ERROR;
+ const requestId = getRequestContext()?.requestId;
+
+ this.log(exception, status, request);
+
+ // A streamed or already-committed response can only be logged, not
+ // rewritten.
+ if (response.headersSent) {
+ return;
+ }
+
+ response.status(status).json(body(exception, status, requestId));
+ }
+
+ private log(exception: unknown, status: number, request: Request): void {
+ const payload = {
+ message: describe(exception),
+ method: request.method,
+ path: request.originalUrl,
+ statusCode: status,
+ exception: exception?.constructor?.name,
+ };
+
+ if (status >= HttpStatus.INTERNAL_SERVER_ERROR) {
+ this.logger.error(
+ payload,
+ exception instanceof Error ? exception.stack : undefined,
+ );
+ return;
+ }
+
+ // The access log already records 4xx as a warning; this adds the reason
+ // for anyone who turns debug on, without doubling up in production.
+ this.logger.debug(payload);
+ }
+}
+
+function describe(exception: unknown): string {
+ if (exception instanceof Error) {
+ return exception.message;
+ }
+
+ return typeof exception === "string" ? exception : "Unknown exception";
+}
+
+function body(
+ exception: unknown,
+ status: number,
+ requestId: string | undefined,
+): Record<string, unknown> {
+ const withRequestId = requestId ? { requestId } : {};
+
+ if (!(exception instanceof HttpException)) {
+ // Never let an unexpected error's message reach the client: it is the
+ // classic way internals leak. The log has the detail.
+ return {
+ statusCode: status,
+ message: "Internal server error",
+ ...withRequestId,
+ };
+ }
+
+ const original = exception.getResponse();
+
+ if (typeof original === "string") {
+ return { statusCode: status, message: original, ...withRequestId };
+ }
+
+ return { ...(original as Record<string, unknown>), ...withRequestId };
+}
diff --git a/apps/api/src/logging/context-logger.ts b/apps/api/src/logging/context-logger.ts
new file mode 100644
index 00000000..3c639518
--- /dev/null
+++ b/apps/api/src/logging/context-logger.ts
@@ -0,0 +1,156 @@
+import { inspect } from "node:util";
+import {
+ ConsoleLogger,
+ type ConsoleLoggerOptions,
+ Injectable,
+ type LogLevel,
+} from "@nestjs/common";
+import { getRequestContext } from "./request-context";
+
+const PRODUCTION_LEVELS: LogLevel[] = ["fatal", "error", "warn", "log"];
+const DEVELOPMENT_LEVELS: LogLevel[] = [
+ "fatal",
+ "error",
+ "warn",
+ "log",
+ "debug",
+ "verbose",
+];
+
+/**
+ * Format and level follow `NODE_ENV` rather than having env vars of their own:
+ * JSON at `log` and above in production, colourised with `debug`/`verbose`
+ * locally. Read live, not captured at import, so tests can flip it.
+ */
+export function consoleLoggerOptions(): ConsoleLoggerOptions {
+ const isProduction = process.env.NODE_ENV === "production";
+
+ return {
+ json: isProduction,
+ colors: !isProduction,
+ timestamp: !isProduction,
+ logLevels: isProduction ? PRODUCTION_LEVELS : DEVELOPMENT_LEVELS,
+ };
+}
+
+/**
+ * A log line with fields attached: `logger.log({ message: "Cache miss", userId })`.
+ *
+ * Nest treats extra arguments as separate messages and prints one line each, so
+ * structured data has to arrive as a single object rather than a second
+ * argument. Fields are hoisted to the top level in JSON and rendered after the
+ * text in development.
+ */
+export type StructuredMessage = { message: string } & Record<string, unknown>;
+
+/** What `ConsoleLogger` emits in JSON mode, plus our correlation fields. */
+interface JsonLogRecord {
+ level: LogLevel;
+ pid: number;
+ timestamp: number;
+ message: unknown;
+ context?: string;
+ stack?: unknown;
+ requestId?: string;
+ userId?: string;
+}
+
+/**
+ * The application logger: `ConsoleLogger` with the current request stitched in,
+ * so a line logged deep inside a service can still be traced back to the call
+ * that caused it.
+ *
+ * Singleton, not request-scoped — the request data comes from
+ * `AsyncLocalStorage`, so there is no reason to pay for a logger instance, and
+ * a fresh dependency graph, per request.
+ */
+@Injectable()
+export class ContextLogger extends ConsoleLogger {
+ constructor() {
+ super(consoleLoggerOptions());
+ }
+
+ protected override getJsonLogObject(
+ message: unknown,
+ options: {
+ context: string;
+ logLevel: LogLevel;
+ writeStreamType?: "stdout" | "stderr";
+ errorStack?: unknown;
+ },
+ ): JsonLogRecord {
+ const base = super.getJsonLogObject(message, options);
+ const request = getRequestContext();
+
+ // Base keys win over caller-supplied fields: a stray `level` in a log
+ // payload must not be able to relabel the line.
+ const record: JsonLogRecord = isStructuredMessage(message)
+ ? { ...withoutMessage(message), ...base, message: message.message }
+ : base;
+
+ if (!request) {
+ return record;
+ }
+
+ return {
+ ...record,
+ requestId: request.requestId,
+ ...(request.userId ? { userId: request.userId } : {}),
+ };
+ }
+
+ /** Renders `{ message, ...fields }` as `text { fields }` instead of Nest's `Object(n) {…}`. */
+ protected override stringifyMessage(
+ message: unknown,
+ logLevel: LogLevel,
+ ): string {
+ if (!isStructuredMessage(message)) {
+ return super.stringifyMessage(message, logLevel);
+ }
+
+ const fields = withoutMessage(message);
+ const text = this.colorize(message.message, logLevel);
+
+ return Object.keys(fields).length === 0
+ ? text
+ : `${text} ${inspect(fields, this.inspectOptions)}`;
+ }
+
+ /**
+ * The pretty path has no field to put a request id in, so it rides along
+ * inside the context bracket: `[AuthService 3f9c1a2b]`.
+ */
+ protected override formatContext(context: string): string {
+ const request = getRequestContext();
+
+ if (!context || !request) {
+ return super.formatContext(context);
+ }
+
+ return super.formatContext(`${context} ${shortId(request.requestId)}`);
+ }
+}
+
+/** Enough of a UUID to eyeball-match lines in a local terminal. */
+export function shortId(requestId: string): string {
+ return requestId.slice(0, 8);
+}
+
+function isStructuredMessage(value: unknown): value is StructuredMessage {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ return false;
+ }
+
+ const prototype = Object.getPrototypeOf(value);
+
+ return (
+ (prototype === Object.prototype || prototype === null) &&
+ typeof (value as { message?: unknown }).message === "string"
+ );
+}
+
+function withoutMessage(value: StructuredMessage): Record<string, unknown> {
+ const { message: _message, ...fields } = value;
+
+ return fields;
+}
diff --git a/apps/api/src/logging/logging.module.ts b/apps/api/src/logging/logging.module.ts
new file mode 100644
index 00000000..4282ec35
--- /dev/null
+++ b/apps/api/src/logging/logging.module.ts
@@ -0,0 +1,38 @@
+import {
+ Global,
+ type MiddlewareConsumer,
+ Module,
+ type NestModule,
+ RequestMethod,
+} from "@nestjs/common";
+import { APP_FILTER, APP_INTERCEPTOR } from "@nestjs/core";
+import { AllExceptionsFilter } from "./all-exceptions.filter";
+import { ContextLogger } from "./context-logger";
+import { PrismaLogBridge } from "./prisma-log.bridge";
+import { RequestLoggerMiddleware } from "./request-logger.middleware";
+import { UserContextInterceptor } from "./user-context.interceptor";
+
+/**
+ * Import this first in `AppModule`. Middleware runs in module-registration
+ * order, and the request context has to be open before anything else — Better
+ * Auth mounts its handler from `configure()` too, and a request that terminates
+ * there would otherwise go unlogged.
+ */
+@Global()
+@Module({
+ providers: [
+ ContextLogger,
+ PrismaLogBridge,
+ { provide: APP_FILTER, useClass: AllExceptionsFilter },
+ { provide: APP_INTERCEPTOR, useClass: UserContextInterceptor },
+ ],
+ exports: [ContextLogger],
+})
+export class LoggingModule implements NestModule {
+ configure(consumer: MiddlewareConsumer): void {
+ consumer
+ .apply(RequestLoggerMiddleware)
+ // Express 5 requires named wildcards; the braces also match `/`.
+ .forRoutes({ path: "{*splat}", method: RequestMethod.ALL });
+ }
+}
diff --git a/apps/api/src/logging/prisma-log.bridge.ts b/apps/api/src/logging/prisma-log.bridge.ts
new file mode 100644
index 00000000..f786e650
--- /dev/null
+++ b/apps/api/src/logging/prisma-log.bridge.ts
@@ -0,0 +1,47 @@
+import { setPrismaLogSink } from "@crm/db";
+import {
+ Injectable,
+ Logger,
+ type OnApplicationShutdown,
+ type OnModuleInit,
+} from "@nestjs/common";
+
+/**
+ * Routes Prisma engine logs through the application logger, so a database
+ * warning is formatted like everything else and carries the request that
+ * triggered it.
+ */
+@Injectable()
+export class PrismaLogBridge implements OnModuleInit, OnApplicationShutdown {
+ private readonly logger = new Logger("Prisma");
+
+ onModuleInit(): void {
+ setPrismaLogSink(({ level, message, target, durationMs }) => {
+ const payload = {
+ message,
+ target,
+ ...(durationMs === undefined ? {} : { durationMs }),
+ };
+
+ if (level === "error") {
+ this.logger.error(payload);
+ return;
+ }
+
+ if (level === "warn") {
+ this.logger.warn(payload);
+ return;
+ }
+
+ // `query` and `info` only fire when PRISMA_LOG_QUERIES is set, and are
+ // debug-level so they stay out of production logs even then.
+ this.logger.debug(payload);
+ });
+ }
+
+ onApplicationShutdown(): void {
+ // The Prisma client outlives the Nest app during a hot reload; leaving a
+ // sink pointing at a torn-down logger would log into nothing.
+ setPrismaLogSink(null);
+ }
+}
diff --git a/apps/api/src/logging/request-context.ts b/apps/api/src/logging/request-context.ts
new file mode 100644
index 00000000..418161e3
--- /dev/null
+++ b/apps/api/src/logging/request-context.ts
@@ -0,0 +1,38 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+
+/**
+ * The per-request facts every log line should carry. Kept deliberately small:
+ * anything larger tends to become a second, untyped request object.
+ */
+export interface RequestContext {
+ requestId: string;
+ method: string;
+ path: string;
+ userId?: string;
+}
+
+const storage = new AsyncLocalStorage<RequestContext>();
+
+/** Runs `fn`, and everything it awaits, with `context` attached. */
+export function runInRequestContext<T>(
+ context: RequestContext,
+ fn: () => T,
+): T {
+ return storage.run(context, fn);
+}
+
+export function getRequestContext(): RequestContext | undefined {
+ return storage.getStore();
+}
+
+/**
+ * The user is only known once the auth guard has run, which is well after the
+ * context is created — so it is filled in rather than passed in.
+ */
+export function setRequestUserId(userId: string): void {
+ const context = storage.getStore();
+
+ if (context) {
+ context.userId = userId;
+ }
+}
diff --git a/apps/api/src/logging/request-logger.middleware.ts b/apps/api/src/logging/request-logger.middleware.ts
new file mode 100644
index 00000000..fdc4b2b7
--- /dev/null
+++ b/apps/api/src/logging/request-logger.middleware.ts
@@ -0,0 +1,132 @@
+import { randomUUID } from "node:crypto";
+import { Injectable, Logger, type NestMiddleware } from "@nestjs/common";
+import type { NextFunction, Request, Response } from "express";
+import { type RequestContext, runInRequestContext } from "./request-context";
+
+const REQUEST_ID_HEADER = "x-request-id";
+
+/** Liveness probes are the loudest thing in the log and the least interesting. */
+const QUIET_PATHS = new Set(["/health"]);
+
+/**
+ * Opens the request context and writes one access line per request.
+ *
+ * Deliberately logs no headers, query string or body: this is a CRM, and all
+ * three routinely carry credentials and personal data. Anything worth logging
+ * from a payload should be logged explicitly by the handler that understands it.
+ */
+@Injectable()
+export class RequestLoggerMiddleware implements NestMiddleware {
+ private readonly logger = new Logger("HTTP");
+
+ use(request: Request, response: Response, next: NextFunction): void {
+ const requestId = incomingRequestId(request) ?? randomUUID();
+ response.setHeader(REQUEST_ID_HEADER, requestId);
+
+ const context: RequestContext = {
+ requestId,
+ method: request.method,
+ path: request.originalUrl,
+ };
+ const startedAt = process.hrtime.bigint();
+
+ runInRequestContext(context, () => {
+ response.on("finish", () => {
+ // `finish` is emitted from the socket's async context rather than
+ // ours, so the context is re-entered explicitly, not inherited.
+ runInRequestContext(context, () => {
+ this.logCompleted(request, response, context, startedAt);
+ });
+ });
+
+ next();
+ });
+ }
+
+ private logCompleted(
+ request: Request,
+ response: Response,
+ context: RequestContext,
+ startedAt: bigint,
+ ): void {
+ const durationMs = Number(process.hrtime.bigint() - startedAt) / 1_000_000;
+ const { statusCode } = response;
+
+ // The auth guard resolves the session long after the context is opened,
+ // so this is the first point at which the user is reliably known.
+ const userId = sessionUserId(request);
+
+ if (userId) {
+ context.userId = userId;
+ }
+
+ const payload = {
+ message: `${context.method} ${context.path} ${statusCode} ${durationMs.toFixed(1)}ms`,
+ method: context.method,
+ path: context.path,
+ statusCode,
+ durationMs: Number(durationMs.toFixed(1)),
+ ip: request.ip,
+ userAgent: request.get("user-agent"),
+ };
+
+ if (statusCode >= 500) {
+ this.logger.error(payload);
+ return;
+ }
+
+ if (statusCode >= 400) {
+ this.logger.warn(payload);
+ return;
+ }
+
+ if (QUIET_PATHS.has(request.path)) {
+ this.logger.verbose(payload);
+ return;
+ }
+
+ this.logger.log(payload);
+ }
+}
+
+/**
+ * A proxy or upstream service may already have stamped the request; reusing its
+ * id is what makes a trace span more than one hop.
+ */
+function incomingRequestId(request: Request): string | undefined {
+ const header = request.get(REQUEST_ID_HEADER);
+
+ // Untrusted input that ends up in every log line for this request, so it is
+ // length-capped and stripped of anything that could forge a second field.
+ if (!header || header.length > 200 || !/^[\w.:-]+$/.test(header)) {
+ return undefined;
+ }
+
+ return header;
+}
+
+const sharedInstance = new RequestLoggerMiddleware();
+
+/**
+ * Better Auth mounts its handler directly onto the HTTP adapter while its
+ * module is being configured — before Nest applies anything registered through
+ * `MiddlewareConsumer` — so `/api/auth/*` terminates before the class above
+ * ever runs. Its `middleware` option is the supported way in, and it is only
+ * invoked for requests Better Auth itself will handle, so nothing is logged
+ * twice.
+ */
+export function logAuthRoute(
+ request: Request,
+ response: Response,
+ next: NextFunction,
+): void {
+ sharedInstance.use(request, response, next);
+}
+
+function sessionUserId(request: Request): string | undefined {
+ const { session } = request as Request & {
+ session?: { user?: { id?: string } };
+ };
+
+ return session?.user?.id;
+}
diff --git a/apps/api/src/logging/user-context.interceptor.ts b/apps/api/src/logging/user-context.interceptor.ts
new file mode 100644
index 00000000..49bc31c9
--- /dev/null
+++ b/apps/api/src/logging/user-context.interceptor.ts
@@ -0,0 +1,36 @@
+import {
+ type CallHandler,
+ type ExecutionContext,
+ Injectable,
+ type NestInterceptor,
+} from "@nestjs/common";
+import type { Request } from "express";
+import type { Observable } from "rxjs";
+import { setRequestUserId } from "./request-context";
+
+/**
+ * Copies the authenticated user id into the request context once the auth guard
+ * has resolved the session, so logs written by handlers and services carry it.
+ *
+ * Interceptors run after guards, which is the earliest point where
+ * `request.session` is populated by `@thallesp/nestjs-better-auth`.
+ */
+@Injectable()
+export class UserContextInterceptor implements NestInterceptor {
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
+ if (context.getType() !== "http") {
+ return next.handle();
+ }
+
+ const request = context
+ .switchToHttp()
+ .getRequest<Request & { session?: { user?: { id?: string } } }>();
+ const userId = request.session?.user?.id;
+
+ if (userId) {
+ setRequestUserId(userId);
+ }
+
+ return next.handle();
+ }
+}
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
new file mode 100644
index 00000000..b02da4de
--- /dev/null
+++ b/apps/api/src/main.ts
@@ -0,0 +1,42 @@
+import { Logger, ValidationPipe } from "@nestjs/common";
+import { NestFactory } from "@nestjs/core";
+import helmet from "helmet";
+import { AppModule } from "./app.module";
+import { ContextLogger } from "./logging/context-logger";
+
+async function bootstrap() {
+ const logger = new ContextLogger();
+
+ const app = await NestFactory.create(AppModule, {
+ bodyParser: false,
+ logger,
+ });
+
+ app.use(helmet());
+ app.useGlobalPipes(
+ new ValidationPipe({
+ whitelist: true,
+ forbidNonWhitelisted: true,
+ transform: true,
+ transformOptions: { enableImplicitConversion: true },
+ }),
+ );
+ app.enableShutdownHooks();
+
+ const port = process.env.PORT ?? 3001;
+ await app.listen(port);
+
+ new Logger("Bootstrap").log({
+ message: `API listening on http://localhost:${port}`,
+ port: Number(port),
+ environment: process.env.NODE_ENV ?? "development",
+ });
+}
+
+void bootstrap().catch((error: unknown) => {
+ new Logger("Bootstrap").fatal(
+ { message: "API failed to start" },
+ error instanceof Error ? error.stack : String(error),
+ );
+ process.exit(1);
+});
diff --git a/apps/api/src/search/search.module.ts b/apps/api/src/search/search.module.ts
new file mode 100644
index 00000000..3bbe1c82
--- /dev/null
+++ b/apps/api/src/search/search.module.ts
@@ -0,0 +1,10 @@
+import { Module } from "@nestjs/common";
+import { TrpcModule } from "../trpc/trpc.module";
+import { SearchRouter } from "./search.router";
+import { SearchService } from "./search.service";
+
+@Module({
+ imports: [TrpcModule],
+ providers: [SearchService, SearchRouter],
+})
+export class SearchModule {}
diff --git a/apps/api/src/search/search.router.ts b/apps/api/src/search/search.router.ts
new file mode 100644
index 00000000..b6507a61
--- /dev/null
+++ b/apps/api/src/search/search.router.ts
@@ -0,0 +1,19 @@
+import { Inject } from "@nestjs/common";
+import { Input, Query, Router, UseMiddlewares } from "nestjs-trpc";
+import { z } from "zod";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { SearchService } from "./search.service";
+
+const quickInput = z.object({ q: z.string().default("") });
+
+@Router({ alias: "search" })
+@UseMiddlewares(AuthMiddleware)
+export class SearchRouter {
+ constructor(@Inject(SearchService) private readonly search: SearchService) {}
+
+ /** Backs the ⌘K switcher. */
+ @Query({ input: quickInput })
+ async quick(@Input("q") q: string) {
+ return this.search.quick(q);
+ }
+}
diff --git a/apps/api/src/search/search.service.ts b/apps/api/src/search/search.service.ts
new file mode 100644
index 00000000..59f0da47
--- /dev/null
+++ b/apps/api/src/search/search.service.ts
@@ -0,0 +1,109 @@
+import type { Db } from "@crm/db";
+import { Injectable } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+
+/** One hit in the quick switcher. */
+export type SearchHit = {
+ kind: "company" | "contact" | "deal";
+ id: string;
+ label: string;
+ /** The line under the label — domain, company, whatever identifies it. */
+ detail: string | null;
+ iconUrl: string | null;
+};
+
+/** Per kind. Enough to be useful, few enough that the list stays scannable. */
+const PER_KIND = 5;
+
+@Injectable()
+export class SearchService {
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ /**
+ * Everything matching one query string, across the three objects.
+ *
+ * Three indexed `contains` queries in parallel rather than a union view: the
+ * result has to be grouped by kind for the UI anyway, and this keeps each
+ * one's ordering and fields its own business.
+ */
+ async quick(q: string): Promise<{ hits: SearchHit[] }> {
+ const term = q.trim();
+ if (term.length < 2) return { hits: [] };
+
+ const [companies, contacts, deals] = await Promise.all([
+ this.db.company.findMany({
+ where: {
+ OR: [
+ { name: { contains: term, mode: "insensitive" } },
+ { domain: { contains: term, mode: "insensitive" } },
+ ],
+ },
+ take: PER_KIND,
+ orderBy: { name: "asc" },
+ select: { id: true, name: true, domain: true, iconUrl: true },
+ }),
+ this.db.contact.findMany({
+ where: {
+ OR: [
+ { firstName: { contains: term, mode: "insensitive" } },
+ { lastName: { contains: term, mode: "insensitive" } },
+ { email: { contains: term, mode: "insensitive" } },
+ ],
+ },
+ take: PER_KIND,
+ orderBy: [{ lastName: "asc" }, { firstName: "asc" }],
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ email: true,
+ company: { select: { name: true } },
+ },
+ }),
+ this.db.deal.findMany({
+ where: { name: { contains: term, mode: "insensitive" } },
+ take: PER_KIND,
+ orderBy: [{ stage: "asc" }, { name: "asc" }],
+ select: {
+ id: true,
+ name: true,
+ company: { select: { name: true, iconUrl: true } },
+ },
+ }),
+ ]);
+
+ return {
+ hits: [
+ ...companies.map(
+ (company): SearchHit => ({
+ kind: "company",
+ id: company.id,
+ label: company.name,
+ detail: company.domain,
+ iconUrl: company.iconUrl,
+ }),
+ ),
+ ...contacts.map(
+ (contact): SearchHit => ({
+ kind: "contact",
+ id: contact.id,
+ label:
+ [contact.firstName, contact.lastName].filter(Boolean).join(" ") ||
+ (contact.email ?? "Unnamed"),
+ detail: contact.company?.name ?? contact.email,
+ iconUrl: null,
+ }),
+ ),
+ ...deals.map(
+ (deal): SearchHit => ({
+ kind: "deal",
+ id: deal.id,
+ label: deal.name,
+ detail: deal.company.name,
+ iconUrl: deal.company.iconUrl,
+ }),
+ ),
+ ],
+ };
+ }
+}
diff --git a/apps/api/src/trpc/context.types.ts b/apps/api/src/trpc/context.types.ts
new file mode 100644
index 00000000..fb7029d2
--- /dev/null
+++ b/apps/api/src/trpc/context.types.ts
@@ -0,0 +1,12 @@
+import type { Session, SessionUser } from "@crm/auth";
+import type { Request } from "express";
+
+export type BaseTrpcContext = {
+ req?: Request;
+ session: Session | null;
+};
+
+/** What every procedure behind `AuthMiddleware` sees. */
+export type AuthedTrpcContext = BaseTrpcContext & {
+ user: SessionUser;
+};
diff --git a/apps/api/src/trpc/list-input.ts b/apps/api/src/trpc/list-input.ts
new file mode 100644
index 00000000..96cabcb3
--- /dev/null
+++ b/apps/api/src/trpc/list-input.ts
@@ -0,0 +1,97 @@
+import { z } from "zod";
+
+/**
+ * The shape every list procedure speaks, so one `DataTable` on the front end can
+ * drive companies, contacts and deals without per-module plumbing.
+ *
+ * Filtering, sorting and pagination all happen in Prisma — the browser never
+ * receives more rows than it draws.
+ */
+export const listInput = z.object({
+ q: z.string().default(""),
+ sort: z.string().default(""),
+ dir: z.enum(["asc", "desc"]).default("asc"),
+ page: z.number().int().min(1).default(1),
+ pageSize: z.number().int().min(1).max(100).default(25),
+});
+
+export type ListInput = z.infer<typeof listInput>;
+
+/** Facet id → value → number of rows that would match. */
+export type FacetCounts = Record<string, Record<string, number>>;
+
+export type ListResult<TRow> = {
+ rows: TRow[];
+ total: number;
+ facetCounts: FacetCounts;
+};
+
+/** `skip`/`take` for a 1-based page number. */
+export function paginate(input: Pick<ListInput, "page" | "pageSize">): {
+ skip: number;
+ take: number;
+} {
+ return {
+ skip: (input.page - 1) * input.pageSize,
+ take: input.pageSize,
+ };
+}
+
+/**
+ * Resolves the requested sort column against the columns a module actually
+ * allows, so `?sort=` can never reach Prisma as an arbitrary field name.
+ *
+ * `orderBy` entries are spelled out per module rather than built from the
+ * column id, because sorting by a relation (`company.name`) or an aggregate is
+ * not a flat `{ [id]: dir }`.
+ */
+export function resolveOrderBy<TOrderBy>(
+ input: Pick<ListInput, "sort" | "dir">,
+ columns: Record<string, (dir: "asc" | "desc") => TOrderBy>,
+ fallback: TOrderBy,
+): TOrderBy {
+ const column = columns[input.sort];
+ return column ? column(input.dir) : fallback;
+}
+
+/**
+ * Turns a `groupBy` result into `{ value: count }`.
+ *
+ * Rows whose grouped value is null are dropped unless `nullKey` is given —
+ * "unassigned" is a facet worth offering, "(blank industry)" usually is not.
+ */
+export function countsByKey<
+ TKey extends string,
+ TGroup extends { _count: { _all: number } } & {
+ [K in TKey]?: string | null;
+ },
+>(groups: TGroup[], key: TKey, nullKey?: string): Record<string, number> {
+ const counts: Record<string, number> = {};
+
+ for (const group of groups) {
+ const value = group[key] ?? nullKey;
+ if (value == null) continue;
+ counts[value] = (counts[value] ?? 0) + group._count._all;
+ }
+
+ return counts;
+}
+
+/** The facet value meaning "no filter". Every list procedure defaults to it. */
+export const FACET_ALL = "all";
+
+/** The facet value meaning "nobody owns this". */
+export const FACET_UNASSIGNED = "unassigned";
+
+/**
+ * `ownerId` filter for an owner facet selection.
+ *
+ * Returns `undefined` for "all" so the caller can spread it into a `where`
+ * without a branch.
+ */
+export function ownerFilter(
+ value: string,
+): { ownerId: string | null } | undefined {
+ if (value === FACET_ALL) return undefined;
+ return { ownerId: value === FACET_UNASSIGNED ? null : value };
+}
diff --git a/apps/api/src/trpc/middlewares/auth.middleware.ts b/apps/api/src/trpc/middlewares/auth.middleware.ts
new file mode 100644
index 00000000..1ef17869
--- /dev/null
+++ b/apps/api/src/trpc/middlewares/auth.middleware.ts
@@ -0,0 +1,32 @@
+import { Injectable } from "@nestjs/common";
+import { TRPCError } from "@trpc/server";
+import type {
+ MiddlewareOptions,
+ MiddlewareResponse,
+ TRPCMiddleware,
+} from "nestjs-trpc";
+import { setRequestUserId } from "../../logging/request-context";
+import type { AuthedTrpcContext, BaseTrpcContext } from "../context.types";
+
+/**
+ * Google sign-in is the only door, so "signed in" is the whole authorisation
+ * model — there are no organizations, roles or permissions in this CRM.
+ */
+@Injectable()
+export class AuthMiddleware implements TRPCMiddleware {
+ async use(opts: MiddlewareOptions): Promise<MiddlewareResponse> {
+ const ctx = opts.ctx as BaseTrpcContext;
+ const user = ctx.session?.user;
+
+ if (!user) {
+ throw new TRPCError({ code: "UNAUTHORIZED" });
+ }
+
+ // tRPC calls arrive as one HTTP request per batch, so the interceptor that
+ // stamps `userId` for REST routes never runs. Stamp it here instead.
+ setRequestUserId(user.id);
+
+ const nextCtx: AuthedTrpcContext = { ...ctx, user };
+ return opts.next({ ctx: nextCtx });
+ }
+}
diff --git a/apps/api/src/trpc/middlewares/domain-error.middleware.ts b/apps/api/src/trpc/middlewares/domain-error.middleware.ts
new file mode 100644
index 00000000..95e0d134
--- /dev/null
+++ b/apps/api/src/trpc/middlewares/domain-error.middleware.ts
@@ -0,0 +1,62 @@
+import { HttpException, Injectable } from "@nestjs/common";
+import { TRPCError } from "@trpc/server";
+import type {
+ MiddlewareOptions,
+ MiddlewareResponse,
+ TRPCMiddleware,
+} from "nestjs-trpc";
+
+type TrpcErrorCode =
+ | "BAD_REQUEST"
+ | "UNAUTHORIZED"
+ | "FORBIDDEN"
+ | "NOT_FOUND"
+ | "CONFLICT"
+ | "TOO_MANY_REQUESTS"
+ | "INTERNAL_SERVER_ERROR";
+
+function statusToTrpcCode(status: number): TrpcErrorCode {
+ switch (status) {
+ case 400:
+ return "BAD_REQUEST";
+ case 401:
+ return "UNAUTHORIZED";
+ case 403:
+ return "FORBIDDEN";
+ case 404:
+ return "NOT_FOUND";
+ case 409:
+ return "CONFLICT";
+ case 429:
+ return "TOO_MANY_REQUESTS";
+ default:
+ return "INTERNAL_SERVER_ERROR";
+ }
+}
+
+/**
+ * Services throw Nest's `HttpException` family because they are also reachable
+ * from REST controllers. Without this, a `NotFoundException` from a service
+ * would reach the browser as a 500 with no message.
+ */
+@Injectable()
+export class DomainErrorMiddleware implements TRPCMiddleware {
+ async use(opts: MiddlewareOptions): Promise<MiddlewareResponse> {
+ const result = await opts.next();
+
+ if (result.ok) {
+ return result;
+ }
+
+ const cause = (result.error as { cause?: unknown } | undefined)?.cause;
+
+ if (cause instanceof HttpException) {
+ throw new TRPCError({
+ code: statusToTrpcCode(cause.getStatus()),
+ message: cause.message,
+ });
+ }
+
+ return result;
+ }
+}
diff --git a/apps/api/src/trpc/middlewares/logging.middleware.ts b/apps/api/src/trpc/middlewares/logging.middleware.ts
new file mode 100644
index 00000000..a00448b4
--- /dev/null
+++ b/apps/api/src/trpc/middlewares/logging.middleware.ts
@@ -0,0 +1,27 @@
+import { Injectable, Logger } from "@nestjs/common";
+import type {
+ MiddlewareOptions,
+ MiddlewareResponse,
+ TRPCMiddleware,
+} from "nestjs-trpc";
+
+@Injectable()
+export class LoggingMiddleware implements TRPCMiddleware {
+ private readonly logger = new Logger("tRPC");
+
+ async use(opts: MiddlewareOptions): Promise<MiddlewareResponse> {
+ const startedAt = Date.now();
+ const result = await opts.next();
+ const durationMs = Date.now() - startedAt;
+
+ this.logger.log({
+ message: `${opts.type} ${opts.path} ${result.ok ? "ok" : "err"} ${durationMs}ms`,
+ type: opts.type,
+ path: opts.path,
+ outcome: result.ok ? "ok" : "err",
+ durationMs,
+ });
+
+ return result;
+ }
+}
diff --git a/apps/api/src/trpc/trpc-error.handler.ts b/apps/api/src/trpc/trpc-error.handler.ts
new file mode 100644
index 00000000..f9dddb46
--- /dev/null
+++ b/apps/api/src/trpc/trpc-error.handler.ts
@@ -0,0 +1,22 @@
+import { Injectable, Logger } from "@nestjs/common";
+import type { OnErrorOptions, TRPCErrorHandler } from "nestjs-trpc";
+
+@Injectable()
+export class TrpcErrorHandler implements TRPCErrorHandler {
+ private readonly logger = new Logger("tRPC");
+
+ onError(opts: OnErrorOptions): void {
+ const { error, type, path } = opts;
+ const message = `${type} ${path ?? "<unknown>"} ${error.code}`;
+
+ if (error.code === "INTERNAL_SERVER_ERROR") {
+ this.logger.error(
+ { message, type, path, code: error.code },
+ error.stack ?? String(error.cause ?? error),
+ );
+ return;
+ }
+
+ this.logger.warn({ message, type, path, code: error.code });
+ }
+}
diff --git a/apps/api/src/trpc/trpc.context.ts b/apps/api/src/trpc/trpc.context.ts
new file mode 100644
index 00000000..bc351368
--- /dev/null
+++ b/apps/api/src/trpc/trpc.context.ts
@@ -0,0 +1,20 @@
+import { auth } from "@crm/auth";
+import { Injectable } from "@nestjs/common";
+import { fromNodeHeaders } from "better-auth/node";
+import type { ContextOptions, TRPCContext } from "nestjs-trpc";
+import type { BaseTrpcContext } from "./context.types";
+
+@Injectable()
+export class TrpcContext implements TRPCContext {
+ async create(opts: ContextOptions): Promise<BaseTrpcContext> {
+ const req = "req" in opts ? opts.req : undefined;
+ // A missing or expired cookie is an anonymous request, not an error —
+ // `AuthMiddleware` is what turns that into UNAUTHORIZED.
+ const session = req
+ ? await auth.api
+ .getSession({ headers: fromNodeHeaders(req.headers) })
+ .catch(() => null)
+ : null;
+ return { req, session };
+ }
+}
diff --git a/apps/api/src/trpc/trpc.module.ts b/apps/api/src/trpc/trpc.module.ts
new file mode 100644
index 00000000..57fabf39
--- /dev/null
+++ b/apps/api/src/trpc/trpc.module.ts
@@ -0,0 +1,29 @@
+import { Module } from "@nestjs/common";
+import { TRPCModule } from "nestjs-trpc";
+import { ContextLogger } from "../logging/context-logger";
+import { AuthMiddleware } from "./middlewares/auth.middleware";
+import { DomainErrorMiddleware } from "./middlewares/domain-error.middleware";
+import { LoggingMiddleware } from "./middlewares/logging.middleware";
+import { TrpcContext } from "./trpc.context";
+import { TrpcErrorHandler } from "./trpc-error.handler";
+
+@Module({
+ imports: [
+ TRPCModule.forRoot({
+ basePath: "/api/trpc",
+ context: TrpcContext,
+ logger: new ContextLogger(),
+ onError: TrpcErrorHandler,
+ globalMiddlewares: [LoggingMiddleware, DomainErrorMiddleware],
+ }),
+ ],
+ providers: [
+ TrpcContext,
+ TrpcErrorHandler,
+ LoggingMiddleware,
+ DomainErrorMiddleware,
+ AuthMiddleware,
+ ],
+ exports: [AuthMiddleware],
+})
+export class TrpcModule {}
diff --git a/apps/api/src/users/users.module.ts b/apps/api/src/users/users.module.ts
new file mode 100644
index 00000000..f7052425
--- /dev/null
+++ b/apps/api/src/users/users.module.ts
@@ -0,0 +1,12 @@
+import { Module } from "@nestjs/common";
+import { AuthModule } from "../auth/auth.module";
+import { TrpcModule } from "../trpc/trpc.module";
+import { UsersRouter } from "./users.router";
+import { UsersService } from "./users.service";
+
+@Module({
+ imports: [AuthModule, TrpcModule],
+ providers: [UsersService, UsersRouter],
+ exports: [UsersService],
+})
+export class UsersModule {}
diff --git a/apps/api/src/users/users.router.ts b/apps/api/src/users/users.router.ts
new file mode 100644
index 00000000..22f91d30
--- /dev/null
+++ b/apps/api/src/users/users.router.ts
@@ -0,0 +1,30 @@
+import { Inject } from "@nestjs/common";
+import { Ctx, Query, Router, UseMiddlewares } from "nestjs-trpc";
+import { AuthService } from "../auth/auth.service";
+import type { AuthedTrpcContext } from "../trpc/context.types";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { UsersService } from "./users.service";
+
+@Router({ alias: "users" })
+@UseMiddlewares(AuthMiddleware)
+export class UsersRouter {
+ constructor(
+ @Inject(UsersService) private readonly users: UsersService,
+ @Inject(AuthService) private readonly auth: AuthService,
+ ) {}
+
+ /**
+ * The signed-in user, read from the row rather than the session snapshot, so
+ * a name or avatar change shows up without signing out.
+ */
+ @Query()
+ async me(@Ctx() ctx: AuthedTrpcContext) {
+ return this.auth.getProfile(ctx.user.id);
+ }
+
+ /** Owner pickers. */
+ @Query()
+ async list() {
+ return this.users.list();
+ }
+}
diff --git a/apps/api/src/users/users.service.ts b/apps/api/src/users/users.service.ts
new file mode 100644
index 00000000..e64ba9e2
--- /dev/null
+++ b/apps/api/src/users/users.service.ts
@@ -0,0 +1,29 @@
+import type { Db } from "@crm/db";
+import { Injectable } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+
+export interface UserOption {
+ id: string;
+ name: string;
+ email: string;
+ image: string | null;
+}
+
+@Injectable()
+export class UsersService {
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ /**
+ * Everyone who can own a company, contact or deal.
+ *
+ * There are no roles here — a user row exists because someone signed in with
+ * a Google account, and that is exactly the set of people work can be
+ * assigned to.
+ */
+ async list(): Promise<UserOption[]> {
+ return this.db.user.findMany({
+ select: { id: true, name: true, email: true, image: true },
+ orderBy: [{ name: "asc" }, { email: "asc" }],
+ });
+ }
+}
diff --git a/apps/api/test/auth.e2e.spec.ts b/apps/api/test/auth.e2e.spec.ts
new file mode 100644
index 00000000..f3d483b6
--- /dev/null
+++ b/apps/api/test/auth.e2e.spec.ts
@@ -0,0 +1,64 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import type { INestApplication } from "@nestjs/common";
+import { Test, type TestingModule } from "@nestjs/testing";
+import request from "supertest";
+
+/** Only fills a variable that is missing or blank — `.env` ships empty OAuth
+ * placeholders, and an empty string still fails validation. */
+const fallback = (key: string, value: string) => {
+ if (!process.env[key]) {
+ process.env[key] = value;
+ }
+};
+
+// `ConfigModule.forRoot()` validates the environment while `AppModule` is being
+// evaluated, so these have to land before that module is imported — hence the
+// dynamic import below. Real values win; these only keep the suite runnable
+// somewhere without credentials, such as CI.
+fallback(
+ "DATABASE_URL",
+ "postgresql://postgres:postgres@localhost:5432/crm?schema=public",
+);
+fallback("BETTER_AUTH_SECRET", "test-secret-at-least-32-characters-long");
+fallback("BETTER_AUTH_URL", "http://localhost:3001");
+fallback("GOOGLE_CLIENT_ID", "test-google-client-id");
+fallback("GOOGLE_CLIENT_SECRET", "test-google-client-secret");
+
+describe("Auth (e2e)", () => {
+ let app: INestApplication;
+
+ beforeAll(async () => {
+ const { AppModule } = await import("../src/app.module");
+
+ const moduleFixture: TestingModule = await Test.createTestingModule({
+ imports: [AppModule],
+ }).compile();
+
+ app = moduleFixture.createNestApplication({ bodyParser: false });
+ await app.init();
+ });
+
+ afterAll(async () => {
+ await app.close();
+ });
+
+ it("rejects an unauthenticated request to a guarded route", async () => {
+ await request(app.getHttpServer()).get("/auth/me").expect(401);
+ });
+
+ it("allows an unauthenticated request to an optional-auth route", async () => {
+ const response = await request(app.getHttpServer())
+ .get("/auth/session")
+ .expect(200);
+
+ expect(response.body).toEqual({ authenticated: false, user: null });
+ });
+
+ // Asserting the route is mounted rather than that it succeeds: Better Auth
+ // stores rate limits in the database, so a 200 here needs a live Postgres.
+ it("mounts the Better Auth handler", async () => {
+ const response = await request(app.getHttpServer()).get("/api/auth/ok");
+
+ expect(response.status).not.toBe(404);
+ });
+});
diff --git a/apps/api/test/csv.spec.ts b/apps/api/test/csv.spec.ts
new file mode 100644
index 00000000..bde9c775
--- /dev/null
+++ b/apps/api/test/csv.spec.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from "bun:test";
+import {
+ field,
+ parseAmountCents,
+ parseCsv,
+ parseCsvDate,
+} from "../src/import/csv";
+
+describe("parseCsv", () => {
+ it("reads a plain file and reports the spreadsheet line", () => {
+ expect(
+ parseCsv("name,domain\nStripe,stripe.com\nLinear,linear.app"),
+ ).toEqual([
+ { line: 2, values: { name: "Stripe", domain: "stripe.com" } },
+ { line: 3, values: { name: "Linear", domain: "linear.app" } },
+ ]);
+ });
+
+ it("keeps line numbers honest when blank rows are skipped", () => {
+ // A report that says "fix row 5" has to mean row 5 in the file, not the
+ // fifth row that happened to have data in it.
+ const rows = parseCsv("name\nStripe\n\n\nLinear\n");
+
+ expect(rows.map((row) => [row.line, row.values.name])).toEqual([
+ [2, "Stripe"],
+ [5, "Linear"],
+ ]);
+ });
+
+ it("normalises header spelling so any HubSpot export lands", () => {
+ const [parsed] = parseCsv("First Name,Company Domain Name\nAda,stripe.com");
+
+ expect(parsed?.values.firstname).toBe("Ada");
+ expect(parsed?.values.companydomainname).toBe("stripe.com");
+ });
+
+ it("handles quoted fields, commas and escaped quotes", () => {
+ const [parsed] = parseCsv(
+ 'name,note\n"Acme, Inc.","They said ""maybe"" twice"',
+ );
+
+ expect(parsed?.values.name).toBe("Acme, Inc.");
+ expect(parsed?.values.note).toBe('They said "maybe" twice');
+ });
+
+ it("keeps newlines inside a quoted field", () => {
+ const [parsed] = parseCsv('name,note\nAcme,"line one\nline two"');
+
+ expect(parsed?.values.note).toBe("line one\nline two");
+ });
+
+ it("copes with CRLF, a trailing newline and blank lines", () => {
+ expect(
+ parseCsv("name\r\nStripe\r\n\r\nLinear\r\n").map((row) => row.values),
+ ).toEqual([{ name: "Stripe" }, { name: "Linear" }]);
+ });
+
+ it("returns nothing for an empty or header-only file", () => {
+ expect(parseCsv("")).toEqual([]);
+ expect(parseCsv("name,domain")).toEqual([]);
+ });
+
+ it("does not let a short row shift the columns", () => {
+ const [parsed] = parseCsv("name,domain,phone\nStripe,stripe.com");
+
+ expect(parsed?.values.name).toBe("Stripe");
+ expect(parsed?.values.domain).toBe("stripe.com");
+ expect(parsed?.values.phone).toBe("");
+ });
+});
+
+describe("field", () => {
+ it("takes the first alias that has a value", () => {
+ const [parsed] = parseCsv("First Name,name\n,Stripe");
+ if (!parsed) throw new Error("expected a row");
+
+ expect(field(parsed.values, "firstname", "name")).toBe("Stripe");
+ expect(field(parsed.values, "nothing", "here")).toBeUndefined();
+ });
+});
+
+describe("parseAmountCents", () => {
+ it("reads what HubSpot writes", () => {
+ expect(parseAmountCents("1,234.50")).toBe(123450);
+ expect(parseAmountCents("$1,234.50")).toBe(123450);
+ expect(parseAmountCents("24000")).toBe(2400000);
+ // Floats are rounded to cents rather than carried as fractions.
+ expect(parseAmountCents("0.1")).toBe(10);
+ });
+
+ it("treats an empty or junk cell as no amount", () => {
+ for (const value of ["", " ", "n/a", "-", undefined]) {
+ expect(parseAmountCents(value)).toBeNull();
+ }
+ });
+});
+
+describe("parseCsvDate", () => {
+ it("parses a date, and drops one it cannot", () => {
+ expect(parseCsvDate("2026-12-31")?.toISOString()).toBe(
+ "2026-12-31T00:00:00.000Z",
+ );
+ expect(parseCsvDate("not a date")).toBeNull();
+ expect(parseCsvDate("")).toBeNull();
+ expect(parseCsvDate(undefined)).toBeNull();
+ });
+});
diff --git a/apps/api/test/enrichment.integration.spec.ts b/apps/api/test/enrichment.integration.spec.ts
new file mode 100644
index 00000000..f3db16e9
--- /dev/null
+++ b/apps/api/test/enrichment.integration.spec.ts
@@ -0,0 +1,394 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+
+/**
+ * The enrichment pipeline end to end, against a stub Context.dev.
+ *
+ * The SDK reads `CONTEXT_DEV_BASE_URL` from the environment, so pointing it at
+ * a local server needs no production code — everything below is the real
+ * client, the real queue, the real mapping and the real database. What it does
+ * *not* prove is that Context.dev's live payloads match the documented schema;
+ * only a real key does that.
+ *
+ * Set before importing anything that constructs the client.
+ */
+const stubResponses: Record<string, () => Response> = {};
+const requests: { path: string; body: unknown }[] = [];
+
+const server = Bun.serve({
+ port: 0,
+ fetch: async (request) => {
+ const path = new URL(request.url).pathname;
+ const body = await request.json().catch(() => null);
+ requests.push({ path, body });
+
+ const key = routeKey(path, body);
+ const handler = stubResponses[key] ?? stubResponses[path];
+
+ return (
+ handler?.() ?? Response.json({ error_code: "NOT_FOUND" }, { status: 400 })
+ );
+ },
+});
+
+/** Brand lookups all share one path, so the discriminator picks the case. */
+function routeKey(path: string, body: unknown): string {
+ const identifier =
+ body && typeof body === "object"
+ ? ((body as Record<string, unknown>).domain ??
+ (body as Record<string, unknown>).email)
+ : undefined;
+ return typeof identifier === "string" ? `${path}:${identifier}` : path;
+}
+
+process.env.CONTEXT_DEV_API_KEY = "ctxt_test_key";
+process.env.CONTEXT_DEV_BASE_URL = `http://localhost:${server.port}/v1`;
+process.env.DATABASE_URL ??=
+ "postgresql://postgres:postgres@localhost:5432/crm?schema=public";
+
+const { db } = await import("@crm/db");
+const { ContextDevClient } = await import(
+ "../src/enrichment/context-dev.client"
+);
+const { EnrichmentQueue } = await import("../src/enrichment/enrichment.queue");
+const { EnrichmentService } = await import(
+ "../src/enrichment/enrichment.service"
+);
+
+/** The real queue, with the five-second backoff wound down. */
+class FastQueue extends EnrichmentQueue {
+ protected override get retryDelayMs(): number {
+ return 5;
+ }
+}
+
+/** `ConfigService`, as much of it as the client uses. */
+const config = {
+ get: (key: string) => process.env[key],
+} as never;
+
+const STRIPE_BRAND = {
+ status: "ok",
+ code: 200,
+ brand: {
+ domain: "enrich-test.example",
+ title: "Enrich Test",
+ description: "Payments infrastructure for the internet.",
+ slogan: "Ignored — description wins.",
+ email: "[email protected]",
+ phone: "+1 888 555 0100",
+ colors: [{ hex: "#635bff", name: "Meteor Shower" }],
+ logos: [
+ { url: "https://cdn/dark.svg", mode: "dark", type: "logo" },
+ { url: "https://cdn/light.svg", mode: "light", type: "logo" },
+ { url: "https://cdn/icon.svg", mode: "light", type: "icon" },
+ ],
+ socials: [
+ { type: "linkedin", url: "https://linkedin.com/company/enrich-test" },
+ { type: "x", url: "https://x.com/enrichtest" },
+ ],
+ address: {
+ city: "South San Francisco",
+ state_code: "CA",
+ country: "United States",
+ country_code: "US",
+ },
+ industries: {
+ eic: [{ industry: "Finance", subindustry: "Payments & Money Movement" }],
+ },
+ links: { pricing: "https://enrich-test.example/pricing" },
+ },
+};
+
+const TEST_DOMAINS = [
+ "enrich-test.example",
+ "enrich-missing.example",
+ "enrich-broken.example",
+ "enrich-email.example",
+ "enrich-research.example",
+];
+
+let service: InstanceType<typeof EnrichmentService>;
+let userId: string;
+
+beforeAll(async () => {
+ const client = new ContextDevClient(config);
+ service = new EnrichmentService(db, client, new FastQueue());
+
+ const user = await db.user.upsert({
+ where: { email: "enrichment-test@localhost" },
+ create: {
+ id: "enrichment-test-user",
+ email: "enrichment-test@localhost",
+ name: "Enrichment Test",
+ emailVerified: true,
+ updatedAt: new Date(),
+ },
+ update: {},
+ select: { id: true },
+ });
+ userId = user.id;
+
+ stubResponses["/v1/utility/prefetch"] = () => Response.json({ status: "ok" });
+ stubResponses["/v1/brand/retrieve:enrich-test.example"] = () =>
+ Response.json(STRIPE_BRAND);
+ stubResponses["/v1/brand/retrieve:enrich-missing.example"] = () =>
+ Response.json({ error_code: "NOT_FOUND" }, { status: 400 });
+ stubResponses["/v1/brand/retrieve:enrich-broken.example"] = () =>
+ Response.json({ error_code: "RATE_LIMITED" }, { status: 429 });
+ stubResponses["/v1/brand/retrieve:[email protected]"] = () =>
+ Response.json({
+ status: "ok",
+ code: 200,
+ brand: { domain: "enrich-email.example", title: "Enrich Email Co" },
+ });
+ stubResponses["/v1/brand/retrieve:[email protected]"] = () =>
+ Response.json({ error_code: "FREE_EMAIL_DETECTED" }, { status: 422 });
+ stubResponses["/v1/web/extract"] = () =>
+ Response.json({
+ data: {
+ positioning: "Sells payments infrastructure to developers.",
+ pricingModel: "Usage-based, per transaction.",
+ notableCustomers: ["Amazon", "Shopify"],
+ recentNews: ["Raised a Series H."],
+ },
+ urls_analyzed: ["https://enrich-research.example"],
+ });
+});
+
+afterAll(async () => {
+ await db.activity.deleteMany({ where: { createdById: userId } });
+ await db.company.deleteMany({ where: { domain: { in: TEST_DOMAINS } } });
+ await db.user.deleteMany({ where: { id: userId } });
+ await db.$disconnect();
+ server.stop(true);
+});
+
+async function makeCompany(
+ domain: string | null,
+ overrides: Record<string, unknown> = {},
+) {
+ return db.company.create({
+ data: {
+ name: (overrides.name as string | undefined) ?? "Placeholder",
+ domain,
+ ...overrides,
+ },
+ select: { id: true },
+ });
+}
+
+describe("enrichment against a stub Context.dev", () => {
+ it("fills a company in and keeps the raw payload", async () => {
+ const { id } = await makeCompany("enrich-test.example", {
+ name: "enrich-test.example",
+ // A value a human typed. The agent must not touch it.
+ city: "London",
+ });
+
+ expect(service.enqueueCompany(id)).toBe(true);
+ await service.drain();
+
+ const company = await db.company.findUniqueOrThrow({
+ where: { id },
+ select: {
+ name: true,
+ description: true,
+ logoUrl: true,
+ logoDarkUrl: true,
+ iconUrl: true,
+ brandColor: true,
+ industry: true,
+ subIndustry: true,
+ city: true,
+ country: true,
+ phone: true,
+ linkedinUrl: true,
+ twitterUrl: true,
+ pricingUrl: true,
+ enrichmentStatus: true,
+ enrichedAt: true,
+ enrichmentError: true,
+ enrichment: { select: { raw: true, source: true } },
+ },
+ });
+
+ expect(company.enrichmentStatus).toBe("COMPLETE");
+ expect(company.enrichmentError).toBeNull();
+ expect(company.enrichedAt).not.toBeNull();
+
+ // The name was the domain, so the lookup is allowed to replace it.
+ expect(company.name).toBe("Enrich Test");
+ expect(company.description).toBe(
+ "Payments infrastructure for the internet.",
+ );
+ // Logos by mode and type, not logos[0].
+ expect(company.logoUrl).toBe("https://cdn/light.svg");
+ expect(company.logoDarkUrl).toBe("https://cdn/dark.svg");
+ expect(company.iconUrl).toBe("https://cdn/icon.svg");
+ expect(company.brandColor).toBe("#635bff");
+ expect(company.industry).toBe("Finance");
+ expect(company.subIndustry).toBe("Payments & Money Movement");
+ expect(company.country).toBe("United States");
+ expect(company.phone).toBe("+1 888 555 0100");
+ expect(company.linkedinUrl).toBe(
+ "https://linkedin.com/company/enrich-test",
+ );
+ expect(company.twitterUrl).toBe("https://x.com/enrichtest");
+ expect(company.pricingUrl).toBe("https://enrich-test.example/pricing");
+
+ // The one field a human had already set.
+ expect(company.city).toBe("London");
+
+ // The whole payload is kept so re-deriving a field costs no credits.
+ expect(company.enrichment?.source).toBe("context.dev");
+ expect(
+ (company.enrichment?.raw as { brand?: { title?: string } })?.brand?.title,
+ ).toBe("Enrich Test");
+ });
+
+ it("warms the cache before looking a domain up", () => {
+ // Prefetch is free and turns a cold 7s lookup into a warm one.
+ const paths = requests.map((request) => request.path);
+ expect(paths).toContain("/v1/utility/prefetch");
+ expect(paths.indexOf("/v1/utility/prefetch")).toBeLessThan(
+ paths.indexOf("/v1/brand/retrieve"),
+ );
+ });
+
+ it("records an unknown domain as SKIPPED, not FAILED", async () => {
+ const { id } = await makeCompany("enrich-missing.example");
+
+ service.enqueueCompany(id);
+ await service.drain();
+
+ const company = await db.company.findUniqueOrThrow({
+ where: { id },
+ select: { enrichmentStatus: true, enrichmentError: true },
+ });
+
+ // Nothing to find is a settled answer, and it is not billed — so it is
+ // not an error message to put in front of a rep.
+ expect(company.enrichmentStatus).toBe("SKIPPED");
+ expect(company.enrichmentError).toBeNull();
+ });
+
+ it("records a rate limit as FAILED, with the reason", async () => {
+ const { id } = await makeCompany("enrich-broken.example");
+
+ service.enqueueCompany(id);
+ await service.drain();
+
+ const company = await db.company.findUniqueOrThrow({
+ where: { id },
+ select: { enrichmentStatus: true, enrichmentError: true },
+ });
+
+ expect(company.enrichmentStatus).toBe("FAILED");
+ expect(company.enrichmentError).toContain("429");
+ });
+
+ it("skips a company with no domain without calling out at all", async () => {
+ const { id } = await makeCompany(null, { name: "No Domain Co" });
+ const before = requests.length;
+
+ service.enqueueCompany(id);
+ await service.drain();
+
+ const company = await db.company.findUniqueOrThrow({
+ where: { id },
+ select: { enrichmentStatus: true },
+ });
+
+ expect(company.enrichmentStatus).toBe("SKIPPED");
+ expect(requests.length).toBe(before);
+
+ await db.company.delete({ where: { id } });
+ });
+
+ it("refuses to queue the same company twice", async () => {
+ const { id } = await makeCompany("enrich-test.example-dupe" as string);
+
+ expect(service.enqueueCompany(id)).toBe(true);
+ // A rep leaning on Re-enrich should not spend ten credits on one lookup.
+ expect(service.enqueueCompany(id)).toBe(false);
+
+ await service.drain();
+ await db.company.delete({ where: { id } });
+ });
+
+ describe("companyForEmail", () => {
+ it("creates the company behind a work address", async () => {
+ const companyId = await service.companyForEmail(
+ );
+ expect(companyId).not.toBeNull();
+
+ const company = await db.company.findUniqueOrThrow({
+ where: { domain: "enrich-email.example" },
+ select: { name: true, website: true },
+ });
+ expect(company.name).toBe("Enrich Email Co");
+ expect(company.website).toBe("https://enrich-email.example");
+
+ await service.drain();
+ });
+
+ it("returns the company we already have rather than looking again", async () => {
+ const before = requests.length;
+ const companyId = await service.companyForEmail(
+ );
+
+ expect(companyId).not.toBeNull();
+ // Already known: no second lookup, no second ten credits.
+ expect(requests.length).toBe(before);
+ });
+
+ it("ignores a personal address", async () => {
+ expect(await service.companyForEmail("[email protected]")).toBeNull();
+ // Rejected on the free-domain list before any call is made.
+ expect(
+ requests.some((request) =>
+ JSON.stringify(request.body).includes("gmail.com"),
+ ),
+ ).toBe(false);
+ });
+ });
+
+ it("posts a research brief to the company timeline", async () => {
+ const { id } = await makeCompany("enrich-research.example", {
+ name: "Research Co",
+ website: "https://enrich-research.example",
+ });
+
+ const result = await service.researchCompany(id, userId);
+ expect(result.ok).toBe(true);
+
+ const activity = await db.activity.findFirstOrThrow({
+ where: { companyId: id, type: "ENRICHMENT" },
+ select: { subject: true, body: true, meta: true, occurredAt: true },
+ });
+
+ expect(activity.subject).toBe("Research brief — Research Co");
+ // Rendered as prose, because a timeline entry is read rather than parsed.
+ expect(activity.body).toContain(
+ "Sells payments infrastructure to developers.",
+ );
+ expect(activity.body).toContain("Pricing: Usage-based, per transaction.");
+ expect(activity.body).toContain("Customers: Amazon, Shopify");
+ expect(activity.body).toContain("• Raised a Series H.");
+ expect(activity.occurredAt).not.toBeNull();
+ expect((activity.meta as { creditCost?: number })?.creditCost).toBe(10);
+ });
+
+ it("reports a company with no website rather than guessing a URL", async () => {
+ const { id } = await makeCompany(null, { name: "Websiteless" });
+
+ const result = await service.researchCompany(id, userId);
+
+ expect(result.ok).toBe(false);
+ expect(result.ok === false && result.reason).toContain("no website");
+
+ await db.company.delete({ where: { id } });
+ });
+});
diff --git a/apps/api/test/enrichment.spec.ts b/apps/api/test/enrichment.spec.ts
new file mode 100644
index 00000000..7a2f592b
--- /dev/null
+++ b/apps/api/test/enrichment.spec.ts
@@ -0,0 +1,283 @@
+import { describe, expect, it } from "bun:test";
+import { domainFromEmail, normalizeDomain } from "../src/companies/domain";
+import {
+ brandToUpdate,
+ type CompanySnapshot,
+} from "../src/enrichment/brand-mapping";
+import type { Brand } from "../src/enrichment/context-dev.client";
+import { EnrichmentQueue } from "../src/enrichment/enrichment.queue";
+
+/** A company with nothing filled in — every gap open. */
+function emptyCompany(
+ overrides: Partial<CompanySnapshot> = {},
+): CompanySnapshot {
+ return {
+ name: "Stripe",
+ nameIsPlaceholder: false,
+ description: null,
+ logoUrl: null,
+ logoDarkUrl: null,
+ iconUrl: null,
+ brandColor: null,
+ industry: null,
+ subIndustry: null,
+ city: null,
+ stateCode: null,
+ country: null,
+ countryCode: null,
+ phone: null,
+ email: null,
+ linkedinUrl: null,
+ twitterUrl: null,
+ githubUrl: null,
+ pricingUrl: null,
+ careersUrl: null,
+ ...overrides,
+ };
+}
+
+describe("normalizeDomain", () => {
+ it("reduces anything a human might type to the bare host", () => {
+ for (const input of [
+ "stripe.com",
+ "STRIPE.com",
+ " stripe.com ",
+ "www.stripe.com",
+ "https://stripe.com",
+ "https://www.Stripe.com/pricing?ref=x",
+ "http://stripe.com/",
+ ]) {
+ expect(normalizeDomain(input)).toBe("stripe.com");
+ }
+ });
+
+ it("rejects things that are not hostnames", () => {
+ for (const input of [
+ "",
+ " ",
+ "localhost",
+ "my company",
+ "not a domain",
+ ]) {
+ expect(normalizeDomain(input)).toBeNull();
+ }
+ expect(normalizeDomain(null)).toBeNull();
+ expect(normalizeDomain(undefined)).toBeNull();
+ });
+});
+
+describe("domainFromEmail", () => {
+ it("takes the domain off a work address", () => {
+ expect(domainFromEmail("[email protected]")).toBe("stripe.com");
+ expect(domainFromEmail(" [email protected] ")).toBe("stripe.com");
+ });
+
+ it("ignores free and malformed addresses", () => {
+ // Creating a "Gmail" company from a personal address is the classic
+ // CRM junk row.
+ for (const email of [
+ "@stripe.com",
+ "not-an-email",
+ "",
+ ]) {
+ expect(domainFromEmail(email)).toBeNull();
+ }
+ });
+});
+
+describe("brandToUpdate", () => {
+ const brand: Brand = {
+ title: "Stripe",
+ description: "Payments infrastructure for the internet.",
+ phone: "+1 888 963 8955",
+ email: "[email protected]",
+ colors: [{ hex: "#635bff", name: "Meteor Shower" }],
+ logos: [
+ { url: "https://cdn/dark-logo.svg", mode: "dark", type: "logo" },
+ { url: "https://cdn/light-logo.svg", mode: "light", type: "logo" },
+ {
+ url: "https://cdn/icon.svg",
+ mode: "has_opaque_background",
+ type: "icon",
+ },
+ ],
+ socials: [
+ { type: "x", url: "https://x.com/stripe" },
+ { type: "linkedin", url: "https://linkedin.com/company/stripe" },
+ { type: "github", url: "https://github.com/stripe" },
+ ],
+ address: {
+ city: "South San Francisco",
+ state_code: "CA",
+ country: "United States",
+ country_code: "US",
+ },
+ industries: {
+ eic: [{ industry: "Finance", subindustry: "Payments & Money Movement" }],
+ },
+ links: {
+ pricing: "https://stripe.com/pricing",
+ careers: "https://stripe.com/jobs",
+ },
+ };
+
+ it("picks logos by mode and type rather than taking the first", () => {
+ const update = brandToUpdate(brand, emptyCompany());
+
+ expect(update.logoUrl).toBe("https://cdn/light-logo.svg");
+ expect(update.logoDarkUrl).toBe("https://cdn/dark-logo.svg");
+ expect(update.iconUrl).toBe("https://cdn/icon.svg");
+ });
+
+ it("maps the rest of the brand onto company fields", () => {
+ const update = brandToUpdate(brand, emptyCompany());
+
+ expect(update).toMatchObject({
+ description: "Payments infrastructure for the internet.",
+ brandColor: "#635bff",
+ industry: "Finance",
+ subIndustry: "Payments & Money Movement",
+ city: "South San Francisco",
+ stateCode: "CA",
+ country: "United States",
+ countryCode: "US",
+ phone: "+1 888 963 8955",
+ email: "[email protected]",
+ linkedinUrl: "https://linkedin.com/company/stripe",
+ twitterUrl: "https://x.com/stripe",
+ githubUrl: "https://github.com/stripe",
+ pricingUrl: "https://stripe.com/pricing",
+ careersUrl: "https://stripe.com/jobs",
+ });
+ });
+
+ it("never overwrites a value a human already set", () => {
+ const update = brandToUpdate(
+ brand,
+ emptyCompany({
+ description: "Our biggest account — handle with care.",
+ city: "London",
+ phone: "+44 20 7946 0000",
+ }),
+ );
+
+ expect(update.description).toBeUndefined();
+ expect(update.city).toBeUndefined();
+ expect(update.phone).toBeUndefined();
+ // The gaps are still filled.
+ expect(update.country).toBe("United States");
+ });
+
+ it("leaves the name alone unless it is the domain placeholder", () => {
+ expect(
+ brandToUpdate(brand, emptyCompany({ name: "Stripe Inc" })).name,
+ ).toBeUndefined();
+
+ expect(
+ brandToUpdate(
+ brand,
+ emptyCompany({ name: "stripe.com", nameIsPlaceholder: true }),
+ ).name,
+ ).toBe("Stripe");
+ });
+
+ it("writes nothing when the lookup found nothing", () => {
+ // Every field on a brand is nullable, so the all-null case is real.
+ expect(brandToUpdate({}, emptyCompany())).toEqual({});
+ });
+
+ it("falls back to the slogan when there is no description", () => {
+ const update = brandToUpdate(
+ { slogan: "Payments, simplified." },
+ emptyCompany(),
+ );
+ expect(update.description).toBe("Payments, simplified.");
+ });
+});
+
+/** The real queue, with the five-second backoff wound down. */
+class FastQueue extends EnrichmentQueue {
+ protected override get retryDelayMs(): number {
+ return 5;
+ }
+}
+
+describe("EnrichmentQueue", () => {
+ it("runs at most two jobs at once", async () => {
+ const queue = new EnrichmentQueue();
+ let running = 0;
+ let peak = 0;
+
+ const job = async () => {
+ running += 1;
+ peak = Math.max(peak, running);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ running -= 1;
+ };
+
+ for (let index = 0; index < 6; index++) {
+ queue.enqueue(`job-${index}`, job);
+ }
+ await queue.drain();
+
+ expect(peak).toBe(2);
+ });
+
+ it("refuses a key that is already queued", () => {
+ const queue = new EnrichmentQueue();
+ const job = () => new Promise<void>((resolve) => setTimeout(resolve, 50));
+
+ expect(queue.enqueue("company:1", job)).toBe(true);
+ // A rep leaning on "Re-enrich" should not spend ten credits on one lookup.
+ expect(queue.enqueue("company:1", job)).toBe(false);
+ expect(queue.enqueue("company:2", job)).toBe(true);
+ });
+
+ it("retries a job that throws, once", async () => {
+ const queue = new FastQueue();
+ let attempts = 0;
+
+ queue.enqueue("flaky", async () => {
+ attempts += 1;
+ if (attempts === 1) throw new Error("cold cache timeout");
+ });
+ await queue.drain();
+
+ expect(attempts).toBe(2);
+ });
+
+ it("gives up after the retry rather than looping", async () => {
+ const queue = new FastQueue();
+ let attempts = 0;
+
+ queue.enqueue("broken", async () => {
+ attempts += 1;
+ throw new Error("still broken");
+ });
+ await queue.drain();
+
+ expect(attempts).toBe(2);
+ });
+
+ it("drops queued work on shutdown instead of racing the database", async () => {
+ const queue = new EnrichmentQueue();
+ let ran = 0;
+ const slow = async () => {
+ ran += 1;
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ };
+
+ for (let index = 0; index < 5; index++) {
+ queue.enqueue(`job-${index}`, slow);
+ }
+ queue.onApplicationShutdown();
+ await queue.drain();
+
+ // The two already in flight finish; the rest are dropped and stay PENDING.
+ expect(ran).toBe(2);
+ expect(queue.enqueue("after-shutdown", slow)).toBe(false);
+ });
+});
diff --git a/apps/api/test/logging.spec.ts b/apps/api/test/logging.spec.ts
new file mode 100644
index 00000000..bf8be43b
--- /dev/null
+++ b/apps/api/test/logging.spec.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it, spyOn } from "bun:test";
+import type { NextFunction, Request, Response } from "express";
+import { ContextLogger } from "../src/logging/context-logger";
+import {
+ getRequestContext,
+ runInRequestContext,
+ setRequestUserId,
+} from "../src/logging/request-context";
+import { RequestLoggerMiddleware } from "../src/logging/request-logger.middleware";
+
+/** The logger reads `NODE_ENV` live so format can be exercised both ways. */
+function withNodeEnv(value: string, fn: () => void): void {
+ const previous = process.env.NODE_ENV;
+ process.env.NODE_ENV = value;
+
+ try {
+ fn();
+ } finally {
+ process.env.NODE_ENV = previous;
+ }
+}
+
+function captureStdout(fn: () => void): string {
+ const chunks: string[] = [];
+ const spy = spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ chunks.push(String(chunk));
+ return true;
+ });
+
+ try {
+ fn();
+ } finally {
+ spy.mockRestore();
+ }
+
+ return chunks.join("");
+}
+
+const context = { requestId: "abcdef1234567890", method: "GET", path: "/x" };
+
+describe("ContextLogger", () => {
+ it("hoists structured fields and the request context into JSON", () => {
+ withNodeEnv("production", () => {
+ const logger = new ContextLogger();
+
+ const output = captureStdout(() => {
+ runInRequestContext({ ...context }, () => {
+ setRequestUserId("user-1");
+ logger.log({ message: "Hello", statusCode: 200 }, "Ctx");
+ });
+ });
+
+ expect(JSON.parse(output)).toMatchObject({
+ level: "log",
+ message: "Hello",
+ statusCode: 200,
+ context: "Ctx",
+ requestId: "abcdef1234567890",
+ userId: "user-1",
+ });
+ });
+ });
+
+ it("does not let a log payload overwrite the fields Nest owns", () => {
+ withNodeEnv("production", () => {
+ const logger = new ContextLogger();
+
+ const output = captureStdout(() => {
+ logger.log({ message: "Hello", level: "error", pid: -1 }, "Ctx");
+ });
+ const record = JSON.parse(output);
+
+ expect(record.level).toBe("log");
+ expect(record.pid).toBe(process.pid);
+ });
+ });
+
+ it("omits correlation fields when there is no request", () => {
+ withNodeEnv("production", () => {
+ const logger = new ContextLogger();
+ const output = captureStdout(() => logger.log("Standalone", "Ctx"));
+
+ expect(JSON.parse(output).requestId).toBeUndefined();
+ });
+ });
+
+ it("renders structured messages readably in development", () => {
+ withNodeEnv("development", () => {
+ const logger = new ContextLogger();
+
+ const output = captureStdout(() => {
+ runInRequestContext({ ...context }, () => {
+ logger.log({ message: "Hello", statusCode: 200 }, "Ctx");
+ });
+ });
+
+ expect(output).toContain("Hello");
+ expect(output).toContain("statusCode");
+ // Nest's default rendering for a plain object, which this replaces.
+ expect(output).not.toContain("Object(2)");
+ // The request id rides inside the context bracket.
+ expect(output).toContain("Ctx abcdef12");
+ });
+ });
+
+ it("drops verbose output in production", () => {
+ withNodeEnv("production", () => {
+ const logger = new ContextLogger();
+
+ expect(captureStdout(() => logger.verbose("Quiet", "Ctx"))).toBe("");
+ });
+ });
+});
+
+describe("request context", () => {
+ it("is isolated per run and unset outside one", () => {
+ expect(getRequestContext()).toBeUndefined();
+
+ runInRequestContext({ ...context, requestId: "a" }, () => {
+ expect(getRequestContext()?.requestId).toBe("a");
+ });
+
+ expect(getRequestContext()).toBeUndefined();
+ });
+});
+
+describe("RequestLoggerMiddleware", () => {
+ function run(headers: Record<string, string>): {
+ requestId: string;
+ seen: string | undefined;
+ } {
+ const middleware = new RequestLoggerMiddleware();
+ let requestId = "";
+ let seen: string | undefined;
+
+ const request = {
+ method: "GET",
+ originalUrl: "/things",
+ path: "/things",
+ ip: "127.0.0.1",
+ get: (name: string) => headers[name.toLowerCase()],
+ } as unknown as Request;
+
+ const response = {
+ statusCode: 200,
+ setHeader: (_name: string, value: string) => {
+ requestId = value;
+ },
+ on: () => response,
+ } as unknown as Response;
+
+ middleware.use(request, response, (() => {
+ seen = getRequestContext()?.requestId;
+ }) as NextFunction);
+
+ return { requestId, seen };
+ }
+
+ it("stamps a request id and exposes it to the handler", () => {
+ const { requestId, seen } = run({});
+
+ expect(requestId).toMatch(/^[0-9a-f-]{36}$/);
+ expect(seen).toBe(requestId);
+ });
+
+ it("reuses a caller-supplied id so a trace spans hops", () => {
+ expect(run({ "x-request-id": "trace-abc.1" }).requestId).toBe(
+ "trace-abc.1",
+ );
+ });
+
+ it("ignores a malformed id rather than logging attacker-controlled text", () => {
+ const { requestId } = run({ "x-request-id": "bad id\nlevel=error" });
+
+ expect(requestId).not.toContain("\n");
+ expect(requestId).toMatch(/^[0-9a-f-]{36}$/);
+ });
+});
diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json
new file mode 100644
index 00000000..43b0d898
--- /dev/null
+++ b/apps/api/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "@crm/typescript-config/nestjs.json",
+ "compilerOptions": {
+ "types": ["bun"],
+ "experimentalDecorators": true,
+ "emitDecoratorMetadata": true
+ },
+ "include": ["src/**/*.ts", "test/**/*.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/apps/api/turbo.json b/apps/api/turbo.json
new file mode 100644
index 00000000..fcd8d77b
--- /dev/null
+++ b/apps/api/turbo.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://turborepo.dev/schema.json",
+ "extends": ["//"],
+ "tasks": {
+ "build": {
+ "dependsOn": ["$TURBO_EXTENDS$", "trpc:generate"],
+ "outputs": ["dist/**", "src/generated/**"]
+ },
+ "check-types": {
+ "dependsOn": ["$TURBO_EXTENDS$", "trpc:generate"]
+ },
+ "trpc:generate": {
+ "dependsOn": ["^build"],
+ "inputs": ["src/**/*.ts"],
+ "outputs": ["src/generated/**"]
+ },
+ "dev": {
+ "cache": false,
+ "persistent": true,
+ "passThroughEnv": [
+ "AUTH_COOKIE_DOMAIN",
+ "AUTH_TRUSTED_ORIGINS",
+ "BETTER_AUTH_SECRET",
+ "BETTER_AUTH_URL",
+ "CACHE_TTL_MS",
+ "DATABASE_URL",
+ "GOOGLE_CLIENT_ID",
+ "GOOGLE_CLIENT_SECRET",
+ "PORT",
+ "REDIS_URL"
+ ]
+ },
+ "test": {
+ "passThroughEnv": [
+ "AUTH_COOKIE_DOMAIN",
+ "AUTH_TRUSTED_ORIGINS",
+ "BETTER_AUTH_SECRET",
+ "BETTER_AUTH_URL",
+ "CACHE_TTL_MS",
+ "DATABASE_URL",
+ "GOOGLE_CLIENT_ID",
+ "GOOGLE_CLIENT_SECRET",
+ "PORT",
+ "REDIS_URL"
+ ]
+ }
+ }
+}
diff --git a/apps/web/.gitignore b/apps/app/.gitignore
similarity index 80%
rename from apps/web/.gitignore
rename to apps/app/.gitignore
index ce1f6254..5ef6a520 100644
--- a/apps/web/.gitignore
+++ b/apps/app/.gitignore
@@ -3,8 +3,12 @@
# dependencies
/node_modules
/.pnp
-.pnp.js
-.yarn/install-state.gz
+.pnp.*
+.yarn/*
+!.yarn/patches
+!.yarn/plugins
+!.yarn/releases
+!.yarn/versions
# testing
/coverage
@@ -24,6 +28,7 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
diff --git a/apps/app/AGENTS.md b/apps/app/AGENTS.md
new file mode 100644
index 00000000..8bd0e390
--- /dev/null
+++ b/apps/app/AGENTS.md
@@ -0,0 +1,5 @@
+<!-- BEGIN:nextjs-agent-rules -->
+# This is NOT the Next.js you know
+
+This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
+<!-- END:nextjs-agent-rules -->
diff --git a/apps/app/CLAUDE.md b/apps/app/CLAUDE.md
new file mode 100644
index 00000000..43c994c2
--- /dev/null
+++ b/apps/app/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/apps/web/README.md b/apps/app/README.md
similarity index 93%
rename from apps/web/README.md
rename to apps/app/README.md
index a98bfa81..e215bc4c 100644
--- a/apps/web/README.md
+++ b/apps/app/README.md
@@ -1,4 +1,4 @@
-This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/create-next-app).
+This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
@@ -18,7 +18,7 @@ Open [http://localhost:3000](http://localhost:3000) with your browser to see the
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
-This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load Inter, a custom Google Font.
+This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
diff --git a/apps/app/app/(app)/companies/[companyId]/page.tsx b/apps/app/app/(app)/companies/[companyId]/page.tsx
new file mode 100644
index 00000000..885968bb
--- /dev/null
+++ b/apps/app/app/(app)/companies/[companyId]/page.tsx
@@ -0,0 +1,18 @@
+import { redirect } from "next/navigation";
+import { recordHref } from "@/lib/record-href";
+
+/**
+ * The company page that used to live here.
+ *
+ * A company is a sheet over the companies table now, but the old URL is in
+ * people's history and in links they have already sent, so it lands on the
+ * table with that company open rather than on a 404.
+ */
+export default async function CompanyRedirect({
+ params,
+}: {
+ params: Promise<{ companyId: string }>;
+}) {
+ const { companyId } = await params;
+ redirect(recordHref("/companies", "company", companyId));
+}
diff --git a/apps/app/app/(app)/companies/companies-search-params.ts b/apps/app/app/(app)/companies/companies-search-params.ts
new file mode 100644
index 00000000..fc432ee6
--- /dev/null
+++ b/apps/app/app/(app)/companies/companies-search-params.ts
@@ -0,0 +1,10 @@
+import { createListSearchParams } from "@/components/data-table/list-search-params";
+
+/**
+ * The companies list URL. Shared by the page's server-side prefetch and the
+ * client table, so the two cannot ask for different things.
+ */
+export const companiesSearchParams = createListSearchParams({
+ defaultSort: "name",
+ facetIds: ["owner", "industry", "enrichment"] as const,
+});
diff --git a/apps/app/app/(app)/companies/companies-table.tsx b/apps/app/app/(app)/companies/companies-table.tsx
new file mode 100644
index 00000000..e447b063
--- /dev/null
+++ b/apps/app/app/(app)/companies/companies-table.tsx
@@ -0,0 +1,183 @@
+"use client";
+
+import {
+ DataTable,
+ type DataTableColumn,
+ type DataTableFacet,
+} from "@crm/ui/components/data-table";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { EntityLogo } from "@crm/ui/components/entity-logo";
+import { relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useQuery } from "@tanstack/react-query";
+import {
+ ENRICHMENT_FACET_OPTIONS,
+ EnrichmentIndicator,
+} from "@/components/crm/enrichment-status";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { useTableQuery } from "@/components/data-table/use-table-query";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { companiesSearchParams } from "./companies-search-params";
+
+type CompanyRow = RouterOutputs["companies"]["list"]["rows"][number];
+
+const COLUMNS: DataTableColumn<CompanyRow>[] = [
+ {
+ id: "name",
+ header: "Company",
+ sortable: true,
+ hideable: false,
+ width: "w-[26%]",
+ cell: (row) => (
+ <span className="flex min-w-0 items-center gap-2.5">
+ <EntityLogo
+ src={row.iconUrl ?? row.logoUrl}
+ name={row.name}
+ size="sm"
+ />
+ <span className="truncate font-medium">{row.name}</span>
+ </span>
+ ),
+ },
+ {
+ id: "domain",
+ header: "Domain",
+ sortable: true,
+ width: "w-[16%]",
+ hideBelow: "md",
+ cell: (row) =>
+ row.domain ? (
+ <span className="truncate text-muted-foreground">{row.domain}</span>
+ ) : (
+ <EmptyCellValue />
+ ),
+ },
+ {
+ id: "industry",
+ header: "Industry",
+ sortable: true,
+ width: "w-[16%]",
+ hideBelow: "lg",
+ cell: (row) =>
+ row.industry ? (
+ <span className="truncate">{row.industry}</span>
+ ) : (
+ <EmptyCellValue />
+ ),
+ },
+ {
+ id: "owner",
+ header: "Owner",
+ width: "w-[16%]",
+ hideBelow: "md",
+ cell: (row) => <OwnerCell owner={row.owner} />,
+ },
+ {
+ id: "contacts",
+ header: "Contacts",
+ sortable: true,
+ align: "right",
+ width: "w-[9%]",
+ hideBelow: "lg",
+ cell: (row) => <span className="tabular-nums">{row.contactCount}</span>,
+ },
+ {
+ id: "deals",
+ header: "Open deals",
+ sortable: true,
+ align: "right",
+ width: "w-[9%]",
+ cell: (row) => <span className="tabular-nums">{row.openDealCount}</span>,
+ },
+ {
+ // Not sortable: "most recent activity" is an aggregate over a relation,
+ // which Prisma cannot order by, and sorting the page in the browser would
+ // only reorder the 25 rows already on screen.
+ id: "lastActivity",
+ header: "Last activity",
+ align: "right",
+ width: "w-[12%]",
+ hideBelow: "sm",
+ cell: (row) => (
+ <span className="text-muted-foreground">
+ {relativeTimeFromIso(row.lastActivityAt)}
+ </span>
+ ),
+ },
+ {
+ // Off by default: while the agent is working through a backlog every row
+ // says the same thing. The facet is the useful way in; this column is for
+ // when you are looking at enrichment specifically.
+ id: "enrichment",
+ header: "Enrichment",
+ label: "Enrichment status",
+ defaultHidden: true,
+ width: "w-[14%]",
+ cell: (row) => <EnrichmentIndicator status={row.enrichmentStatus} />,
+ },
+];
+
+export function CompaniesTable() {
+ const openRecord = useOpenRecord();
+ const trpc = useTRPC();
+ const { query, input } = useTableQuery(companiesSearchParams);
+
+ const companies = useQuery({
+ ...trpc.companies.list.queryOptions(input),
+ // Keeps the previous page on screen while the next one loads, so paging
+ // and typing never blank the table.
+ placeholderData: (previous) => previous,
+ });
+ const users = useQuery(trpc.users.list.queryOptions());
+
+ const facetCounts = companies.data?.facetCounts;
+
+ const facets: DataTableFacet[] = [
+ {
+ id: "owner",
+ label: "Owner",
+ options: [
+ { value: "unassigned", label: "Unassigned" },
+ ...(users.data ?? []).map((user) => ({
+ value: user.id,
+ label: user.name,
+ })),
+ // An owner with nothing assigned is a dropdown entry that can only
+ // ever produce an empty table.
+ ].filter((option) => (facetCounts?.owner?.[option.value] ?? 0) > 0),
+ },
+ {
+ id: "industry",
+ label: "Industry",
+ // The industries that exist, not a fixed list: they come from the
+ // agent, so nobody here gets to decide what the set is.
+ options: Object.keys(facetCounts?.industry ?? {})
+ .sort()
+ .map((value) => ({ value, label: value })),
+ },
+ {
+ id: "enrichment",
+ label: "Enrichment",
+ options: ENRICHMENT_FACET_OPTIONS.filter(
+ (option) => (facetCounts?.enrichment?.[option.value] ?? 0) > 0,
+ ),
+ },
+ ];
+
+ return (
+ <DataTable
+ query={query}
+ columns={COLUMNS}
+ rows={companies.data?.rows ?? []}
+ total={companies.data?.total ?? 0}
+ facetCounts={facetCounts}
+ facets={facets}
+ getRowId={(row) => row.id}
+ loading={companies.isFetching}
+ searchPlaceholder="Search companies by name or domain…"
+ onRowClick={(row) => openRecord({ kind: "company", id: row.id })}
+ empty="No companies match this view."
+ />
+ );
+}
diff --git a/apps/app/app/(app)/companies/create-company-sheet.tsx b/apps/app/app/(app)/companies/create-company-sheet.tsx
new file mode 100644
index 00000000..13037116
--- /dev/null
+++ b/apps/app/app/(app)/companies/create-company-sheet.tsx
@@ -0,0 +1,179 @@
+"use client";
+
+import Add from "@carbon/icons-react/es/Add";
+import { Button } from "@crm/ui/components/button";
+import {
+ Field,
+ FieldDescription,
+ FieldGroup,
+ FieldLabel,
+} from "@crm/ui/components/field";
+import { Icon } from "@crm/ui/components/icon";
+import { Input } from "@crm/ui/components/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@crm/ui/components/select";
+import {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ SheetTrigger,
+} from "@crm/ui/components/sheet";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { parseAsBoolean, useQueryState } from "nuqs";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { useTRPC } from "@/lib/trpc/client";
+
+const UNASSIGNED = "unassigned";
+
+/**
+ * Name, domain, owner — nothing else.
+ *
+ * Everything a form could ask for next (industry, address, logo, socials) is
+ * something the agent can find from the domain, and a form that asks a rep to
+ * type it is a form they will skip.
+ */
+export function CreateCompanySheet() {
+ const openRecord = useOpenRecord();
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ // Open state lives in the URL, like every other view state here: "add a
+ // company" is then a link you can send someone, and Back closes the sheet
+ // instead of leaving the page. Shallow, so it costs no server round trip.
+ const [open, setOpen] = useQueryState(
+ "new",
+ parseAsBoolean.withDefault(false),
+ );
+ const [name, setName] = useState("");
+ const [domain, setDomain] = useState("");
+ const [ownerId, setOwnerId] = useState(UNASSIGNED);
+
+ const nameId = useId();
+ const domainId = useId();
+
+ const users = useQuery(trpc.users.list.queryOptions());
+
+ const create = useMutation(
+ trpc.companies.create.mutationOptions({
+ onSuccess: async (company) => {
+ await queryClient.invalidateQueries({
+ queryKey: trpc.companies.list.queryKey(),
+ });
+ toast.success(`${company.name} added.`);
+ // `null` rather than `false` so the closed state leaves a clean URL.
+ await setOpen(null);
+ setName("");
+ setDomain("");
+ setOwnerId(UNASSIGNED);
+ openRecord({ kind: "company", id: company.id });
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ return (
+ <Sheet open={open} onOpenChange={(next) => setOpen(next || null)}>
+ <SheetTrigger asChild>
+ <Button size="sm">
+ <Icon icon={Add} data-icon="inline-start" />
+ New company
+ </Button>
+ </SheetTrigger>
+ <SheetContent side="right">
+ <SheetHeader>
+ <SheetTitle>New company</SheetTitle>
+ <SheetDescription>
+ Give it a name and a domain. The agent fills in the logo,
+ description, industry, address and socials.
+ </SheetDescription>
+ </SheetHeader>
+
+ <form
+ id="create-company"
+ className="flex-1 overflow-y-auto px-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ create.mutate({
+ name,
+ domain: domain || undefined,
+ ownerId: ownerId === UNASSIGNED ? null : ownerId,
+ });
+ }}
+ >
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor={nameId}>Name</FieldLabel>
+ <Input
+ id={nameId}
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ placeholder="Stripe"
+ autoComplete="off"
+ required
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor={domainId}>Domain</FieldLabel>
+ <Input
+ id={domainId}
+ value={domain}
+ onChange={(event) => setDomain(event.target.value)}
+ placeholder="stripe.com"
+ autoComplete="off"
+ inputMode="url"
+ />
+ <FieldDescription>
+ A full URL is fine — it is reduced to the bare host, which has
+ to be unique.
+ </FieldDescription>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="create-company-owner">Owner</FieldLabel>
+ <Select value={ownerId} onValueChange={setOwnerId}>
+ <SelectTrigger id="create-company-owner">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={UNASSIGNED}>Unassigned</SelectItem>
+ {(users.data ?? []).map((user) => (
+ <SelectItem key={user.id} value={user.id}>
+ {user.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ </FieldGroup>
+ </form>
+
+ <SheetFooter>
+ <Button
+ type="submit"
+ form="create-company"
+ disabled={create.isPending || name.trim() === ""}
+ >
+ {create.isPending ? <Spinner /> : null}
+ Add company
+ </Button>
+ <SheetClose asChild>
+ <Button variant="outline">Cancel</Button>
+ </SheetClose>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/apps/app/app/(app)/companies/page.tsx b/apps/app/app/(app)/companies/page.tsx
new file mode 100644
index 00000000..a3b6be50
--- /dev/null
+++ b/apps/app/app/(app)/companies/page.tsx
@@ -0,0 +1,65 @@
+import type { Metadata } from "next";
+import type { SearchParams } from "nuqs/server";
+import {
+ PageShell,
+ PageShellActions,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { companiesSearchParams } from "./companies-search-params";
+import { CompaniesTable } from "./companies-table";
+import { CreateCompanySheet } from "./create-company-sheet";
+
+export const metadata: Metadata = {
+ title: "Companies",
+};
+
+export default async function CompaniesPage({
+ searchParams,
+}: {
+ searchParams: Promise<SearchParams>;
+}) {
+ await requireSession();
+
+ // Parsed with the same parsers the table uses, so the first paint is already
+ // filtered, sorted and on the right page.
+ const values = await companiesSearchParams.load(searchParams);
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ // The rows are awaited so the first paint is the filtered, sorted, correct
+ // page rather than a spinner. The owner and company pickers behind the facet
+ // dropdowns are not — the table draws fine without them.
+ await queryClient.prefetchQuery(
+ trpc.companies.list.queryOptions(companiesSearchParams.toInput(values)),
+ );
+ void queryClient.prefetchQuery(trpc.users.list.queryOptions());
+
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Companies</PageShellTitle>
+ <PageShellDescription>
+ Every account in the pipeline.
+ </PageShellDescription>
+ </PageShellHeading>
+ <PageShellActions>
+ <CreateCompanySheet />
+ </PageShellActions>
+ </PageShellHeader>
+
+ <PageShellContent>
+ <HydrateClient>
+ <CompaniesTable />
+ </HydrateClient>
+ </PageShellContent>
+ </PageShell>
+ );
+}
diff --git a/apps/app/app/(app)/contacts/[contactId]/page.tsx b/apps/app/app/(app)/contacts/[contactId]/page.tsx
new file mode 100644
index 00000000..3c49310c
--- /dev/null
+++ b/apps/app/app/(app)/contacts/[contactId]/page.tsx
@@ -0,0 +1,12 @@
+import { redirect } from "next/navigation";
+import { recordHref } from "@/lib/record-href";
+
+/** Kept for links to the contact page this used to be. */
+export default async function ContactRedirect({
+ params,
+}: {
+ params: Promise<{ contactId: string }>;
+}) {
+ const { contactId } = await params;
+ redirect(recordHref("/contacts", "contact", contactId));
+}
diff --git a/apps/app/app/(app)/contacts/contacts-search-params.ts b/apps/app/app/(app)/contacts/contacts-search-params.ts
new file mode 100644
index 00000000..45b5638e
--- /dev/null
+++ b/apps/app/app/(app)/contacts/contacts-search-params.ts
@@ -0,0 +1,6 @@
+import { createListSearchParams } from "@/components/data-table/list-search-params";
+
+export const contactsSearchParams = createListSearchParams({
+ defaultSort: "name",
+ facetIds: ["owner", "company"] as const,
+});
diff --git a/apps/app/app/(app)/contacts/contacts-table.tsx b/apps/app/app/(app)/contacts/contacts-table.tsx
new file mode 100644
index 00000000..903ee04f
--- /dev/null
+++ b/apps/app/app/(app)/contacts/contacts-table.tsx
@@ -0,0 +1,147 @@
+"use client";
+
+import {
+ DataTable,
+ type DataTableColumn,
+ type DataTableFacet,
+} from "@crm/ui/components/data-table";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useQuery } from "@tanstack/react-query";
+import { CompanyCell } from "@/components/crm/company-cell";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { useTableQuery } from "@/components/data-table/use-table-query";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { contactsSearchParams } from "./contacts-search-params";
+
+type ContactRow = RouterOutputs["contacts"]["list"]["rows"][number];
+
+export function contactName(contact: {
+ firstName: string;
+ lastName: string | null;
+}): string {
+ return [contact.firstName, contact.lastName].filter(Boolean).join(" ");
+}
+
+const COLUMNS: DataTableColumn<ContactRow>[] = [
+ {
+ id: "name",
+ header: "Name",
+ sortable: true,
+ hideable: false,
+ width: "w-[22%]",
+ cell: (row) => (
+ <span className="truncate font-medium">{contactName(row)}</span>
+ ),
+ },
+ {
+ id: "title",
+ header: "Title",
+ sortable: true,
+ width: "w-[20%]",
+ hideBelow: "lg",
+ cell: (row) =>
+ row.title ? (
+ <span className="truncate">{row.title}</span>
+ ) : (
+ <EmptyCellValue />
+ ),
+ },
+ {
+ id: "email",
+ header: "Email",
+ sortable: true,
+ width: "w-[24%]",
+ hideBelow: "md",
+ cell: (row) =>
+ row.email ? (
+ <span className="truncate text-muted-foreground">{row.email}</span>
+ ) : (
+ <EmptyCellValue />
+ ),
+ },
+ {
+ id: "company",
+ header: "Company",
+ sortable: true,
+ width: "w-[18%]",
+ cell: (row) => <CompanyCell company={row.company} />,
+ },
+ {
+ id: "owner",
+ header: "Owner",
+ width: "w-[16%]",
+ hideBelow: "md",
+ cell: (row) => <OwnerCell owner={row.owner} />,
+ },
+ {
+ id: "lastActivity",
+ header: "Last activity",
+ align: "right",
+ width: "w-[12%]",
+ hideBelow: "sm",
+ cell: (row) => (
+ <span className="text-muted-foreground">
+ {relativeTimeFromIso(row.lastActivityAt)}
+ </span>
+ ),
+ },
+];
+
+export function ContactsTable() {
+ const openRecord = useOpenRecord();
+ const trpc = useTRPC();
+ const { query, input } = useTableQuery(contactsSearchParams);
+
+ const contacts = useQuery({
+ ...trpc.contacts.list.queryOptions(input),
+ placeholderData: (previous) => previous,
+ });
+ const users = useQuery(trpc.users.list.queryOptions());
+ const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
+
+ const facetCounts = contacts.data?.facetCounts;
+
+ const facets: DataTableFacet[] = [
+ {
+ id: "owner",
+ label: "Owner",
+ options: [
+ { value: "unassigned", label: "Unassigned" },
+ ...(users.data ?? []).map((user) => ({
+ value: user.id,
+ label: user.name,
+ })),
+ ].filter((option) => (facetCounts?.owner?.[option.value] ?? 0) > 0),
+ },
+ {
+ id: "company",
+ label: "Company",
+ options: [
+ { value: "none", label: "No company" },
+ ...(companies.data ?? []).map((company) => ({
+ value: company.id,
+ label: company.name,
+ })),
+ ].filter((option) => (facetCounts?.company?.[option.value] ?? 0) > 0),
+ },
+ ];
+
+ return (
+ <DataTable
+ query={query}
+ columns={COLUMNS}
+ rows={contacts.data?.rows ?? []}
+ total={contacts.data?.total ?? 0}
+ facetCounts={facetCounts}
+ facets={facets}
+ getRowId={(row) => row.id}
+ loading={contacts.isFetching}
+ searchPlaceholder="Search by name, email or company…"
+ onRowClick={(row) => openRecord({ kind: "contact", id: row.id })}
+ empty="No contacts match this view."
+ />
+ );
+}
diff --git a/apps/app/app/(app)/contacts/create-contact-sheet.tsx b/apps/app/app/(app)/contacts/create-contact-sheet.tsx
new file mode 100644
index 00000000..8e117ef2
--- /dev/null
+++ b/apps/app/app/(app)/contacts/create-contact-sheet.tsx
@@ -0,0 +1,222 @@
+"use client";
+
+import Add from "@carbon/icons-react/es/Add";
+import { Button } from "@crm/ui/components/button";
+import { Field, FieldGroup, FieldLabel } from "@crm/ui/components/field";
+import { Icon } from "@crm/ui/components/icon";
+import { Input } from "@crm/ui/components/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@crm/ui/components/select";
+import {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ SheetTrigger,
+} from "@crm/ui/components/sheet";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { parseAsBoolean, useQueryState } from "nuqs";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { useTRPC } from "@/lib/trpc/client";
+
+const NONE = "none";
+
+export function CreateContactSheet({
+ /** Pre-selects a company when opened from that company's page. */
+ companyId,
+}: {
+ companyId?: string;
+}) {
+ const openRecord = useOpenRecord();
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ // URL state, like every other view state here — see CreateCompanySheet.
+ const [open, setOpen] = useQueryState(
+ "new",
+ parseAsBoolean.withDefault(false),
+ );
+ const [firstName, setFirstName] = useState("");
+ const [lastName, setLastName] = useState("");
+ const [email, setEmail] = useState("");
+ const [title, setTitle] = useState("");
+ const [company, setCompany] = useState(companyId ?? NONE);
+ const [ownerId, setOwnerId] = useState(NONE);
+
+ const firstNameId = useId();
+ const lastNameId = useId();
+ const emailId = useId();
+ const titleId = useId();
+
+ const users = useQuery(trpc.users.list.queryOptions());
+ const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
+
+ const create = useMutation(
+ trpc.contacts.create.mutationOptions({
+ onSuccess: async (contact) => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.contacts.list.queryKey(),
+ }),
+ // The company's own page shows its contacts and their count.
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.list.queryKey(),
+ }),
+ ]);
+ toast.success(
+ `${[contact.firstName, contact.lastName].filter(Boolean).join(" ")} added.`,
+ );
+ await setOpen(null);
+ setFirstName("");
+ setLastName("");
+ setEmail("");
+ setTitle("");
+ openRecord({ kind: "contact", id: contact.id });
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ return (
+ <Sheet open={open} onOpenChange={(next) => setOpen(next || null)}>
+ <SheetTrigger asChild>
+ <Button size="sm">
+ <Icon icon={Add} data-icon="inline-start" />
+ New contact
+ </Button>
+ </SheetTrigger>
+ <SheetContent side="right">
+ <SheetHeader>
+ <SheetTitle>New contact</SheetTitle>
+ <SheetDescription>
+ Email addresses are unique, so importing the same person twice
+ updates them rather than duplicating them.
+ </SheetDescription>
+ </SheetHeader>
+
+ <form
+ id="create-contact"
+ className="flex-1 overflow-y-auto px-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ create.mutate({
+ firstName,
+ lastName: lastName || undefined,
+ email: email || undefined,
+ title: title || undefined,
+ companyId: company === NONE ? null : company,
+ ownerId: ownerId === NONE ? null : ownerId,
+ });
+ }}
+ >
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor={firstNameId}>First name</FieldLabel>
+ <Input
+ id={firstNameId}
+ value={firstName}
+ onChange={(event) => setFirstName(event.target.value)}
+ autoComplete="off"
+ required
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor={lastNameId}>Last name</FieldLabel>
+ <Input
+ id={lastNameId}
+ value={lastName}
+ onChange={(event) => setLastName(event.target.value)}
+ autoComplete="off"
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor={emailId}>Email</FieldLabel>
+ <Input
+ id={emailId}
+ type="email"
+ value={email}
+ onChange={(event) => setEmail(event.target.value)}
+ autoComplete="off"
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor={titleId}>Title</FieldLabel>
+ <Input
+ id={titleId}
+ value={title}
+ onChange={(event) => setTitle(event.target.value)}
+ placeholder="Head of Security"
+ autoComplete="off"
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="create-contact-company">Company</FieldLabel>
+ <Select value={company} onValueChange={setCompany}>
+ <SelectTrigger id="create-contact-company">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={NONE}>No company</SelectItem>
+ {(companies.data ?? []).map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {option.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="create-contact-owner">Owner</FieldLabel>
+ <Select value={ownerId} onValueChange={setOwnerId}>
+ <SelectTrigger id="create-contact-owner">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={NONE}>Unassigned</SelectItem>
+ {(users.data ?? []).map((user) => (
+ <SelectItem key={user.id} value={user.id}>
+ {user.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ </FieldGroup>
+ </form>
+
+ <SheetFooter>
+ <Button
+ type="submit"
+ form="create-contact"
+ disabled={create.isPending || firstName.trim() === ""}
+ >
+ {create.isPending ? <Spinner /> : null}
+ Add contact
+ </Button>
+ <SheetClose asChild>
+ <Button variant="outline">Cancel</Button>
+ </SheetClose>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/apps/app/app/(app)/contacts/page.tsx b/apps/app/app/(app)/contacts/page.tsx
new file mode 100644
index 00000000..5889bc30
--- /dev/null
+++ b/apps/app/app/(app)/contacts/page.tsx
@@ -0,0 +1,61 @@
+import type { Metadata } from "next";
+import type { SearchParams } from "nuqs/server";
+import {
+ PageShell,
+ PageShellActions,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { contactsSearchParams } from "./contacts-search-params";
+import { ContactsTable } from "./contacts-table";
+import { CreateContactSheet } from "./create-contact-sheet";
+
+export const metadata: Metadata = {
+ title: "Contacts",
+};
+
+export default async function ContactsPage({
+ searchParams,
+}: {
+ searchParams: Promise<SearchParams>;
+}) {
+ await requireSession();
+
+ const values = await contactsSearchParams.load(searchParams);
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ await queryClient.prefetchQuery(
+ trpc.contacts.list.queryOptions(contactsSearchParams.toInput(values)),
+ );
+ void queryClient.prefetchQuery(trpc.users.list.queryOptions());
+ void queryClient.prefetchQuery(
+ trpc.companies.options.queryOptions({ q: "" }),
+ );
+
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Contacts</PageShellTitle>
+ <PageShellDescription>Everyone in the pipeline.</PageShellDescription>
+ </PageShellHeading>
+ <PageShellActions>
+ <CreateContactSheet />
+ </PageShellActions>
+ </PageShellHeader>
+
+ <PageShellContent>
+ <HydrateClient>
+ <ContactsTable />
+ </HydrateClient>
+ </PageShellContent>
+ </PageShell>
+ );
+}
diff --git a/apps/app/app/(app)/dashboard-summary.tsx b/apps/app/app/(app)/dashboard-summary.tsx
new file mode 100644
index 00000000..e8a7cc8c
--- /dev/null
+++ b/apps/app/app/(app)/dashboard-summary.tsx
@@ -0,0 +1,272 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+} from "@crm/ui/components/card";
+import { Checkbox } from "@crm/ui/components/checkbox";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { Separator } from "@crm/ui/components/separator";
+import { StatusIndicator } from "@crm/ui/components/status-indicator";
+import { formatMoney, relativeTimeFromIso } from "@crm/ui/lib/format";
+import {
+ useMutation,
+ useQueryClient,
+ useSuspenseQuery,
+} from "@tanstack/react-query";
+import Link from "next/link";
+import { toast } from "sonner";
+import { dealStageLabel } from "@/components/crm/deal-stage";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { RecordLink } from "@/components/crm/record-sheet/record-link";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import {
+ ActivityIcon,
+ activityLabel,
+} from "@/components/crm/timeline/activity-icon";
+import { useTRPC } from "@/lib/trpc/client";
+
+const dateFormat = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+});
+
+export function DashboardSummary() {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const openRecord = useOpenRecord();
+
+ const { data } = useSuspenseQuery(trpc.dashboard.summary.queryOptions());
+
+ const complete = useMutation(
+ trpc.activities.complete.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.dashboard.summary.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.timeline.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.myTasks.queryKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const {
+ pipeline,
+ wonThisMonth,
+ closingThisMonth,
+ overdueTasks,
+ recentActivity,
+ } = data;
+
+ return (
+ <div className="flex flex-col gap-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>Pipeline</CardTitle>
+ <CardAction>
+ <span className="text-muted-foreground text-xs">
+ {pipeline.totalDeals} open ·{" "}
+ <span className="tabular-nums">
+ {formatMoney(pipeline.totalCents)}
+ </span>
+ </span>
+ </CardAction>
+ </CardHeader>
+ <Separator />
+ <CardContent>
+ <div className="grid gap-3 @md/page-content:grid-cols-2 @3xl/page-content:grid-cols-4">
+ {pipeline.stages.map((stage) => (
+ <Link
+ key={stage.stage}
+ href={`/deals?stage=${stage.stage}`}
+ className="flex flex-col gap-1 border p-3 hover:bg-muted/40"
+ >
+ <span className="text-muted-foreground text-xs">
+ {dealStageLabel(stage.stage)}
+ </span>
+ <span className="font-medium text-xl tabular-nums">
+ {formatMoney(stage.valueCents)}
+ </span>
+ <span className="text-muted-foreground text-xs tabular-nums">
+ {stage.count} {stage.count === 1 ? "deal" : "deals"}
+ </span>
+ </Link>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+
+ <div className="grid gap-6 @3xl/page-content:grid-cols-2">
+ <Card>
+ <CardHeader>
+ <CardTitle>Closing this month</CardTitle>
+ <CardAction>
+ <span className="text-muted-foreground text-xs">
+ {wonThisMonth.count} won ·{" "}
+ <span className="tabular-nums">
+ {formatMoney(wonThisMonth.valueCents)}
+ </span>
+ </span>
+ </CardAction>
+ </CardHeader>
+ <Separator />
+ <CardContent>
+ {closingThisMonth.length === 0 ? (
+ <p className="py-6 text-center text-muted-foreground text-xs">
+ Nothing is due to close this month.
+ </p>
+ ) : (
+ <ul className="divide-y">
+ {closingThisMonth.map((deal) => (
+ <li key={deal.id} className="flex items-center gap-3 py-2.5">
+ <button
+ type="button"
+ onClick={() => openRecord({ kind: "deal", id: deal.id })}
+ className="flex min-w-0 flex-1 flex-col text-left hover:underline"
+ >
+ <span className="truncate font-medium text-sm">
+ {deal.name}
+ </span>
+ <span className="truncate text-muted-foreground text-xs">
+ {deal.company.name} · {dealStageLabel(deal.stage)}
+ </span>
+ </button>
+ <span className="shrink-0 text-muted-foreground text-xs">
+ {deal.expectedCloseDate
+ ? dateFormat.format(new Date(deal.expectedCloseDate))
+ : null}
+ </span>
+ <span className="shrink-0 tabular-nums text-sm">
+ {deal.amountCents === null ? (
+ <EmptyCellValue />
+ ) : (
+ formatMoney(deal.amountCents, deal.currency)
+ )}
+ </span>
+ <OwnerCell owner={deal.owner} />
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>My overdue tasks</CardTitle>
+ <CardAction>
+ {overdueTasks.length > 0 ? (
+ <StatusIndicator
+ tone="error"
+ className="text-xs"
+ label={`${overdueTasks.length} overdue`}
+ />
+ ) : null}
+ </CardAction>
+ </CardHeader>
+ <Separator />
+ <CardContent>
+ {overdueTasks.length === 0 ? (
+ <p className="py-6 text-center text-muted-foreground text-xs">
+ Nothing overdue. Good.
+ </p>
+ ) : (
+ <ul className="divide-y">
+ {overdueTasks.map((task) => (
+ <li key={task.id} className="flex items-center gap-3 py-2.5">
+ <Checkbox
+ checked={false}
+ disabled={complete.isPending}
+ aria-label="Mark as done"
+ onCheckedChange={() =>
+ complete.mutate({ id: task.id, completed: true })
+ }
+ />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm">{task.subject}</span>
+ <span className="flex min-w-0 text-xs">
+ {task.deal ? (
+ <RecordLink kind="deal" id={task.deal.id}>
+ {task.deal.name}
+ </RecordLink>
+ ) : task.company ? (
+ <RecordLink kind="company" id={task.company.id}>
+ {task.company.name}
+ </RecordLink>
+ ) : null}
+ </span>
+ </span>
+ <StatusIndicator
+ tone="error"
+ className="shrink-0 text-xs"
+ label={relativeTimeFromIso(task.dueAt)}
+ />
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Recent activity</CardTitle>
+ <CardAction>
+ <Button asChild variant="ghost" size="sm">
+ <Link href="/companies">All companies</Link>
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <Separator />
+ <CardContent>
+ {recentActivity.length === 0 ? (
+ <p className="py-6 text-center text-muted-foreground text-xs">
+ Nothing has happened yet.
+ </p>
+ ) : (
+ <ul className="divide-y">
+ {recentActivity.map((entry) => (
+ <li key={entry.id} className="flex items-start gap-3 py-2.5">
+ <span className="mt-0.5 text-muted-foreground">
+ <ActivityIcon type={entry.type} />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm">
+ {entry.subject ?? activityLabel(entry.type)}
+ </span>
+ <span className="flex min-w-0 items-center gap-1 truncate text-muted-foreground text-xs">
+ {entry.company ? (
+ <RecordLink kind="company" id={entry.company.id}>
+ {entry.company.name}
+ </RecordLink>
+ ) : null}
+ <span className="truncate">
+ {entry.deal ? ` · ${entry.deal.name}` : null}
+ {` · ${entry.createdBy.name}`}
+ </span>
+ </span>
+ </span>
+ <span className="shrink-0 text-muted-foreground text-xs">
+ {relativeTimeFromIso(entry.createdAt)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/apps/app/app/(app)/deals/[dealId]/page.tsx b/apps/app/app/(app)/deals/[dealId]/page.tsx
new file mode 100644
index 00000000..6df89cd7
--- /dev/null
+++ b/apps/app/app/(app)/deals/[dealId]/page.tsx
@@ -0,0 +1,12 @@
+import { redirect } from "next/navigation";
+import { recordHref } from "@/lib/record-href";
+
+/** Kept for links to the deal page this used to be. */
+export default async function DealRedirect({
+ params,
+}: {
+ params: Promise<{ dealId: string }>;
+}) {
+ const { dealId } = await params;
+ redirect(recordHref("/deals", "deal", dealId));
+}
diff --git a/apps/app/app/(app)/deals/create-deal-sheet.tsx b/apps/app/app/(app)/deals/create-deal-sheet.tsx
new file mode 100644
index 00000000..85229f9e
--- /dev/null
+++ b/apps/app/app/(app)/deals/create-deal-sheet.tsx
@@ -0,0 +1,242 @@
+"use client";
+
+import Add from "@carbon/icons-react/es/Add";
+import { Button } from "@crm/ui/components/button";
+import {
+ Field,
+ FieldDescription,
+ FieldGroup,
+ FieldLabel,
+} from "@crm/ui/components/field";
+import { Icon } from "@crm/ui/components/icon";
+import { Input } from "@crm/ui/components/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@crm/ui/components/select";
+import {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ SheetTrigger,
+} from "@crm/ui/components/sheet";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { parseAsBoolean, useQueryState } from "nuqs";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { dealStageLabel, OPEN_STAGES } from "@/components/crm/deal-stage";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { useTRPC } from "@/lib/trpc/client";
+
+const UNSET = "";
+
+export function CreateDealSheet({
+ /** Pre-selects a company when opened from that company's page. */
+ companyId,
+}: {
+ companyId?: string;
+}) {
+ const openRecord = useOpenRecord();
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ // URL state, like every other view state here — see CreateCompanySheet.
+ const [open, setOpen] = useQueryState(
+ "new",
+ parseAsBoolean.withDefault(false),
+ );
+ const [name, setName] = useState("");
+ const [company, setCompany] = useState(companyId ?? UNSET);
+ const [ownerId, setOwnerId] = useState(UNSET);
+ const [stage, setStage] = useState<string>("DEMO_BOOKED");
+ const [amount, setAmount] = useState("");
+ const [closeDate, setCloseDate] = useState("");
+
+ const nameId = useId();
+ const amountId = useId();
+ const closeDateId = useId();
+
+ const users = useQuery(trpc.users.list.queryOptions());
+ const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
+ const me = useQuery(trpc.users.me.queryOptions());
+
+ // Whoever is adding the deal is almost always the one working it.
+ const resolvedOwner = ownerId || me.data?.id || UNSET;
+
+ const create = useMutation(
+ trpc.deals.create.mutationOptions({
+ onSuccess: async (deal) => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.list.queryKey(),
+ }),
+ ]);
+ toast.success(`${deal.name} added.`);
+ await setOpen(null);
+ setName("");
+ setAmount("");
+ setCloseDate("");
+ openRecord({ kind: "deal", id: deal.id });
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const ready =
+ name.trim() !== "" && company !== UNSET && resolvedOwner !== UNSET;
+
+ return (
+ <Sheet open={open} onOpenChange={(next) => setOpen(next || null)}>
+ <SheetTrigger asChild>
+ <Button size="sm">
+ <Icon icon={Add} data-icon="inline-start" />
+ New deal
+ </Button>
+ </SheetTrigger>
+ <SheetContent side="right">
+ <SheetHeader>
+ <SheetTitle>New deal</SheetTitle>
+ <SheetDescription>
+ Every deal belongs to a company and has someone's name against it.
+ </SheetDescription>
+ </SheetHeader>
+
+ <form
+ id="create-deal"
+ className="flex-1 overflow-y-auto px-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const parsed = Number.parseFloat(amount);
+ create.mutate({
+ name,
+ companyId: company,
+ ownerId: resolvedOwner,
+ stage: stage as never,
+ // Typed in whole currency, stored and summed in cents.
+ amountCents: Number.isFinite(parsed)
+ ? Math.round(parsed * 100)
+ : null,
+ expectedCloseDate: closeDate || null,
+ });
+ }}
+ >
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor={nameId}>Name</FieldLabel>
+ <Input
+ id={nameId}
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ placeholder="Stripe — Comp AI"
+ autoComplete="off"
+ required
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="create-deal-company">Company</FieldLabel>
+ <Select value={company} onValueChange={setCompany}>
+ <SelectTrigger id="create-deal-company">
+ <SelectValue placeholder="Choose a company" />
+ </SelectTrigger>
+ <SelectContent>
+ {(companies.data ?? []).map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {option.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="create-deal-owner">Owner</FieldLabel>
+ <Select value={resolvedOwner} onValueChange={setOwnerId}>
+ <SelectTrigger id="create-deal-owner">
+ <SelectValue placeholder="Choose an owner" />
+ </SelectTrigger>
+ <SelectContent>
+ {(users.data ?? []).map((user) => (
+ <SelectItem key={user.id} value={user.id}>
+ {user.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="create-deal-stage">Stage</FieldLabel>
+ <Select value={stage} onValueChange={setStage}>
+ <SelectTrigger id="create-deal-stage">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {OPEN_STAGES.map((value) => (
+ <SelectItem key={value} value={value}>
+ {dealStageLabel(value)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ A new deal is an open deal — close it from the pipeline once
+ there is an outcome to record.
+ </FieldDescription>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor={amountId}>Amount (USD)</FieldLabel>
+ <Input
+ id={amountId}
+ value={amount}
+ onChange={(event) => setAmount(event.target.value)}
+ placeholder="24000"
+ inputMode="decimal"
+ autoComplete="off"
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor={closeDateId}>Expected close date</FieldLabel>
+ <Input
+ id={closeDateId}
+ type="date"
+ value={closeDate}
+ onChange={(event) => setCloseDate(event.target.value)}
+ />
+ </Field>
+ </FieldGroup>
+ </form>
+
+ <SheetFooter>
+ <Button
+ type="submit"
+ form="create-deal"
+ disabled={create.isPending || !ready}
+ >
+ {create.isPending ? <Spinner /> : null}
+ Add deal
+ </Button>
+ <SheetClose asChild>
+ <Button variant="outline">Cancel</Button>
+ </SheetClose>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/apps/app/app/(app)/deals/deals-board.tsx b/apps/app/app/(app)/deals/deals-board.tsx
new file mode 100644
index 00000000..05d214bf
--- /dev/null
+++ b/apps/app/app/(app)/deals/deals-board.tsx
@@ -0,0 +1,222 @@
+"use client";
+
+import type { DealStage } from "@crm/db/enums";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { EntityLogo } from "@crm/ui/components/entity-logo";
+import { Spinner } from "@crm/ui/components/spinner";
+import { formatMoney } from "@crm/ui/lib/format";
+import { cn } from "@crm/ui/lib/utils";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { parseAsString, useQueryState, useQueryStates } from "nuqs";
+import { useState } from "react";
+import { toast } from "sonner";
+import { dealStageLabel, LOSING_STAGES } from "@/components/crm/deal-stage";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { DealStageMenu } from "@/components/crm/stage-change";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+
+type Column = RouterOutputs["deals"]["board"]["columns"][number];
+type Card = Column["cards"][number];
+
+const dateFormat = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+});
+
+/**
+ * The open pipeline, as columns you can drag between.
+ *
+ * Native HTML drag and drop rather than a library: the interaction is "pick up
+ * one card, drop it on one column", and that is what the platform already does.
+ * Dropping onto a losing stage opens the same reason dialog the table uses —
+ * the API refuses those without one either way.
+ */
+export function DealsBoard() {
+ const openRecord = useOpenRecord();
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ const [owner] = useQueryState("owner", parseAsString.withDefault("all"));
+ const [q] = useQueryState("q", parseAsString.withDefault(""));
+ const [, setCloseParams] = useQueryStates({
+ closing: parseAsString,
+ closingStage: parseAsString,
+ });
+
+ const [dragging, setDragging] = useState<string | null>(null);
+ const [over, setOver] = useState<DealStage | null>(null);
+
+ const board = useQuery({
+ ...trpc.deals.board.queryOptions({ q, owner, limit: 50 }),
+ placeholderData: (previous) => previous,
+ });
+
+ const setStage = useMutation(
+ trpc.deals.setStage.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.board.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const drop = (stage: DealStage) => {
+ const id = dragging;
+ setDragging(null);
+ setOver(null);
+ if (!id) return;
+
+ if (LOSING_STAGES.includes(stage)) {
+ void setCloseParams({ closing: id, closingStage: stage });
+ return;
+ }
+ setStage.mutate({ id, stage });
+ };
+
+ if (board.isPending) {
+ return (
+ <div className="flex justify-center py-12">
+ <Spinner />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex min-h-0 flex-1 gap-3 overflow-x-auto pb-2">
+ {(board.data?.columns ?? []).map((column) => (
+ /*
+ * A column is a drop target across its whole area, not just the
+ * cards in it — an empty column has to be droppable too.
+ */
+ // biome-ignore lint/a11y/noStaticElementInteractions: a drop target is pointer-only by nature. Dragging is an enhancement, not the only route: every card carries the same stage menu the table rows use, which is keyboard-operable.
+ <section
+ key={column.stage}
+ onDragOver={(event) => {
+ event.preventDefault();
+ setOver(column.stage);
+ }}
+ onDragLeave={() =>
+ setOver((current) => (current === column.stage ? null : current))
+ }
+ onDrop={() => drop(column.stage)}
+ className={cn(
+ "flex w-72 shrink-0 flex-col border",
+ over === column.stage && "bg-muted/50",
+ )}
+ >
+ <header className="flex items-baseline justify-between gap-2 border-b px-3 py-2">
+ <span className="truncate font-medium text-sm">
+ {dealStageLabel(column.stage)}
+ </span>
+ <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
+ {column.total} · {formatMoney(column.valueCents)}
+ </span>
+ </header>
+
+ <ul className="flex min-h-24 flex-1 flex-col gap-2 overflow-y-auto p-2">
+ {column.cards.map((card) => (
+ <BoardCard
+ key={card.id}
+ card={card}
+ dragging={dragging === card.id}
+ onDragStart={() => setDragging(card.id)}
+ onDragEnd={() => setDragging(null)}
+ onOpen={() => openRecord({ kind: "deal", id: card.id })}
+ />
+ ))}
+
+ {column.cards.length < column.total ? (
+ <li className="py-2 text-center text-muted-foreground text-xs">
+ {column.total - column.cards.length} more — narrow the filters
+ to see them
+ </li>
+ ) : null}
+ </ul>
+ </section>
+ ))}
+ </div>
+ );
+}
+
+function BoardCard({
+ card,
+ dragging,
+ onDragStart,
+ onDragEnd,
+ onOpen,
+}: {
+ card: Card;
+ dragging: boolean;
+ onDragStart: () => void;
+ onDragEnd: () => void;
+ onOpen: () => void;
+}) {
+ return (
+ <li
+ draggable
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ className={cn(
+ "flex cursor-grab flex-col gap-2 border bg-background p-2.5",
+ dragging && "opacity-50",
+ )}
+ >
+ {/*
+ * The title is the clickable region rather than the whole card: the
+ * footer holds a stage menu, and a button inside a button is neither
+ * valid nor operable.
+ */}
+ <button
+ type="button"
+ onClick={onOpen}
+ className="truncate text-left font-medium text-sm hover:underline"
+ >
+ {card.name}
+ </button>
+
+ <span className="flex min-w-0 items-center gap-2">
+ <EntityLogo
+ src={card.company.iconUrl}
+ name={card.company.name}
+ size="sm"
+ />
+ <span className="truncate text-muted-foreground text-xs">
+ {card.company.name}
+ </span>
+ </span>
+
+ <span className="flex items-center justify-between gap-2">
+ <span className="tabular-nums text-sm">
+ {card.amountCents === null ? (
+ <EmptyCellValue />
+ ) : (
+ formatMoney(card.amountCents, card.currency)
+ )}
+ </span>
+ <span className="flex items-center gap-2">
+ {card.expectedCloseDate ? (
+ <span className="text-muted-foreground text-xs">
+ {dateFormat.format(new Date(card.expectedCloseDate))}
+ </span>
+ ) : null}
+ <OwnerCell owner={card.owner} compact />
+ </span>
+ </span>
+
+ {/* The keyboard route to the same move dragging performs. */}
+ <DealStageMenu dealId={card.id} stage={card.stage} />
+ </li>
+ );
+}
diff --git a/apps/app/app/(app)/deals/deals-search-params.ts b/apps/app/app/(app)/deals/deals-search-params.ts
new file mode 100644
index 00000000..ba26bcb4
--- /dev/null
+++ b/apps/app/app/(app)/deals/deals-search-params.ts
@@ -0,0 +1,21 @@
+import { parseAsStringLiteral } from "nuqs/server";
+import { createListSearchParams } from "@/components/data-table/list-search-params";
+
+export const dealsSearchParams = createListSearchParams({
+ // Pipeline order by default: the deals closest to closing are the ones a rep
+ // opens this page to look at.
+ defaultSort: "stage",
+ tabId: "status",
+ facetIds: ["owner", "stage", "closing"] as const,
+});
+
+/** `?view=board` swaps the table for the pipeline columns. */
+export const dealsViewParser = parseAsStringLiteral([
+ "table",
+ "board",
+] as const).withDefault("table");
+
+export const loadDealsView = (searchParams: Record<string, unknown>) =>
+ dealsViewParser.parseServerSide(
+ searchParams.view as string | string[] | undefined,
+ );
diff --git a/apps/app/app/(app)/deals/deals-table.tsx b/apps/app/app/(app)/deals/deals-table.tsx
new file mode 100644
index 00000000..218516b0
--- /dev/null
+++ b/apps/app/app/(app)/deals/deals-table.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+import {
+ DataTable,
+ type DataTableColumn,
+ type DataTableFacet,
+} from "@crm/ui/components/data-table";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { formatMoney, relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useQuery } from "@tanstack/react-query";
+import { CLOSING_OPTIONS } from "@/components/crm/closing-window";
+import { CompanyCell } from "@/components/crm/company-cell";
+import { DEAL_STAGE_OPTIONS } from "@/components/crm/deal-stage";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { DealStageMenu } from "@/components/crm/stage-change";
+import { useTableQuery } from "@/components/data-table/use-table-query";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { dealsSearchParams } from "./deals-search-params";
+
+type DealRow = RouterOutputs["deals"]["list"]["rows"][number];
+
+const dateFormat = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+});
+
+const COLUMNS: DataTableColumn<DealRow>[] = [
+ {
+ id: "name",
+ header: "Deal",
+ sortable: true,
+ hideable: false,
+ width: "w-[24%]",
+ cell: (row) => <span className="truncate font-medium">{row.name}</span>,
+ },
+ {
+ id: "company",
+ header: "Company",
+ sortable: true,
+ width: "w-[18%]",
+ cell: (row) => <CompanyCell company={row.company} />,
+ },
+ {
+ id: "stage",
+ header: "Stage",
+ sortable: true,
+ width: "w-[18%]",
+ // Editable in place: moving a deal along is the single most common thing
+ // anyone does here, and it should not need a page load.
+ cell: (row) => <DealStageMenu dealId={row.id} stage={row.stage} />,
+ },
+ {
+ id: "amount",
+ header: "Amount",
+ sortable: true,
+ align: "right",
+ width: "w-[12%]",
+ hideBelow: "sm",
+ cell: (row) =>
+ row.amountCents === null ? (
+ <EmptyCellValue />
+ ) : (
+ <span className="tabular-nums">
+ {formatMoney(row.amountCents, row.currency)}
+ </span>
+ ),
+ },
+ {
+ id: "owner",
+ header: "Owner",
+ width: "w-[14%]",
+ hideBelow: "md",
+ cell: (row) => <OwnerCell owner={row.owner} />,
+ },
+ {
+ id: "expectedCloseDate",
+ header: "Close date",
+ sortable: true,
+ width: "w-[12%]",
+ hideBelow: "lg",
+ cell: (row) =>
+ row.expectedCloseDate ? (
+ <span className="text-muted-foreground">
+ {dateFormat.format(new Date(row.expectedCloseDate))}
+ </span>
+ ) : (
+ <EmptyCellValue />
+ ),
+ },
+ {
+ id: "lastActivity",
+ header: "Last activity",
+ align: "right",
+ width: "w-[12%]",
+ hideBelow: "lg",
+ cell: (row) => (
+ <span className="text-muted-foreground">
+ {relativeTimeFromIso(row.lastActivityAt)}
+ </span>
+ ),
+ },
+];
+
+export function DealsTable() {
+ const openRecord = useOpenRecord();
+ const trpc = useTRPC();
+ const { query, input } = useTableQuery(dealsSearchParams);
+
+ const deals = useQuery({
+ ...trpc.deals.list.queryOptions(input),
+ placeholderData: (previous) => previous,
+ });
+ const users = useQuery(trpc.users.list.queryOptions());
+
+ const facetCounts = deals.data?.facetCounts;
+
+ const facets: DataTableFacet[] = [
+ {
+ id: "owner",
+ label: "Owner",
+ options: (users.data ?? [])
+ .map((user) => ({ value: user.id, label: user.name }))
+ .filter((option) => (facetCounts?.owner?.[option.value] ?? 0) > 0),
+ },
+ {
+ id: "stage",
+ label: "Stage",
+ options: DEAL_STAGE_OPTIONS.filter(
+ (option) => (facetCounts?.stage?.[option.value] ?? 0) > 0,
+ ),
+ },
+ {
+ id: "closing",
+ label: "Closing",
+ options: CLOSING_OPTIONS.filter(
+ (option) => (facetCounts?.closing?.[option.value] ?? 0) > 0,
+ ).map((option) => ({ value: option.value, label: option.label })),
+ },
+ ];
+
+ const openValueCents = deals.data?.openValueCents;
+
+ return (
+ <DataTable
+ query={query}
+ columns={COLUMNS}
+ rows={deals.data?.rows ?? []}
+ total={deals.data?.total ?? 0}
+ facetCounts={facetCounts}
+ facets={facets}
+ tabs={{
+ id: "status",
+ allLabel: "All deals",
+ options: [
+ { value: "open", label: "Open" },
+ { value: "closed", label: "Closed" },
+ ],
+ }}
+ getRowId={(row) => row.id}
+ loading={deals.isFetching}
+ searchPlaceholder="Search deals by name or company…"
+ onRowClick={(row) => openRecord({ kind: "deal", id: row.id })}
+ empty="No deals match this view."
+ meta={
+ // The open pipeline for everything the filters match, not just the
+ // page — summed in Postgres.
+ openValueCents === null || openValueCents === undefined ? undefined : (
+ <span>
+ {deals.data?.total ?? 0} deals ·{" "}
+ <span className="tabular-nums">{formatMoney(openValueCents)}</span>{" "}
+ open pipeline
+ </span>
+ )
+ }
+ />
+ );
+}
diff --git a/apps/app/app/(app)/deals/deals-view.tsx b/apps/app/app/(app)/deals/deals-view.tsx
new file mode 100644
index 00000000..98e9c83a
--- /dev/null
+++ b/apps/app/app/(app)/deals/deals-view.tsx
@@ -0,0 +1,42 @@
+"use client";
+
+import ChartColumn from "@carbon/icons-react/es/ChartColumn";
+import ListChecked from "@carbon/icons-react/es/ListChecked";
+import { Icon } from "@crm/ui/components/icon";
+import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";
+import { useQueryState } from "nuqs";
+import { DealsBoard } from "./deals-board";
+import { dealsViewParser } from "./deals-search-params";
+import { DealsTable } from "./deals-table";
+
+/** Table or board, from `?view=` — so "the board, filtered to me" is a link. */
+export function DealsViewToggle() {
+ const [view, setView] = useQueryState("view", dealsViewParser);
+
+ return (
+ <ToggleGroup
+ type="single"
+ value={view}
+ onValueChange={(next) =>
+ next && setView(next === "board" ? "board" : null)
+ }
+ variant="outline"
+ size="sm"
+ >
+ <ToggleGroupItem value="table" aria-label="Table">
+ <Icon icon={ListChecked} />
+ Table
+ </ToggleGroupItem>
+ <ToggleGroupItem value="board" aria-label="Board">
+ <Icon icon={ChartColumn} />
+ Board
+ </ToggleGroupItem>
+ </ToggleGroup>
+ );
+}
+
+export function DealsView() {
+ const [view] = useQueryState("view", dealsViewParser);
+
+ return view === "board" ? <DealsBoard /> : <DealsTable />;
+}
diff --git a/apps/app/app/(app)/deals/page.tsx b/apps/app/app/(app)/deals/page.tsx
new file mode 100644
index 00000000..997e01a1
--- /dev/null
+++ b/apps/app/app/(app)/deals/page.tsx
@@ -0,0 +1,78 @@
+import type { Metadata } from "next";
+import type { SearchParams } from "nuqs/server";
+import {
+ PageShell,
+ PageShellActions,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { CreateDealSheet } from "./create-deal-sheet";
+import { dealsSearchParams, loadDealsView } from "./deals-search-params";
+import { DealsView, DealsViewToggle } from "./deals-view";
+
+export const metadata: Metadata = {
+ title: "Deals",
+};
+
+export default async function DealsPage({
+ searchParams,
+}: {
+ searchParams: Promise<SearchParams>;
+}) {
+ await requireSession();
+
+ const values = await dealsSearchParams.load(searchParams);
+ const view = loadDealsView(await searchParams);
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ // The rows are awaited so the first paint is the filtered, sorted, correct
+ // page rather than a spinner. The owner and company pickers behind the facet
+ // dropdowns are not — the table draws fine without them.
+ // Only the view actually being shown is prefetched — the other one is a
+ // second set of queries nobody asked for.
+ await (view === "board"
+ ? queryClient.prefetchQuery(
+ trpc.deals.board.queryOptions({
+ q: values.q.trim(),
+ owner: values.owner,
+ limit: 50,
+ }),
+ )
+ : queryClient.prefetchQuery(
+ trpc.deals.list.queryOptions(dealsSearchParams.toInput(values)),
+ ));
+ void queryClient.prefetchQuery(trpc.users.list.queryOptions());
+ void queryClient.prefetchQuery(
+ trpc.companies.options.queryOptions({ q: "" }),
+ );
+
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Deals</PageShellTitle>
+ <PageShellDescription>
+ The pipeline, and everything that has already closed.
+ </PageShellDescription>
+ </PageShellHeading>
+ <PageShellActions>
+ <DealsViewToggle />
+ <CreateDealSheet />
+ </PageShellActions>
+ </PageShellHeader>
+
+ <PageShellContent>
+ <HydrateClient>
+ <DealsView />
+ </HydrateClient>
+ </PageShellContent>
+ </PageShell>
+ );
+}
diff --git a/apps/app/app/(app)/import/import-panel.tsx b/apps/app/app/(app)/import/import-panel.tsx
new file mode 100644
index 00000000..68daf4ba
--- /dev/null
+++ b/apps/app/app/(app)/import/import-panel.tsx
@@ -0,0 +1,279 @@
+"use client";
+
+import Upload from "@carbon/icons-react/es/Upload";
+import { Button } from "@crm/ui/components/button";
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+} from "@crm/ui/components/card";
+import { Field, FieldDescription, FieldLabel } from "@crm/ui/components/field";
+import { Icon } from "@crm/ui/components/icon";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@crm/ui/components/select";
+import { Separator } from "@crm/ui/components/separator";
+import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
+import { Spinner } from "@crm/ui/components/spinner";
+import {
+ StatusIndicator,
+ type StatusTone,
+} from "@crm/ui/components/status-indicator";
+import { TableCell } from "@crm/ui/components/table";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { parseAsStringLiteral, useQueryState } from "nuqs";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+
+type Report = RouterOutputs["import"]["run"];
+type Outcome = Report["rows"][number]["outcome"];
+
+const KINDS = ["companies", "contacts", "deals"] as const;
+
+const KIND_HELP: Record<(typeof KINDS)[number], string> = {
+ companies:
+ "Matched on domain. Columns: Name, Company Domain Name, Phone, City, Country, Industry.",
+ contacts:
+ "Matched on email. Columns: First Name, Last Name, Email, Phone, Job Title, Associated Company.",
+ deals:
+ "Matched on deal name within a company. Columns: Deal Name, Associated Company, Deal Stage, Amount, Close Date. Import companies first.",
+};
+
+const OUTCOME_TONE: Record<Outcome, StatusTone> = {
+ created: "success",
+ updated: "info",
+ skipped: "neutral",
+ failed: "error",
+};
+
+const UNASSIGNED = "unassigned";
+
+/**
+ * HubSpot CSV import.
+ *
+ * Always dry-runs first. The report is the whole point: a bad column mapping is
+ * invisible until you can see that four hundred rows would be "skipped — no
+ * name and no domain", and by then it has already run.
+ */
+export function ImportPanel() {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ const [kind, setKind] = useQueryState(
+ "kind",
+ parseAsStringLiteral(KINDS).withDefault("companies"),
+ );
+ const [fileName, setFileName] = useState<string | null>(null);
+ const [csv, setCsv] = useState("");
+ const [ownerId, setOwnerId] = useState(UNASSIGNED);
+ const [report, setReport] = useState<Report | null>(null);
+
+ const fileId = useId();
+
+ const users = useQuery(trpc.users.list.queryOptions());
+
+ const run = useMutation(
+ trpc.import.run.mutationOptions({
+ onSuccess: async (result) => {
+ setReport(result);
+ if (result.dryRun) {
+ toast.success("Dry run finished — nothing was written.");
+ return;
+ }
+ // An applied import touches everything.
+ await queryClient.invalidateQueries();
+ toast.success(
+ `Imported: ${result.created} created, ${result.updated} updated.`,
+ );
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const submit = (dryRun: boolean) =>
+ run.mutate({
+ kind,
+ csv,
+ dryRun,
+ defaultOwnerId: ownerId === UNASSIGNED ? null : ownerId,
+ });
+
+ const readFile = async (file: File) => {
+ setFileName(file.name);
+ setCsv(await file.text());
+ // The old report describes the old file.
+ setReport(null);
+ };
+
+ return (
+ <div className="flex flex-col gap-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>File</CardTitle>
+ </CardHeader>
+ <Separator />
+ <CardContent className="flex flex-col gap-4">
+ <Field>
+ <FieldLabel htmlFor="import-kind">What is in it</FieldLabel>
+ <Select
+ value={kind}
+ onValueChange={(next) => {
+ void setKind(next as (typeof KINDS)[number]);
+ setReport(null);
+ }}
+ >
+ <SelectTrigger id="import-kind">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="companies">Companies</SelectItem>
+ <SelectItem value="contacts">Contacts</SelectItem>
+ <SelectItem value="deals">Deals</SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldDescription>{KIND_HELP[kind]}</FieldDescription>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor={fileId}>CSV</FieldLabel>
+ <input
+ id={fileId}
+ type="file"
+ accept=".csv,text/csv"
+ className="text-sm file:mr-3 file:border file:bg-muted file:px-3 file:py-1.5 file:text-xs"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ if (file) void readFile(file);
+ }}
+ />
+ {fileName ? (
+ <FieldDescription>
+ {fileName} · {csv.length.toLocaleString()} characters
+ </FieldDescription>
+ ) : null}
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="import-owner">
+ Owner for rows that do not name one
+ </FieldLabel>
+ <Select value={ownerId} onValueChange={setOwnerId}>
+ <SelectTrigger id="import-owner">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={UNASSIGNED}>Unassigned</SelectItem>
+ {(users.data ?? []).map((user) => (
+ <SelectItem key={user.id} value={user.id}>
+ {user.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {kind === "deals" ? (
+ <FieldDescription>
+ Deals must have an owner, so this one is not optional for them.
+ </FieldDescription>
+ ) : null}
+ </Field>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ size="sm"
+ disabled={run.isPending || csv === ""}
+ onClick={() => submit(true)}
+ >
+ {run.isPending ? <Spinner /> : null}
+ Dry run
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ // Only enabled once a dry run of *this* file has been read.
+ disabled={run.isPending || !report?.dryRun}
+ onClick={() => submit(false)}
+ >
+ <Icon icon={Upload} data-icon="inline-start" />
+ Apply {report ? `${report.created + report.updated} rows` : ""}
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+
+ {report ? <ImportReportCard report={report} /> : null}
+ </div>
+ );
+}
+
+const REPORT_COLUMNS = [
+ { header: "Row", width: "w-[10%]", align: "right" as const },
+ { header: "Outcome", width: "w-[18%]" },
+ { header: "Record", width: "w-[34%]" },
+ { header: "Why", width: "w-[38%]" },
+];
+
+function ImportReportCard({ report }: { report: Report }) {
+ // The ones that need a decision come first; a thousand clean "created" rows
+ // are not what anyone is scanning for.
+ const rows = [...report.rows].sort((a, b) => {
+ const rank = (outcome: Outcome) =>
+ outcome === "failed" ? 0 : outcome === "skipped" ? 1 : 2;
+ return rank(a.outcome) - rank(b.outcome) || a.line - b.line;
+ });
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{report.dryRun ? "Dry run" : "Imported"}</CardTitle>
+ <CardAction>
+ <span className="flex flex-wrap items-center gap-4 text-xs">
+ <StatusIndicator
+ tone="success"
+ label={`${report.created} created`}
+ />
+ <StatusIndicator tone="info" label={`${report.updated} updated`} />
+ {report.skipped > 0 ? (
+ <StatusIndicator
+ tone="neutral"
+ label={`${report.skipped} skipped`}
+ />
+ ) : null}
+ {report.failed > 0 ? (
+ <StatusIndicator tone="error" label={`${report.failed} failed`} />
+ ) : null}
+ </span>
+ </CardAction>
+ </CardHeader>
+
+ <SimpleTable columns={REPORT_COLUMNS}>
+ {rows.map((row) => (
+ <SimpleTableRow key={row.line}>
+ <TableCell className="px-3 py-2 text-right tabular-nums text-muted-foreground">
+ {row.line}
+ </TableCell>
+ <TableCell className="px-3 py-2 capitalize">
+ <StatusIndicator
+ tone={OUTCOME_TONE[row.outcome]}
+ label={row.outcome}
+ />
+ </TableCell>
+ <TableCell className="truncate px-3 py-2">
+ {row.label ?? row.key ?? "—"}
+ </TableCell>
+ <TableCell className="truncate px-3 py-2 text-muted-foreground">
+ {row.reason ?? ""}
+ </TableCell>
+ </SimpleTableRow>
+ ))}
+ </SimpleTable>
+ </Card>
+ );
+}
diff --git a/apps/app/app/(app)/import/page.tsx b/apps/app/app/(app)/import/page.tsx
new file mode 100644
index 00000000..2fff8a84
--- /dev/null
+++ b/apps/app/app/(app)/import/page.tsx
@@ -0,0 +1,46 @@
+import type { Metadata } from "next";
+import {
+ PageShell,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { ImportPanel } from "./import-panel";
+
+export const metadata: Metadata = {
+ title: "Import",
+};
+
+export default async function ImportPage() {
+ await requireSession();
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ void queryClient.prefetchQuery(trpc.users.list.queryOptions());
+
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Import from HubSpot</PageShellTitle>
+ <PageShellDescription>
+ Export a list from HubSpot and drop the CSV here. Companies match on
+ domain and contacts on email, so re-running an import updates rather
+ than duplicates.
+ </PageShellDescription>
+ </PageShellHeading>
+ </PageShellHeader>
+
+ <PageShellContent>
+ <HydrateClient>
+ <ImportPanel />
+ </HydrateClient>
+ </PageShellContent>
+ </PageShell>
+ );
+}
diff --git a/apps/app/app/(app)/layout.tsx b/apps/app/app/(app)/layout.tsx
new file mode 100644
index 00000000..f6679607
--- /dev/null
+++ b/apps/app/app/(app)/layout.tsx
@@ -0,0 +1,47 @@
+import { AppHeader } from "@/components/app-header";
+import { AppIconRail } from "@/components/app-icon-rail";
+import { QuickSwitcher } from "@/components/crm/quick-switcher";
+import { RecordSheetHost } from "@/components/crm/record-sheet/record-sheet-host";
+import { MobileNavProvider } from "@/components/mobile-nav";
+import { requireSession } from "@/lib/session";
+
+export default async function AppLayout({
+ children,
+}: Readonly<{
+ children: React.ReactNode;
+}>) {
+ const { user } = await requireSession();
+
+ return (
+ <MobileNavProvider>
+ <div className="isolate flex h-svh flex-col">
+ <AppHeader
+ user={{
+ name: user.name,
+ email: user.email,
+ image: user.image ?? null,
+ }}
+ />
+ {/*
+ * No scroll container here: <PageShell> renders the scrolling
+ * <main>, so the page can own its own transition snapshot while
+ * the header and rail stay put.
+ */}
+ <div className="flex min-h-0 flex-1">
+ <AppIconRail />
+ {children}
+ </div>
+
+ {/*
+ * Records open over whatever list you were on rather than as pages of
+ * their own, so the sheet lives in the shell — one instance, driven
+ * by `?record=`, reachable from every row, card and search hit.
+ */}
+ <RecordSheetHost />
+
+ {/* ⌘K from anywhere inside the app shell. */}
+ <QuickSwitcher />
+ </div>
+ </MobileNavProvider>
+ );
+}
diff --git a/apps/app/app/(app)/overview-greeting.tsx b/apps/app/app/(app)/overview-greeting.tsx
new file mode 100644
index 00000000..c6b62e05
--- /dev/null
+++ b/apps/app/app/(app)/overview-greeting.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { useSuspenseQuery } from "@tanstack/react-query";
+import { PageShellDescription, PageShellTitle } from "@/components/page-shell";
+import { useTRPC } from "@/lib/trpc/client";
+
+/**
+ * Reads the signed-in user from the API rather than the session cookie, so a
+ * renamed account is right on the next load instead of the next sign-in.
+ *
+ * `useSuspenseQuery` because the page awaits the prefetch: the data is already
+ * in the cache by the time this renders, and the alternative is an
+ * `undefined` branch that can never actually be taken.
+ */
+export function OverviewGreeting() {
+ const trpc = useTRPC();
+ const { data: me } = useSuspenseQuery(trpc.users.me.queryOptions());
+
+ return (
+ <>
+ <PageShellTitle>Welcome back, {me.name.split(" ")[0]}</PageShellTitle>
+ <PageShellDescription>Welcome to the Comp AI CRM.</PageShellDescription>
+ </>
+ );
+}
diff --git a/apps/app/app/(app)/page.tsx b/apps/app/app/(app)/page.tsx
new file mode 100644
index 00000000..e5b12dc9
--- /dev/null
+++ b/apps/app/app/(app)/page.tsx
@@ -0,0 +1,41 @@
+import {
+ PageShell,
+ PageShellContent,
+ PageShellHeader,
+ PageShellHeading,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { DashboardSummary } from "./dashboard-summary";
+import { OverviewGreeting } from "./overview-greeting";
+
+export default async function OverviewPage() {
+ await requireSession();
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ // The greeting is awaited — it is one line of text, and a skeleton that
+ // flashes for the length of one API call is worse than rendering a beat
+ // later. The summary streams in behind it.
+ await queryClient.prefetchQuery(trpc.users.me.queryOptions());
+ await queryClient.prefetchQuery(trpc.dashboard.summary.queryOptions());
+
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <HydrateClient>
+ <OverviewGreeting />
+ </HydrateClient>
+ </PageShellHeading>
+ </PageShellHeader>
+
+ <PageShellContent>
+ <HydrateClient>
+ <DashboardSummary />
+ </HydrateClient>
+ </PageShellContent>
+ </PageShell>
+ );
+}
diff --git a/apps/app/app/(auth)/sign-in/google-sign-in.tsx b/apps/app/app/(auth)/sign-in/google-sign-in.tsx
new file mode 100644
index 00000000..780bef0e
--- /dev/null
+++ b/apps/app/app/(auth)/sign-in/google-sign-in.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import { signIn } from "@crm/auth/client";
+import GoogleLogo from "@crm/ui/components/brand-logos/google";
+import { Button } from "@crm/ui/components/button";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useState } from "react";
+import { toast } from "sonner";
+
+export function GoogleSignIn() {
+ const [pending, setPending] = useState(false);
+
+ async function handleClick() {
+ setPending(true);
+
+ // The API owns /api/auth/*, so both URLs have to be absolute — a relative
+ // one would resolve against the API's origin, not this app's. Better Auth
+ // checks them against AUTH_TRUSTED_ORIGINS.
+ const origin = window.location.origin;
+
+ const { error } = await signIn.social({
+ provider: "google",
+ callbackURL: `${origin}/`,
+ errorCallbackURL: `${origin}/sign-in`,
+ });
+
+ // On success the client has already navigated to Google.
+ if (error) {
+ toast.error(error.message ?? "Could not reach the sign-in service.");
+ setPending(false);
+ }
+ }
+
+ return (
+ <Button
+ className="w-full"
+ disabled={pending}
+ onClick={handleClick}
+ type="button"
+ variant="outline"
+ >
+ {pending ? (
+ <Spinner data-icon="inline-start" />
+ ) : (
+ <GoogleLogo data-icon="inline-start" className="size-4" />
+ )}
+ Continue with Google
+ </Button>
+ );
+}
diff --git a/apps/app/app/(auth)/sign-in/page.tsx b/apps/app/app/(auth)/sign-in/page.tsx
new file mode 100644
index 00000000..9fa27908
--- /dev/null
+++ b/apps/app/app/(auth)/sign-in/page.tsx
@@ -0,0 +1,44 @@
+import type { Metadata } from "next";
+import { redirect } from "next/navigation";
+import { AuthHeading, AuthShell } from "@/components/auth-shell";
+import { getSession } from "@/lib/session";
+import { GoogleSignIn } from "./google-sign-in";
+
+export const metadata: Metadata = {
+ title: "Sign in",
+};
+
+export default async function SignInPage() {
+ // The authoritative counterpart to the cookie sniff in `proxy.ts`, and the
+ // reason that check is not in the proxy: only a session that verifies
+ // against Postgres sends you back into the app. A cookie that no longer
+ // resolves falls through to the form instead of ping-ponging with `/`.
+ //
+ // A database that cannot answer must not take this page down with it — it is
+ // the one page that has to work when everything else is broken, so a failed
+ // lookup counts as signed out.
+ const session = await getSession().catch((error: unknown) => {
+ console.error("Sign-in: could not read the session.", error);
+ return null;
+ });
+
+ if (session) {
+ redirect("/");
+ }
+
+ return (
+ <AuthShell>
+ <AuthHeading
+ title="Welcome back"
+ description="Sign in with your Comp AI Google account to continue."
+ />
+
+ <GoogleSignIn />
+
+ <p className="text-center text-muted-foreground text-sm/5">
+ Comp AI CRM is internal. If you cannot get in, ask an admin to check
+ your Google account.
+ </p>
+ </AuthShell>
+ );
+}
diff --git a/apps/app/app/api/[...path]/route.ts b/apps/app/app/api/[...path]/route.ts
new file mode 100644
index 00000000..5dc69fbb
--- /dev/null
+++ b/apps/app/app/api/[...path]/route.ts
@@ -0,0 +1,116 @@
+import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
+import { API_URL } from "@/lib/env";
+
+/**
+ * Same-origin passthrough to the NestJS API.
+ *
+ * Without it every tRPC call from the browser would be a cross-origin,
+ * credentialed request: CORS preflights, `SameSite` cookie rules and third-party
+ * cookie blocking all become problems the moment the app and the API are not on
+ * the same host. Forwarding through the app makes `/api/trpc` look local, and
+ * the session cookie just works.
+ */
+
+/**
+ * `undici` transparently decompresses some responses and not others, so the
+ * bytes we hold may or may not still be encoded. Try to decode; if it throws,
+ * they were already plain.
+ */
+function decode(buf: Buffer, encoding: string | null): Buffer {
+ const enc = (encoding ?? "").toLowerCase();
+ try {
+ if (enc.includes("br")) return brotliDecompressSync(buf);
+ if (enc.includes("gzip")) return gunzipSync(buf);
+ if (enc.includes("deflate")) return inflateSync(buf);
+ } catch {
+ // Already decompressed upstream.
+ }
+ return buf;
+}
+
+async function handler(request: Request): Promise<Response> {
+ const url = new URL(request.url);
+ const target = `${API_URL}${url.pathname}${url.search}`;
+
+ const headers = new Headers(request.headers);
+ // Hop-by-hop and origin-describing headers belong to the browser→app hop,
+ // not the app→API one. Leaving them on makes the API think it is behind a
+ // proxy it is not, and re-sending `content-length` after we have touched the
+ // body is a truncated request.
+ for (const header of [
+ "host",
+ "x-forwarded-host",
+ "x-forwarded-proto",
+ "x-forwarded-for",
+ "forwarded",
+ "transfer-encoding",
+ "connection",
+ "keep-alive",
+ "content-length",
+ "expect",
+ ]) {
+ headers.delete(header);
+ }
+
+ const init: RequestInit & { duplex?: "half" } = {
+ method: request.method,
+ headers,
+ redirect: "manual",
+ };
+
+ if (request.method !== "GET" && request.method !== "HEAD") {
+ init.body = request.body;
+ init.duplex = "half";
+ }
+
+ const upstream = await fetch(target, init);
+
+ const responseHeaders = new Headers(upstream.headers);
+ for (const header of [
+ "transfer-encoding",
+ "connection",
+ "content-encoding",
+ "content-length",
+ ]) {
+ responseHeaders.delete(header);
+ }
+
+ // `Headers` folds repeated values into one comma-joined string, which mangles
+ // cookies. `getSetCookie()` is the only way to keep them separate.
+ const setCookies = upstream.headers.getSetCookie?.() ?? [];
+ if (setCookies.length > 0) {
+ responseHeaders.delete("set-cookie");
+ for (const cookie of setCookies) {
+ responseHeaders.append("set-cookie", cookie);
+ }
+ }
+
+ // Streams pass straight through — buffering an SSE response would hold it
+ // open forever and deliver nothing.
+ if (upstream.headers.get("content-type")?.includes("text/event-stream")) {
+ return new Response(upstream.body, {
+ status: upstream.status,
+ statusText: upstream.statusText,
+ headers: responseHeaders,
+ });
+ }
+
+ const raw = Buffer.from(await upstream.arrayBuffer());
+ const body = decode(raw, upstream.headers.get("content-encoding"));
+
+ return new Response(new Uint8Array(body), {
+ status: upstream.status,
+ statusText: upstream.statusText,
+ headers: responseHeaders,
+ });
+}
+
+export {
+ handler as DELETE,
+ handler as GET,
+ handler as HEAD,
+ handler as OPTIONS,
+ handler as PATCH,
+ handler as POST,
+ handler as PUT,
+};
diff --git a/apps/app/app/favicon.ico b/apps/app/app/favicon.ico
new file mode 100644
index 00000000..712b9754
Binary files /dev/null and b/apps/app/app/favicon.ico differ
diff --git a/apps/app/app/layout.tsx b/apps/app/app/layout.tsx
new file mode 100644
index 00000000..5e8d23b9
--- /dev/null
+++ b/apps/app/app/layout.tsx
@@ -0,0 +1,64 @@
+import "@crm/ui/globals.css";
+import { Toaster } from "@crm/ui/components/sonner";
+import { TooltipProvider } from "@crm/ui/components/tooltip";
+import { cn } from "@crm/ui/lib/utils";
+import type { Metadata } from "next";
+import { Geist, Geist_Mono } from "next/font/google";
+import { NuqsAdapter } from "nuqs/adapters/next/app";
+import { ThemeProvider } from "@/components/theme-provider";
+import { TRPCReactProvider } from "@/lib/trpc/client";
+
+// --font-geist-sans / --font-geist-mono are the variables @crm/ui's theme reads
+// (see the @theme block in globals.css), so the design system picks these up.
+const fontSans = Geist({
+ variable: "--font-geist-sans",
+ subsets: ["latin"],
+});
+
+const fontMono = Geist_Mono({
+ variable: "--font-geist-mono",
+ subsets: ["latin"],
+});
+
+export const metadata: Metadata = {
+ title: {
+ default: "Comp AI - CRM",
+ template: "%s · Comp AI CRM",
+ },
+ description: "Customer Relationship Management for Comp AI",
+ // app/favicon.ico is picked up by Next's file convention and covers the
+ // legacy /favicon.ico request on its own; these are the modern additions.
+ icons: {
+ icon: [
+ { url: "/favicon.svg", type: "image/svg+xml" },
+ { url: "/favicon-96x96.png", type: "image/png", sizes: "96x96" },
+ ],
+ apple: "/apple-touch-icon.png",
+ },
+ manifest: "/site.webmanifest",
+};
+
+export default function RootLayout({
+ children,
+}: Readonly<{
+ children: React.ReactNode;
+}>) {
+ return (
+ <html
+ lang="en"
+ suppressHydrationWarning
+ className={cn(fontSans.variable, fontMono.variable, "h-full antialiased")}
+ >
+ <body className="flex min-h-full flex-col font-sans">
+ <NuqsAdapter>
+ <TRPCReactProvider>
+ <ThemeProvider>
+ <TooltipProvider>{children}</TooltipProvider>
+ <Toaster richColors />
+ </ThemeProvider>
+ </TRPCReactProvider>
+ </NuqsAdapter>
+ </body>
+ </html>
+ );
+}
diff --git a/apps/app/components.json b/apps/app/components.json
new file mode 100644
index 00000000..8797f475
--- /dev/null
+++ b/apps/app/components.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://ui.shadcn.com/schema.json",
+ "style": "radix-nova",
+ "rsc": true,
+ "tsx": true,
+ "tailwind": {
+ "config": "",
+ "css": "../../packages/ui/src/styles/globals.css",
+ "baseColor": "neutral",
+ "cssVariables": true
+ },
+ "iconLibrary": "lucide",
+ "aliases": {
+ "components": "@/components",
+ "hooks": "@/hooks",
+ "lib": "@/lib",
+ "utils": "@crm/ui/lib/utils",
+ "ui": "@crm/ui/components"
+ },
+ "rtl": false,
+ "menuColor": "default",
+ "menuAccent": "subtle"
+}
diff --git a/apps/app/components/app-header.tsx b/apps/app/components/app-header.tsx
new file mode 100644
index 00000000..787bf6ea
--- /dev/null
+++ b/apps/app/components/app-header.tsx
@@ -0,0 +1,139 @@
+"use client";
+
+import Asleep from "@carbon/icons-react/es/Asleep";
+import Light from "@carbon/icons-react/es/Light";
+import Logout from "@carbon/icons-react/es/Logout";
+import Menu from "@carbon/icons-react/es/Menu";
+import UserAvatar from "@carbon/icons-react/es/UserAvatar";
+import { signOut } from "@crm/auth/client";
+import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";
+import { Button } from "@crm/ui/components/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@crm/ui/components/dropdown-menu";
+import Logo from "@crm/ui/components/logo";
+import { Separator } from "@crm/ui/components/separator";
+import Link from "next/link";
+import { useTheme } from "next-themes";
+import { toast } from "sonner";
+import { useMobileNav } from "@/components/mobile-nav";
+
+type User = { name: string; email: string; image: string | null };
+
+export function AppHeader({ user }: { user: User }) {
+ const { setOpen: setMobileNavOpen } = useMobileNav();
+
+ async function handleSignOut() {
+ const { error } = await signOut();
+
+ if (error) {
+ toast.error(error.message ?? "Could not sign out.");
+ return;
+ }
+
+ // A full navigation rather than router.push: the session cookie is gone,
+ // so every cached server render has to be thrown away and `proxy.ts`
+ // re-evaluated from scratch.
+ window.location.assign("/sign-in");
+ }
+
+ // h-12 rather than mvp's h-14. mvp fills its bar with h-8 controls (org
+ // switcher, search, credits), so 56px reads tight there; this bar holds only
+ // a logo, a label and an avatar, so the same 56px reads empty.
+ return (
+ <header className="flex h-12 shrink-0 items-center gap-2 border-b px-3 [view-transition-name:app-header]">
+ <div className="flex shrink-0 items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="md:hidden"
+ aria-label="Open navigation"
+ onClick={() => setMobileNavOpen(true)}
+ >
+ <Menu />
+ </Button>
+ <Link
+ href="/"
+ aria-label="Homepage"
+ className="hidden size-8 items-center justify-center text-primary md:flex"
+ >
+ <Logo className="size-5" />
+ </Link>
+ <Separator orientation="vertical" className="mx-1 h-5 bg-transparent" />
+ <span className="font-medium text-sm">Comp AI CRM</span>
+ </div>
+
+ <div className="ml-auto flex shrink-0 items-center gap-1.5">
+ <UserMenu
+ user={user}
+ onSignOut={() => {
+ handleSignOut().catch(() => toast.error("Could not sign out."));
+ }}
+ />
+ </div>
+ </header>
+ );
+}
+
+function UserMenu({ user, onSignOut }: { user: User; onSignOut: () => void }) {
+ const { resolvedTheme, setTheme } = useTheme();
+ const isDark = resolvedTheme === "dark";
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label="Account menu"
+ className="hover:bg-transparent aria-expanded:bg-transparent dark:hover:bg-transparent"
+ >
+ <Avatar className="size-7">
+ {user.image && <AvatarImage alt={user.name} src={user.image} />}
+ <AvatarFallback className="text-xs">
+ {initials(user.name)}
+ </AvatarFallback>
+ </Avatar>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-56">
+ <DropdownMenuLabel className="flex items-center gap-2">
+ <UserAvatar />
+ <span className="min-w-0 truncate">{user.email}</span>
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ setTheme(isDark ? "light" : "dark");
+ }}
+ >
+ {isDark ? <Light /> : <Asleep />}
+ {isDark ? "Light mode" : "Dark mode"}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={onSignOut}>
+ <Logout />
+ Sign out
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function initials(name: string): string {
+ return (
+ name
+ .split(" ")
+ .map((part) => part[0])
+ .filter(Boolean)
+ .slice(0, 2)
+ .join("")
+ .toUpperCase() || "?"
+ );
+}
diff --git a/apps/app/components/app-icon-rail.tsx b/apps/app/components/app-icon-rail.tsx
new file mode 100644
index 00000000..bc47beaa
--- /dev/null
+++ b/apps/app/components/app-icon-rail.tsx
@@ -0,0 +1,152 @@
+"use client";
+
+import Building from "@carbon/icons-react/es/Building";
+import type { CarbonIconType } from "@carbon/icons-react/es/CarbonIcon";
+import Dashboard from "@carbon/icons-react/es/Dashboard";
+import Partnership from "@carbon/icons-react/es/Partnership";
+import Upload from "@carbon/icons-react/es/Upload";
+import UserMultiple from "@carbon/icons-react/es/UserMultiple";
+import { Button } from "@crm/ui/components/button";
+import { Icon } from "@crm/ui/components/icon";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from "@crm/ui/components/sheet";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@crm/ui/components/tooltip";
+import { cn } from "@crm/ui/lib/utils";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { useMobileNav } from "@/components/mobile-nav";
+
+type RailItem = {
+ title: string;
+ href: string;
+ icon: CarbonIconType;
+ match: "exact" | "prefix";
+};
+
+const ITEMS: RailItem[] = [
+ { title: "Overview", href: "/", icon: Dashboard, match: "exact" },
+ { title: "Companies", href: "/companies", icon: Building, match: "prefix" },
+ {
+ title: "Contacts",
+ href: "/contacts",
+ icon: UserMultiple,
+ match: "prefix",
+ },
+ { title: "Deals", href: "/deals", icon: Partnership, match: "prefix" },
+ { title: "Import", href: "/import", icon: Upload, match: "prefix" },
+];
+
+function isActive(item: RailItem, pathname: string): boolean {
+ return (
+ pathname === item.href ||
+ (item.match === "prefix" && pathname.startsWith(item.href))
+ );
+}
+
+function RailLink({ item, active }: { item: RailItem; active: boolean }) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ asChild
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "text-muted-foreground",
+ active &&
+ "bg-primary/10 text-primary hover:bg-primary/10 hover:text-primary",
+ )}
+ >
+ <Link
+ href={item.href}
+ aria-current={active ? "page" : undefined}
+ transitionTypes={["nav-lateral"]}
+ >
+ <Icon icon={item.icon} />
+ <span className="sr-only">{item.title}</span>
+ </Link>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="right">{item.title}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+function MobileRailLink({
+ item,
+ active,
+ onNavigate,
+}: {
+ item: RailItem;
+ active: boolean;
+ onNavigate: () => void;
+}) {
+ return (
+ <Button
+ asChild
+ variant="ghost"
+ className={cn(
+ "justify-start gap-3 text-muted-foreground",
+ active &&
+ "bg-primary/10 text-primary hover:bg-primary/10 hover:text-primary",
+ )}
+ >
+ <Link
+ href={item.href}
+ aria-current={active ? "page" : undefined}
+ onClick={onNavigate}
+ >
+ <Icon icon={item.icon} />
+ <span>{item.title}</span>
+ </Link>
+ </Button>
+ );
+}
+
+export function AppIconRail() {
+ const pathname = usePathname();
+ const { open, setOpen } = useMobileNav();
+
+ return (
+ <>
+ <nav
+ aria-label="Primary"
+ className="hidden w-14 shrink-0 flex-col items-center gap-1 border-r py-3 md:flex [view-transition-name:app-rail]"
+ >
+ {ITEMS.map((item) => (
+ <RailLink
+ key={item.href}
+ item={item}
+ active={isActive(item, pathname)}
+ />
+ ))}
+ </nav>
+
+ <Sheet open={open} onOpenChange={setOpen}>
+ <SheetContent side="left" className="w-64 gap-0 p-0">
+ <SheetHeader>
+ <SheetTitle>Navigation</SheetTitle>
+ </SheetHeader>
+ <nav aria-label="Primary" className="flex flex-1 flex-col gap-1 p-2">
+ {ITEMS.map((item) => (
+ <MobileRailLink
+ key={item.href}
+ item={item}
+ active={isActive(item, pathname)}
+ onNavigate={() => setOpen(false)}
+ />
+ ))}
+ </nav>
+ </SheetContent>
+ </Sheet>
+ </>
+ );
+}
diff --git a/apps/app/components/auth-shader.tsx b/apps/app/components/auth-shader.tsx
new file mode 100644
index 00000000..e0d7b5d7
--- /dev/null
+++ b/apps/app/components/auth-shader.tsx
@@ -0,0 +1,15 @@
+export function AuthShader() {
+ return (
+ <>
+ <div
+ aria-hidden="true"
+ className="absolute inset-0 size-full opacity-60 bg-[radial-gradient(circle_at_20%_20%,#2e2e2e,transparent_55%),radial-gradient(circle_at_80%_0%,#1a1a1a,transparent_50%),radial-gradient(circle_at_60%_90%,#ededed_0%,transparent_40%),linear-gradient(#000000,#000000)]"
+ />
+ <div
+ aria-hidden="true"
+ className="absolute inset-0 opacity-[0.5] mix-blend-overlay bg-[url('data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22120%22 height=%22120%22><filter id=%22n%22><feTurbulence type=%22fractalNoise%22 baseFrequency=%220.85%22 numOctaves=%222%22/></filter><rect width=%22100%25%22 height=%22100%25%22 filter=%22url(%23n)%22/></svg>')]"
+ />
+ <div aria-hidden="true" className="absolute inset-0 bg-background/70" />
+ </>
+ );
+}
diff --git a/apps/app/components/auth-shell.tsx b/apps/app/components/auth-shell.tsx
new file mode 100644
index 00000000..a42f6541
--- /dev/null
+++ b/apps/app/components/auth-shell.tsx
@@ -0,0 +1,69 @@
+import Logo from "@crm/ui/components/logo";
+import Link from "next/link";
+import type { ReactNode } from "react";
+import { AuthShader } from "@/components/auth-shader";
+
+export function AuthShell({ children }: { children: ReactNode }) {
+ return (
+ <main className="dark grid min-h-svh bg-background text-foreground lg:grid-cols-[minmax(0,1fr)_minmax(420px,520px)]">
+ <section className="relative hidden min-h-svh overflow-hidden bg-muted p-8 lg:flex lg:flex-col lg:justify-between xl:p-12">
+ <AuthShader />
+
+ <div className="relative flex gap-2 text-sm/5">
+ <Link href="/" aria-label="Homepage" className="flex">
+ <Logo className="size-5 shrink-0" />
+ </Link>
+ </div>
+
+ <div className="relative flex max-w-lg flex-col gap-8">
+ <div className="flex flex-col gap-4">
+ <p className="font-mono text-xs/4 text-muted-foreground uppercase">
+ Internal tool
+ </p>
+ <h1 className="max-w-[14ch] text-5xl/14 font-semibold text-balance">
+ Every customer, in one place.
+ </h1>
+ </div>
+ </div>
+
+ <p className="relative font-mono text-xs/4 text-muted-foreground">
+ Comp AI · staff access only
+ </p>
+ </section>
+
+ <section className="flex min-h-svh flex-col bg-background px-6 py-8 sm:px-10 lg:px-14">
+ <div className="flex gap-2 text-sm/5 max-lg:hidden lg:invisible">
+ <Logo className="size-5 shrink-0" />
+ </div>
+
+ <div className="flex flex-1 items-center justify-center py-12">
+ <div className="flex w-full max-w-sm flex-col gap-8">{children}</div>
+ </div>
+ </section>
+ </main>
+ );
+}
+
+export function AuthHeading({
+ title,
+ description,
+}: {
+ title: string;
+ description: ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-3 text-left">
+ <Link href="/" aria-label="Homepage" className="flex">
+ <Logo className="size-6 shrink-0" />
+ </Link>
+ <div className="flex flex-col gap-1">
+ <h2 className="text-2xl/8 font-semibold tracking-tight text-balance">
+ {title}
+ </h2>
+ <p className="max-w-[32ch] text-sm/5 text-muted-foreground text-pretty">
+ {description}
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/app/components/crm/closing-window.ts b/apps/app/components/crm/closing-window.ts
new file mode 100644
index 00000000..9c1ee2f3
--- /dev/null
+++ b/apps/app/components/crm/closing-window.ts
@@ -0,0 +1,13 @@
+/**
+ * Buckets for the "closing" facet, in the order a rep would scan them.
+ *
+ * Kept in step with `CLOSING_WINDOWS` in `apps/api/src/deals/deals.contracts.ts`
+ * — the API owns which dates fall in which bucket; this is only the labels.
+ */
+export const CLOSING_OPTIONS = [
+ { value: "overdue", label: "Overdue" },
+ { value: "this-month", label: "Closing this month" },
+ { value: "next-month", label: "Closing next month" },
+ { value: "later", label: "Later" },
+ { value: "none", label: "No close date" },
+] as const;
diff --git a/apps/app/components/crm/company-cell.tsx b/apps/app/components/crm/company-cell.tsx
new file mode 100644
index 00000000..a53b3fd6
--- /dev/null
+++ b/apps/app/components/crm/company-cell.tsx
@@ -0,0 +1,26 @@
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { EntityLogo } from "@crm/ui/components/entity-logo";
+
+export type CompanyRef = {
+ id: string;
+ name: string;
+ domain: string | null;
+ iconUrl: string | null;
+ logoUrl?: string | null;
+};
+
+/** A company where it appears inside another record's row. */
+export function CompanyCell({ company }: { company: CompanyRef | null }) {
+ if (!company) return <EmptyCellValue />;
+
+ return (
+ <span className="flex min-w-0 items-center gap-2">
+ <EntityLogo
+ src={company.iconUrl ?? company.logoUrl}
+ name={company.name}
+ size="sm"
+ />
+ <span className="truncate">{company.name}</span>
+ </span>
+ );
+}
diff --git a/apps/app/components/crm/company-socials.tsx b/apps/app/components/crm/company-socials.tsx
new file mode 100644
index 00000000..e401f6bc
--- /dev/null
+++ b/apps/app/components/crm/company-socials.tsx
@@ -0,0 +1,68 @@
+import Launch from "@carbon/icons-react/es/Launch";
+import LogoGithub from "@carbon/icons-react/es/LogoGithub";
+import LogoLinkedin from "@carbon/icons-react/es/LogoLinkedin";
+import LogoX from "@carbon/icons-react/es/LogoX";
+import Money from "@carbon/icons-react/es/Money";
+import UserMultiple from "@carbon/icons-react/es/UserMultiple";
+import { Button } from "@crm/ui/components/button";
+import type { CarbonIcon } from "@crm/ui/components/icon";
+import { Icon } from "@crm/ui/components/icon";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@crm/ui/components/tooltip";
+
+type Link = { label: string; href: string | null; icon: CarbonIcon };
+
+/**
+ * Everywhere else this company exists, as found by the agent.
+ *
+ * Renders nothing until there is something to render — an empty row of
+ * placeholder icons says "broken", not "not enriched yet".
+ */
+export function CompanySocials({
+ company,
+}: {
+ company: {
+ website: string | null;
+ linkedinUrl: string | null;
+ twitterUrl: string | null;
+ githubUrl: string | null;
+ pricingUrl: string | null;
+ careersUrl: string | null;
+ };
+}) {
+ const links: Link[] = [
+ { label: "Website", href: company.website, icon: Launch },
+ { label: "LinkedIn", href: company.linkedinUrl, icon: LogoLinkedin },
+ { label: "X", href: company.twitterUrl, icon: LogoX },
+ { label: "GitHub", href: company.githubUrl, icon: LogoGithub },
+ { label: "Pricing", href: company.pricingUrl, icon: Money },
+ { label: "Careers", href: company.careersUrl, icon: UserMultiple },
+ ];
+
+ const present = links.filter(
+ (link): link is Link & { href: string } => link.href !== null,
+ );
+
+ if (present.length === 0) return null;
+
+ return (
+ <div className="flex flex-wrap items-center gap-1">
+ {present.map((link) => (
+ <Tooltip key={link.label}>
+ <TooltipTrigger asChild>
+ <Button asChild variant="ghost" size="icon-sm">
+ <a href={link.href} target="_blank" rel="noreferrer noopener">
+ <Icon icon={link.icon} />
+ <span className="sr-only">{link.label}</span>
+ </a>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{link.label}</TooltipContent>
+ </Tooltip>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/app/components/crm/deal-stage.tsx b/apps/app/components/crm/deal-stage.tsx
new file mode 100644
index 00000000..b91354d5
--- /dev/null
+++ b/apps/app/components/crm/deal-stage.tsx
@@ -0,0 +1,68 @@
+// `@crm/db/enums` and not `@crm/db`: the package root exports the Prisma client
+// instance, so a value import of an enum drags `pg` — and its `node:dns`
+// dependency — into the browser bundle. The generated enums module is a
+// standalone file of string constants.
+import { DealStage } from "@crm/db/enums";
+import {
+ StatusIndicator,
+ type StatusTone,
+} from "@crm/ui/components/status-indicator";
+
+/**
+ * Stage presentation, in pipeline order.
+ *
+ * `UNQUALIFIED_TO_BUY` sits with the other closed stages rather than between
+ * "qualified" and "decision maker bought in": it is a disqualification, so
+ * showing it mid-funnel would suggest a deal is progressing when it is over.
+ */
+const ORDER = [
+ DealStage.DEMO_BOOKED,
+ DealStage.QUALIFIED_TO_BUY,
+ DealStage.DECISION_MAKER_BOUGHT_IN,
+ DealStage.CONTRACT_SENT,
+ DealStage.CLOSED_WON,
+ DealStage.CLOSED_LOST,
+ DealStage.UNQUALIFIED_TO_BUY,
+] as const;
+
+const PRESENTATION: Record<DealStage, { label: string; tone: StatusTone }> = {
+ DEMO_BOOKED: { label: "Demo booked", tone: "neutral" },
+ QUALIFIED_TO_BUY: { label: "Qualified to buy", tone: "info" },
+ DECISION_MAKER_BOUGHT_IN: { label: "Decision maker in", tone: "info" },
+ CONTRACT_SENT: { label: "Contract sent", tone: "warning" },
+ CLOSED_WON: { label: "Closed won", tone: "success" },
+ CLOSED_LOST: { label: "Closed lost", tone: "error" },
+ UNQUALIFIED_TO_BUY: { label: "Unqualified", tone: "neutral" },
+};
+
+/** Stages a deal can still be won from — the pipeline. */
+export const OPEN_STAGES = ORDER.slice(0, 4) as readonly DealStage[];
+
+/** Stages a deal is finished in. */
+export const CLOSED_STAGES = ORDER.slice(4) as readonly DealStage[];
+
+/** The two the API refuses without a `closedReason`. */
+export const LOSING_STAGES: readonly DealStage[] = [
+ DealStage.CLOSED_LOST,
+ DealStage.UNQUALIFIED_TO_BUY,
+];
+
+export const DEAL_STAGE_OPTIONS = ORDER.map((value) => ({
+ value,
+ label: PRESENTATION[value].label,
+}));
+
+export function dealStageLabel(stage: DealStage): string {
+ return PRESENTATION[stage].label;
+}
+
+export function DealStageIndicator({
+ stage,
+ className,
+}: {
+ stage: DealStage;
+ className?: string;
+}) {
+ const { label, tone } = PRESENTATION[stage];
+ return <StatusIndicator tone={tone} label={label} className={className} />;
+}
diff --git a/apps/app/components/crm/enrichment-actions.tsx b/apps/app/components/crm/enrichment-actions.tsx
new file mode 100644
index 00000000..22894be9
--- /dev/null
+++ b/apps/app/components/crm/enrichment-actions.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import MagicWand from "@carbon/icons-react/es/MagicWand";
+import Renew from "@carbon/icons-react/es/Renew";
+import { Button } from "@crm/ui/components/button";
+import { Icon } from "@crm/ui/components/icon";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { useTRPC } from "@/lib/trpc/client";
+
+/**
+ * The two things a rep can ask the agent for.
+ *
+ * Both are background work with no immediate result to show, so neither
+ * navigates or blocks: the enrichment chip in the header goes to "Enriching"
+ * and the page polls until it settles, and the brief appears on the timeline.
+ */
+export function EnrichmentActions({
+ companyId,
+ hasDomain,
+}: {
+ companyId: string;
+ hasDomain: boolean;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ const invalidateCompany = () =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey({ id: companyId }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.list.queryKey(),
+ }),
+ ]);
+
+ const enrich = useMutation(
+ trpc.companies.enrich.mutationOptions({
+ onSuccess: async (result) => {
+ await invalidateCompany();
+ toast.success(
+ result.queued
+ ? "Looking it up — this page will update when it finishes."
+ : "Already running.",
+ );
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const research = useMutation(
+ trpc.companies.research.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.timeline.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.timelineCounts.queryKey(),
+ }),
+ ]);
+ toast.success("Brief added to the timeline.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ return (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ // Without a domain there is nothing to look up, and the API would only
+ // come back and say so.
+ disabled={!hasDomain || enrich.isPending}
+ onClick={() => enrich.mutate({ id: companyId })}
+ >
+ {enrich.isPending ? (
+ <Spinner />
+ ) : (
+ <Icon icon={Renew} data-icon="inline-start" />
+ )}
+ Re-enrich
+ </Button>
+
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!hasDomain || research.isPending}
+ onClick={() => research.mutate({ id: companyId })}
+ >
+ {research.isPending ? (
+ <Spinner />
+ ) : (
+ <Icon icon={MagicWand} data-icon="inline-start" />
+ )}
+ Research
+ </Button>
+ </>
+ );
+}
diff --git a/apps/app/components/crm/enrichment-status.tsx b/apps/app/components/crm/enrichment-status.tsx
new file mode 100644
index 00000000..1e809c95
--- /dev/null
+++ b/apps/app/components/crm/enrichment-status.tsx
@@ -0,0 +1,51 @@
+import type { EnrichmentStatus } from "@crm/db/enums";
+import {
+ StatusIndicator,
+ type StatusTone,
+} from "@crm/ui/components/status-indicator";
+
+/**
+ * How the agent is getting on with a company.
+ *
+ * `SKIPPED` is neutral, not an error: there was nothing to find (an unknown
+ * domain, a free email host), and no credits were spent. `FAILED` is the one
+ * worth chasing.
+ */
+const PRESENTATION: Record<
+ EnrichmentStatus,
+ { label: string; tone: StatusTone; busy?: boolean }
+> = {
+ PENDING: { label: "Queued", tone: "neutral" },
+ RUNNING: { label: "Enriching", tone: "info", busy: true },
+ COMPLETE: { label: "Enriched", tone: "success" },
+ FAILED: { label: "Enrichment failed", tone: "error" },
+ SKIPPED: { label: "Nothing found", tone: "neutral" },
+};
+
+export function EnrichmentIndicator({
+ status,
+ /** The error, when there is one — shown on hover rather than in the row. */
+ title,
+ className,
+}: {
+ status: EnrichmentStatus;
+ title?: string | null;
+ className?: string;
+}) {
+ const { label, tone, busy } = PRESENTATION[status];
+
+ return (
+ <StatusIndicator
+ tone={tone}
+ busy={busy}
+ label={label}
+ title={title ?? undefined}
+ className={className}
+ />
+ );
+}
+
+/** Statuses in the order the facet dropdown should list them. */
+export const ENRICHMENT_FACET_OPTIONS = (
+ Object.keys(PRESENTATION) as EnrichmentStatus[]
+).map((value) => ({ value, label: PRESENTATION[value].label }));
diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsx
new file mode 100644
index 00000000..d9a1df4c
--- /dev/null
+++ b/apps/app/components/crm/inline-field.tsx
@@ -0,0 +1,137 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { Input } from "@crm/ui/components/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@crm/ui/components/select";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useId, useState } from "react";
+
+/**
+ * A property that turns into an input when you click it.
+ *
+ * The detail page is where reps live, and a card of read-only values with an
+ * "Edit" mode over the whole thing means five clicks to fix one typo. Each
+ * field saves on Enter or blur and reverts on Escape.
+ */
+export function InlineField({
+ label,
+ value,
+ onSave,
+ saving = false,
+ placeholder,
+ type = "text",
+ render,
+}: {
+ label: string;
+ value: string | null;
+ onSave: (next: string) => void;
+ saving?: boolean;
+ placeholder?: string;
+ type?: "text" | "url" | "email" | "tel";
+ /** How the saved value reads when not being edited — a link, usually. */
+ render?: (value: string) => React.ReactNode;
+}) {
+ const id = useId();
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(value ?? "");
+
+ const commit = () => {
+ setEditing(false);
+ if (draft.trim() !== (value ?? "")) onSave(draft.trim());
+ };
+
+ return (
+ <div className="grid grid-cols-[minmax(0,9rem)_minmax(0,1fr)] items-center gap-3 py-1.5">
+ <label htmlFor={id} className="truncate text-muted-foreground text-xs">
+ {label}
+ </label>
+
+ {editing ? (
+ <Input
+ id={id}
+ type={type}
+ // The input only exists because the user just clicked this field;
+ // not focusing it would mean clicking twice to type once.
+ autoFocus
+ value={draft}
+ placeholder={placeholder}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ commit();
+ }
+ if (event.key === "Escape") {
+ setDraft(value ?? "");
+ setEditing(false);
+ }
+ }}
+ />
+ ) : (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 justify-start font-normal"
+ onClick={() => {
+ setDraft(value ?? "");
+ setEditing(true);
+ }}
+ >
+ {saving ? <Spinner /> : null}
+ {value ? (
+ <span className="truncate">{render ? render(value) : value}</span>
+ ) : (
+ <span className="text-muted-foreground">
+ {placeholder ?? <EmptyCellValue />}
+ </span>
+ )}
+ </Button>
+ )}
+ </div>
+ );
+}
+
+/** The same row, for a value chosen from a list rather than typed. */
+export function InlineSelectField({
+ label,
+ value,
+ options,
+ onSave,
+ placeholder = "None",
+}: {
+ label: string;
+ value: string;
+ options: { value: string; label: string }[];
+ onSave: (next: string) => void;
+ placeholder?: string;
+}) {
+ const id = useId();
+
+ return (
+ <div className="grid grid-cols-[minmax(0,9rem)_minmax(0,1fr)] items-center gap-3 py-1.5">
+ <label htmlFor={id} className="truncate text-muted-foreground text-xs">
+ {label}
+ </label>
+ <Select value={value} onValueChange={onSave}>
+ <SelectTrigger id={id} size="sm">
+ <SelectValue placeholder={placeholder} />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
diff --git a/apps/app/components/crm/owner-cell.tsx b/apps/app/components/crm/owner-cell.tsx
new file mode 100644
index 00000000..d588990a
--- /dev/null
+++ b/apps/app/components/crm/owner-cell.tsx
@@ -0,0 +1,52 @@
+import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@crm/ui/components/tooltip";
+import { initialsFromName } from "@crm/ui/lib/format";
+
+export type Owner = {
+ id: string;
+ name: string;
+ email: string;
+ image: string | null;
+};
+
+/** The person a company, contact or deal is assigned to. */
+export function OwnerCell({
+ owner,
+ /** Avatar only — for tight spots like a board card footer. */
+ compact = false,
+}: {
+ owner: Owner | null;
+ compact?: boolean;
+}) {
+ if (!owner) return compact ? null : <EmptyCellValue />;
+
+ const avatar = (
+ <Avatar size="sm">
+ {owner.image ? <AvatarImage src={owner.image} alt="" /> : null}
+ <AvatarFallback>{initialsFromName(owner.name)}</AvatarFallback>
+ </Avatar>
+ );
+
+ if (compact) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>{avatar}</span>
+ </TooltipTrigger>
+ <TooltipContent>{owner.name}</TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return (
+ <span className="flex min-w-0 items-center gap-2">
+ {avatar}
+ <span className="truncate">{owner.name}</span>
+ </span>
+ );
+}
diff --git a/apps/app/components/crm/quick-switcher.tsx b/apps/app/components/crm/quick-switcher.tsx
new file mode 100644
index 00000000..1381355b
--- /dev/null
+++ b/apps/app/components/crm/quick-switcher.tsx
@@ -0,0 +1,127 @@
+"use client";
+
+import {
+ Command,
+ CommandDialog,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@crm/ui/components/command";
+import { EntityLogo } from "@crm/ui/components/entity-logo";
+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";
+import { useQuery } from "@tanstack/react-query";
+import { parseAsBoolean, useQueryState } from "nuqs";
+import { useState } from "react";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { useTRPC } from "@/lib/trpc/client";
+
+const GROUP_LABEL = {
+ company: "Companies",
+ contact: "Contacts",
+ deal: "Deals",
+} as const;
+
+const KINDS = ["company", "contact", "deal"] as const;
+
+/**
+ * ⌘K over companies, contacts and deals.
+ *
+ * Open state is in the URL like every other overlay here, so a colleague can be
+ * sent `?k=true` and land on the same thing. The query itself is not — a
+ * half-typed search is not a view worth sharing, and it would put every
+ * keystroke in the history.
+ */
+export function QuickSwitcher() {
+ const openRecord = useOpenRecord();
+ const trpc = useTRPC();
+
+ const [open, setOpen] = useQueryState("k", parseAsBoolean.withDefault(false));
+ const [query, setQuery] = useState("");
+
+ // The keyboard shortcut is a document-level listener, which is exactly what
+ // `useMountEffect` is for — it is a subscription, not derived state.
+ useMountEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "k" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ void setOpen((current) => (current ? null : true));
+ }
+ };
+
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ });
+
+ const results = useQuery({
+ ...trpc.search.quick.queryOptions({ q: query }),
+ // Two characters is where the results stop being "everything".
+ enabled: open && query.trim().length >= 2,
+ placeholderData: (previous) => previous,
+ });
+
+ const hits = results.data?.hits ?? [];
+
+ const go = (kind: (typeof KINDS)[number], id: string) => {
+ setQuery("");
+ void setOpen(null);
+ openRecord({ kind, id });
+ };
+
+ return (
+ <CommandDialog
+ open={open}
+ onOpenChange={(next) => setOpen(next || null)}
+ title="Search"
+ description="Jump to a company, contact or deal"
+ >
+ {/*
+ * `shouldFilter={false}`: the API already matched and ranked these,
+ * against fields the row does not always render (an email, a domain).
+ * Letting cmdk filter again would drop hits whose match is invisible.
+ */}
+ <Command shouldFilter={false}>
+ <CommandInput
+ placeholder="Search companies, contacts and deals…"
+ value={query}
+ onValueChange={setQuery}
+ />
+ <CommandList>
+ <CommandEmpty>
+ {query.trim().length < 2
+ ? "Type at least two characters."
+ : "Nothing matches."}
+ </CommandEmpty>
+
+ {KINDS.map((kind) => {
+ const group = hits.filter((hit) => hit.kind === kind);
+ if (group.length === 0) return null;
+
+ return (
+ <CommandGroup key={kind} heading={GROUP_LABEL[kind]}>
+ {group.map((hit) => (
+ <CommandItem
+ key={`${hit.kind}:${hit.id}`}
+ value={`${hit.kind}:${hit.id}`}
+ onSelect={() => go(kind, hit.id)}
+ >
+ <EntityLogo src={hit.iconUrl} name={hit.label} size="sm" />
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate">{hit.label}</span>
+ {hit.detail ? (
+ <span className="truncate text-muted-foreground text-xs">
+ {hit.detail}
+ </span>
+ ) : null}
+ </span>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ );
+ })}
+ </CommandList>
+ </Command>
+ </CommandDialog>
+ );
+}
diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsx
new file mode 100644
index 00000000..9f13b267
--- /dev/null
+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx
@@ -0,0 +1,471 @@
+"use client";
+
+import Launch from "@carbon/icons-react/es/Launch";
+import Star from "@carbon/icons-react/es/Star";
+import StarFilled from "@carbon/icons-react/es/StarFilled";
+import { Button } from "@crm/ui/components/button";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { EntityLogo } from "@crm/ui/components/entity-logo";
+import { Icon } from "@crm/ui/components/icon";
+import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
+import { TableCell } from "@crm/ui/components/table";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@crm/ui/components/tooltip";
+import { formatMoney } from "@crm/ui/lib/format";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+import { CompanySocials } from "@/components/crm/company-socials";
+import { OPEN_STAGES } from "@/components/crm/deal-stage";
+import { EnrichmentActions } from "@/components/crm/enrichment-actions";
+import { EnrichmentIndicator } from "@/components/crm/enrichment-status";
+import { InlineField, InlineSelectField } from "@/components/crm/inline-field";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { DealStageMenu } from "@/components/crm/stage-change";
+import { Timeline } from "@/components/crm/timeline/timeline";
+import {
+ DetailSheetBody,
+ DetailSheetEmpty,
+ DetailSheetSection,
+ DetailSheetStat,
+ DetailSheetStats,
+ type DetailSheetTab,
+} from "@/components/detail-sheet";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { DealAmount, RecordSheetFrame } from "./record-parts";
+import { useOpenRecord } from "./record-stack";
+
+type Company = RouterOutputs["companies"]["byId"];
+
+const UNASSIGNED = "unassigned";
+
+const CONTACT_COLUMNS = [
+ { srLabel: "Primary", width: "w-10", className: "pl-4" },
+ { header: "Name", width: "w-[28%]" },
+ { header: "Title", width: "w-[24%]" },
+ { header: "Email", width: "w-[26%]" },
+ { header: "Owner", width: "w-[22%]" },
+];
+
+const DEAL_COLUMNS = [
+ { header: "Deal", width: "w-[32%]", className: "pl-4" },
+ { header: "Stage", width: "w-[24%]" },
+ { header: "Amount", width: "w-[16%]", align: "right" as const },
+ { header: "Close date", width: "w-[14%]" },
+ { header: "Owner", width: "w-[14%]" },
+];
+
+const dateFormat = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+});
+
+/**
+ * A company, everything attached to it, and the agent's work on it.
+ *
+ * Polls while the agent is running: enrichment is a background write with no
+ * client action behind it, so there is nothing to invalidate — the only way to
+ * notice it finished is to ask. The interval stops the moment it settles.
+ */
+export function CompanySheet({
+ companyId,
+ open,
+ onOpenChange,
+}: {
+ companyId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const trpc = useTRPC();
+ const [tab, setTab] = useState("overview");
+
+ const query = useQuery({
+ ...trpc.companies.byId.queryOptions({ id: companyId }),
+ enabled: open,
+ refetchInterval: (current) => {
+ const status = current.state.data?.enrichmentStatus;
+ return status === "PENDING" || status === "RUNNING" ? 3_000 : false;
+ },
+ });
+
+ const company = query.data;
+
+ const location = company
+ ? [company.city, company.stateCode, company.country]
+ .filter(Boolean)
+ .join(", ")
+ : "";
+
+ const openDeals =
+ company?.deals.filter((deal) => OPEN_STAGES.includes(deal.stage)) ?? [];
+ const openValueCents = openDeals.reduce(
+ (total, deal) => total + (deal.amountCents ?? 0),
+ 0,
+ );
+
+ const tabs: DetailSheetTab[] = company
+ ? [
+ {
+ value: "overview",
+ label: "Overview",
+ content: <CompanyOverview company={company} />,
+ },
+ {
+ value: "contacts",
+ label: "Contacts",
+ count: company.contacts.length,
+ content: <CompanyContacts company={company} />,
+ },
+ {
+ value: "deals",
+ label: "Deals",
+ count: company.deals.length,
+ content: <CompanyDeals company={company} />,
+ },
+ {
+ value: "activity",
+ label: "Activity",
+ content: <Timeline anchor={{ companyId: company.id }} />,
+ },
+ ]
+ : [];
+
+ return (
+ <RecordSheetFrame
+ open={open}
+ onOpenChange={onOpenChange}
+ loading={query.isPending}
+ error={query.error?.message ?? null}
+ title={company?.name ?? "Company"}
+ description={
+ company
+ ? [company.domain, location, company.industry]
+ .filter(Boolean)
+ .join(" · ") ||
+ "No domain yet — add one and the agent will fill in the rest."
+ : undefined
+ }
+ media={
+ <EntityLogo
+ src={company?.iconUrl ?? company?.logoUrl}
+ name={company?.name ?? "?"}
+ size="xl"
+ />
+ }
+ eyebrow={
+ company ? (
+ <EnrichmentIndicator
+ status={company.enrichmentStatus}
+ title={company.enrichmentError}
+ />
+ ) : null
+ }
+ actions={
+ company ? (
+ <>
+ {company.website ? (
+ <Button asChild variant="outline" size="sm">
+ <a
+ href={company.website}
+ target="_blank"
+ rel="noreferrer noopener"
+ >
+ <Icon icon={Launch} data-icon="inline-start" />
+ Visit site
+ </a>
+ </Button>
+ ) : null}
+ <EnrichmentActions
+ companyId={company.id}
+ hasDomain={company.domain !== null}
+ />
+ </>
+ ) : null
+ }
+ stats={
+ company ? (
+ <DetailSheetStats>
+ <DetailSheetStat label="Contacts">
+ <span className="tabular-nums">{company.contacts.length}</span>
+ </DetailSheetStat>
+ <DetailSheetStat label="Open deals">
+ <span className="tabular-nums">{openDeals.length}</span>
+ </DetailSheetStat>
+ <DetailSheetStat label="Open pipeline">
+ <span className="tabular-nums">
+ {formatMoney(openValueCents)}
+ </span>
+ </DetailSheetStat>
+ <DetailSheetStat label="Owner">
+ <OwnerCell owner={company.owner} />
+ </DetailSheetStat>
+ </DetailSheetStats>
+ ) : null
+ }
+ tabs={tabs}
+ tab={tab}
+ onTabChange={setTab}
+ />
+ );
+}
+
+function CompanyOverview({ company }: { company: Company }) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ const users = useQuery(trpc.users.list.queryOptions());
+
+ const update = useMutation(
+ trpc.companies.update.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey({ id: company.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.list.queryKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const save = (data: Record<string, string | null>) =>
+ update.mutate({ id: company.id, data });
+
+ return (
+ <DetailSheetBody>
+ {/*
+ * Only the fields a rep would correct by hand are editable: the brand,
+ * industry and socials come from the agent, and a text box inviting
+ * someone to retype them is a text box inviting someone to fight it.
+ */}
+ <DetailSheetSection title="Details">
+ <div className="grid gap-x-8 sm:grid-cols-2">
+ <InlineField
+ label="Name"
+ value={company.name}
+ saving={update.isPending}
+ onSave={(name) => name && save({ name })}
+ />
+ <InlineField
+ label="Domain"
+ value={company.domain}
+ type="url"
+ placeholder="stripe.com"
+ saving={update.isPending}
+ onSave={(domain) => save({ domain })}
+ />
+ <InlineField
+ label="Website"
+ value={company.website}
+ type="url"
+ placeholder="https://stripe.com"
+ saving={update.isPending}
+ onSave={(website) => save({ website })}
+ />
+ <InlineField
+ label="Phone"
+ value={company.phone}
+ type="tel"
+ saving={update.isPending}
+ onSave={(phone) => save({ phone })}
+ />
+ <InlineField
+ label="Email"
+ value={company.email}
+ type="email"
+ saving={update.isPending}
+ onSave={(email) => save({ email })}
+ />
+ <InlineField
+ label="City"
+ value={company.city}
+ saving={update.isPending}
+ onSave={(city) => save({ city })}
+ />
+ <InlineField
+ label="Country"
+ value={company.country}
+ saving={update.isPending}
+ onSave={(country) => save({ country })}
+ />
+ <InlineSelectField
+ label="Owner"
+ value={company.owner?.id ?? UNASSIGNED}
+ options={[
+ { value: UNASSIGNED, label: "Unassigned" },
+ ...(users.data ?? []).map((user) => ({
+ value: user.id,
+ label: user.name,
+ })),
+ ]}
+ onSave={(ownerId) =>
+ save({ ownerId: ownerId === UNASSIGNED ? null : ownerId })
+ }
+ />
+ </div>
+ </DetailSheetSection>
+
+ {company.description ? (
+ <DetailSheetSection title="About">
+ <p className="text-pretty text-muted-foreground text-sm/6">
+ {company.description}
+ </p>
+ </DetailSheetSection>
+ ) : null}
+
+ <CompanyLinks company={company} />
+ </DetailSheetBody>
+ );
+}
+
+/**
+ * Renders nothing until the agent has found somewhere to link to — a heading
+ * over an empty row of icons says "broken", not "not enriched yet".
+ */
+function CompanyLinks({ company }: { company: Company }) {
+ const hasAny = [
+ company.website,
+ company.linkedinUrl,
+ company.twitterUrl,
+ company.githubUrl,
+ company.pricingUrl,
+ company.careersUrl,
+ ].some(Boolean);
+
+ if (!hasAny) return null;
+
+ return (
+ <DetailSheetSection title="Links">
+ <CompanySocials company={company} />
+ </DetailSheetSection>
+ );
+}
+
+function CompanyContacts({ company }: { company: Company }) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const openRecord = useOpenRecord();
+
+ const setPrimary = useMutation(
+ trpc.companies.setPrimaryContact.mutationOptions({
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey({ id: company.id }),
+ });
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ if (company.contacts.length === 0) {
+ return <DetailSheetEmpty>Nobody here yet.</DetailSheetEmpty>;
+ }
+
+ return (
+ <SimpleTable variant="panel" columns={CONTACT_COLUMNS}>
+ {company.contacts.map((contact) => {
+ const isPrimary = contact.id === company.primaryContactId;
+ return (
+ <SimpleTableRow
+ key={contact.id}
+ clickable
+ onClick={() => openRecord({ kind: "contact", id: contact.id })}
+ >
+ <TableCell className="w-10 py-2.5 pl-4">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-pressed={isPrimary}
+ disabled={isPrimary || setPrimary.isPending}
+ // Without this the row's own handler fires too and opens
+ // the contact over the change just made.
+ onClick={(event) => {
+ event.stopPropagation();
+ setPrimary.mutate({
+ companyId: company.id,
+ contactId: contact.id,
+ });
+ }}
+ >
+ <Icon icon={isPrimary ? StarFilled : Star} />
+ <span className="sr-only">
+ {isPrimary ? "Primary contact" : "Make primary"}
+ </span>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {isPrimary ? "Primary contact" : "Make primary"}
+ </TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell className="truncate px-3 py-2.5 font-medium">
+ {[contact.firstName, contact.lastName].filter(Boolean).join(" ")}
+ </TableCell>
+ <TableCell className="truncate px-3 py-2.5">
+ {contact.title ?? <EmptyCellValue />}
+ </TableCell>
+ <TableCell className="truncate px-3 py-2.5 text-muted-foreground">
+ {contact.email ?? <EmptyCellValue />}
+ </TableCell>
+ <TableCell className="px-3 py-2.5">
+ <OwnerCell owner={contact.owner} />
+ </TableCell>
+ </SimpleTableRow>
+ );
+ })}
+ </SimpleTable>
+ );
+}
+
+function CompanyDeals({ company }: { company: Company }) {
+ const openRecord = useOpenRecord();
+
+ if (company.deals.length === 0) {
+ return <DetailSheetEmpty>No deals yet.</DetailSheetEmpty>;
+ }
+
+ return (
+ <SimpleTable variant="panel" columns={DEAL_COLUMNS}>
+ {company.deals.map((deal) => (
+ <SimpleTableRow
+ key={deal.id}
+ clickable
+ onClick={() => openRecord({ kind: "deal", id: deal.id })}
+ >
+ <TableCell className="truncate py-2.5 pr-3 pl-4 font-medium">
+ {deal.name}
+ </TableCell>
+ <TableCell className="px-3 py-2.5">
+ <DealStageMenu dealId={deal.id} stage={deal.stage} />
+ </TableCell>
+ <TableCell className="px-3 py-2.5 text-right">
+ <DealAmount
+ amountCents={deal.amountCents}
+ currency={deal.currency}
+ />
+ </TableCell>
+ <TableCell className="px-3 py-2.5 text-muted-foreground">
+ {deal.expectedCloseDate ? (
+ dateFormat.format(new Date(deal.expectedCloseDate))
+ ) : (
+ <EmptyCellValue />
+ )}
+ </TableCell>
+ <TableCell className="px-3 py-2.5">
+ <OwnerCell owner={deal.owner} />
+ </TableCell>
+ </SimpleTableRow>
+ ))}
+ </SimpleTable>
+ );
+}
diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsx
new file mode 100644
index 00000000..e812cffd
--- /dev/null
+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx
@@ -0,0 +1,376 @@
+"use client";
+
+import Email from "@carbon/icons-react/es/Email";
+import Star from "@carbon/icons-react/es/Star";
+import { Button } from "@crm/ui/components/button";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { EntityLogo } from "@crm/ui/components/entity-logo";
+import { Icon } from "@crm/ui/components/icon";
+import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
+import { StatusIndicator } from "@crm/ui/components/status-indicator";
+import { TableCell } from "@crm/ui/components/table";
+import { formatMoney, initialsFromName } from "@crm/ui/lib/format";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+import { OPEN_STAGES } from "@/components/crm/deal-stage";
+import { InlineField, InlineSelectField } from "@/components/crm/inline-field";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { DealStageMenu } from "@/components/crm/stage-change";
+import { Timeline } from "@/components/crm/timeline/timeline";
+import {
+ DetailSheetBody,
+ DetailSheetEmpty,
+ DetailSheetSection,
+ DetailSheetStat,
+ DetailSheetStats,
+ type DetailSheetTab,
+} from "@/components/detail-sheet";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { DealAmount, RecordSheetFrame } from "./record-parts";
+import { useOpenRecord } from "./record-stack";
+
+type Contact = RouterOutputs["contacts"]["byId"];
+
+const NONE = "none";
+
+const DEAL_COLUMNS = [
+ { header: "Deal", width: "w-[32%]", className: "pl-4" },
+ { header: "Role", width: "w-[16%]" },
+ { header: "Stage", width: "w-[22%]" },
+ { header: "Amount", width: "w-[16%]", align: "right" as const },
+ { header: "Owner", width: "w-[14%]" },
+];
+
+function contactName(contact: {
+ firstName: string;
+ lastName: string | null;
+}): string {
+ return [contact.firstName, contact.lastName].filter(Boolean).join(" ");
+}
+
+export function ContactSheet({
+ contactId,
+ open,
+ onOpenChange,
+}: {
+ contactId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [tab, setTab] = useState("overview");
+
+ const query = useQuery({
+ ...trpc.contacts.byId.queryOptions({ id: contactId }),
+ enabled: open,
+ });
+
+ const contact = query.data;
+
+ const setPrimary = useMutation(
+ trpc.companies.setPrimaryContact.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.contacts.byId.queryKey({ id: contactId }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey(),
+ }),
+ ]);
+ toast.success("Primary contact updated.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const openDeals =
+ contact?.deals.filter((deal) => OPEN_STAGES.includes(deal.stage)) ?? [];
+ const openValueCents = openDeals.reduce(
+ (total, deal) => total + (deal.amountCents ?? 0),
+ 0,
+ );
+
+ const tabs: DetailSheetTab[] = contact
+ ? [
+ {
+ value: "overview",
+ label: "Overview",
+ content: <ContactOverview contact={contact} />,
+ },
+ {
+ value: "deals",
+ label: "Deals",
+ count: contact.deals.length,
+ content: <ContactDeals contact={contact} />,
+ },
+ {
+ value: "activity",
+ label: "Activity",
+ content: <Timeline anchor={{ contactId: contact.id }} />,
+ },
+ ]
+ : [];
+
+ return (
+ <RecordSheetFrame
+ open={open}
+ onOpenChange={onOpenChange}
+ loading={query.isPending}
+ error={query.error?.message ?? null}
+ title={contact ? contactName(contact) : "Contact"}
+ description={
+ contact
+ ? [contact.title, contact.company?.name]
+ .filter(Boolean)
+ .join(" · ") || "No title or company yet."
+ : undefined
+ }
+ // A person, so initials rather than a logo — there is no avatar in the
+ // directory and a broken image placeholder is worse than two letters.
+ media={
+ <span className="inline-flex size-14 shrink-0 items-center justify-center border bg-muted font-medium text-lg text-muted-foreground uppercase">
+ {contact ? initialsFromName(contactName(contact)) : "?"}
+ </span>
+ }
+ eyebrow={
+ contact?.isPrimaryContact ? (
+ <StatusIndicator tone="success" label="Primary contact" />
+ ) : null
+ }
+ actions={
+ contact ? (
+ <>
+ {contact.email ? (
+ <Button asChild variant="outline" size="sm">
+ <a href={`mailto:${contact.email}`}>
+ <Icon icon={Email} data-icon="inline-start" />
+ Email
+ </a>
+ </Button>
+ ) : null}
+ {contact.company && !contact.isPrimaryContact ? (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={setPrimary.isPending}
+ onClick={() =>
+ setPrimary.mutate({
+ // Narrowed by the guard above; the API re-checks that this
+ // person actually works there.
+ companyId: contact.company?.id ?? "",
+ contactId: contact.id,
+ })
+ }
+ >
+ <Icon icon={Star} data-icon="inline-start" />
+ Make primary
+ </Button>
+ ) : null}
+ </>
+ ) : null
+ }
+ stats={
+ contact ? (
+ <DetailSheetStats>
+ <DetailSheetStat label="Company">
+ {contact.company ? (
+ <CompanyStat company={contact.company} />
+ ) : (
+ <EmptyCellValue />
+ )}
+ </DetailSheetStat>
+ <DetailSheetStat label="Deals">
+ <span className="tabular-nums">{contact.deals.length}</span>
+ </DetailSheetStat>
+ <DetailSheetStat label="Open pipeline">
+ <span className="tabular-nums">
+ {formatMoney(openValueCents)}
+ </span>
+ </DetailSheetStat>
+ <DetailSheetStat label="Owner">
+ <OwnerCell owner={contact.owner} />
+ </DetailSheetStat>
+ </DetailSheetStats>
+ ) : null
+ }
+ tabs={tabs}
+ tab={tab}
+ onTabChange={setTab}
+ />
+ );
+}
+
+function CompanyStat({
+ company,
+}: {
+ company: NonNullable<Contact["company"]>;
+}) {
+ const openRecord = useOpenRecord();
+
+ return (
+ <button
+ type="button"
+ onClick={() => openRecord({ kind: "company", id: company.id })}
+ className="flex min-w-0 items-center gap-2 hover:underline"
+ >
+ <EntityLogo src={company.iconUrl} name={company.name} size="xs" />
+ <span className="truncate">{company.name}</span>
+ </button>
+ );
+}
+
+function ContactOverview({ contact }: { contact: Contact }) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ const users = useQuery(trpc.users.list.queryOptions());
+ const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
+
+ const update = useMutation(
+ trpc.contacts.update.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.contacts.byId.queryKey({ id: contact.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.contacts.list.queryKey(),
+ }),
+ // Moving someone between companies changes both companies' records.
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const save = (data: Record<string, string | null>) =>
+ update.mutate({ id: contact.id, data });
+
+ return (
+ <DetailSheetBody>
+ <DetailSheetSection title="Details">
+ <div className="grid gap-x-8 sm:grid-cols-2">
+ <InlineField
+ label="First name"
+ value={contact.firstName}
+ saving={update.isPending}
+ onSave={(firstName) => firstName && save({ firstName })}
+ />
+ <InlineField
+ label="Last name"
+ value={contact.lastName}
+ saving={update.isPending}
+ onSave={(lastName) => save({ lastName })}
+ />
+ <InlineField
+ label="Title"
+ value={contact.title}
+ placeholder="Head of Security"
+ saving={update.isPending}
+ onSave={(title) => save({ title })}
+ />
+ <InlineField
+ label="Email"
+ value={contact.email}
+ type="email"
+ saving={update.isPending}
+ onSave={(email) => save({ email })}
+ render={(email) => (
+ <a href={`mailto:${email}`} className="hover:underline">
+ {email}
+ </a>
+ )}
+ />
+ <InlineField
+ label="Phone"
+ value={contact.phone}
+ type="tel"
+ saving={update.isPending}
+ onSave={(phone) => save({ phone })}
+ />
+ <InlineField
+ label="LinkedIn"
+ value={contact.linkedinUrl}
+ type="url"
+ saving={update.isPending}
+ onSave={(linkedinUrl) => save({ linkedinUrl })}
+ />
+ <InlineSelectField
+ label="Company"
+ value={contact.company?.id ?? NONE}
+ options={[
+ { value: NONE, label: "No company" },
+ ...(companies.data ?? []).map((company) => ({
+ value: company.id,
+ label: company.name,
+ })),
+ ]}
+ onSave={(companyId) =>
+ save({ companyId: companyId === NONE ? null : companyId })
+ }
+ />
+ <InlineSelectField
+ label="Owner"
+ value={contact.owner?.id ?? NONE}
+ options={[
+ { value: NONE, label: "Unassigned" },
+ ...(users.data ?? []).map((user) => ({
+ value: user.id,
+ label: user.name,
+ })),
+ ]}
+ onSave={(ownerId) =>
+ save({ ownerId: ownerId === NONE ? null : ownerId })
+ }
+ />
+ </div>
+ </DetailSheetSection>
+ </DetailSheetBody>
+ );
+}
+
+function ContactDeals({ contact }: { contact: Contact }) {
+ const openRecord = useOpenRecord();
+
+ if (contact.deals.length === 0) {
+ return <DetailSheetEmpty>Not on any deals yet.</DetailSheetEmpty>;
+ }
+
+ return (
+ <SimpleTable variant="panel" columns={DEAL_COLUMNS}>
+ {contact.deals.map((deal) => (
+ <SimpleTableRow
+ key={deal.id}
+ clickable
+ onClick={() => openRecord({ kind: "deal", id: deal.id })}
+ >
+ <TableCell className="truncate py-2.5 pr-3 pl-4 font-medium">
+ {deal.name}
+ </TableCell>
+ <TableCell className="truncate px-3 py-2.5 text-muted-foreground">
+ {deal.role ?? <EmptyCellValue />}
+ </TableCell>
+ <TableCell className="px-3 py-2.5">
+ <DealStageMenu dealId={deal.id} stage={deal.stage} />
+ </TableCell>
+ <TableCell className="px-3 py-2.5 text-right">
+ <DealAmount
+ amountCents={deal.amountCents}
+ currency={deal.currency}
+ />
+ </TableCell>
+ <TableCell className="px-3 py-2.5">
+ <OwnerCell owner={deal.owner} />
+ </TableCell>
+ </SimpleTableRow>
+ ))}
+ </SimpleTable>
+ );
+}
diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsx
new file mode 100644
index 00000000..a9c179cf
--- /dev/null
+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx
@@ -0,0 +1,320 @@
+"use client";
+
+import { Alert, AlertDescription, AlertTitle } from "@crm/ui/components/alert";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { EntityLogo } from "@crm/ui/components/entity-logo";
+import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
+import { TableCell } from "@crm/ui/components/table";
+import { formatMoney, relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+import { DealStageIndicator } from "@/components/crm/deal-stage";
+import { InlineField, InlineSelectField } from "@/components/crm/inline-field";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { StageStepper } from "@/components/crm/stage-stepper";
+import { Timeline } from "@/components/crm/timeline/timeline";
+import {
+ DetailSheetBody,
+ DetailSheetEmpty,
+ DetailSheetSection,
+ DetailSheetStat,
+ DetailSheetStats,
+ type DetailSheetTab,
+} from "@/components/detail-sheet";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { RecordSheetFrame } from "./record-parts";
+import { useOpenRecord } from "./record-stack";
+
+type Deal = RouterOutputs["deals"]["byId"];
+
+const CONTACT_COLUMNS = [
+ { header: "Name", width: "w-[30%]", className: "pl-4" },
+ { header: "Role", width: "w-[20%]" },
+ { header: "Title", width: "w-[25%]" },
+ { header: "Email", width: "w-[25%]" },
+];
+
+const dateFormat = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+});
+
+/** `2026-07-31` — what `<input type="date">` speaks. */
+function toDateInput(iso: string | null): string | null {
+ return iso ? (iso.slice(0, 10) ?? null) : null;
+}
+
+export function DealSheet({
+ dealId,
+ open,
+ onOpenChange,
+}: {
+ dealId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const trpc = useTRPC();
+ const openRecord = useOpenRecord();
+ const [tab, setTab] = useState("overview");
+
+ const query = useQuery({
+ ...trpc.deals.byId.queryOptions({ id: dealId }),
+ enabled: open,
+ });
+
+ const deal = query.data;
+
+ const tabs: DetailSheetTab[] = deal
+ ? [
+ {
+ value: "overview",
+ label: "Overview",
+ content: <DealOverview deal={deal} />,
+ },
+ {
+ value: "contacts",
+ label: "Contacts",
+ count: deal.contacts.length,
+ content: <DealContacts deal={deal} />,
+ },
+ {
+ value: "activity",
+ label: "Activity",
+ content: <Timeline anchor={{ dealId: deal.id }} />,
+ },
+ ]
+ : [];
+
+ return (
+ <RecordSheetFrame
+ open={open}
+ onOpenChange={onOpenChange}
+ loading={query.isPending}
+ error={query.error?.message ?? null}
+ title={deal?.name ?? "Deal"}
+ description={
+ deal ? (
+ <button
+ type="button"
+ onClick={() => openRecord({ kind: "company", id: deal.company.id })}
+ className="hover:underline"
+ >
+ {deal.company.name}
+ </button>
+ ) : undefined
+ }
+ media={
+ deal ? (
+ <EntityLogo
+ src={deal.company.iconUrl}
+ name={deal.company.name}
+ size="xl"
+ />
+ ) : null
+ }
+ eyebrow={
+ deal ? (
+ <>
+ <DealStageIndicator stage={deal.stage} />
+ <span className="text-muted-foreground">
+ changed {relativeTimeFromIso(deal.stageChangedAt)}
+ </span>
+ </>
+ ) : null
+ }
+ stats={
+ deal ? (
+ <DetailSheetStats>
+ <DetailSheetStat label="Amount">
+ {deal.amountCents === null ? (
+ <EmptyCellValue />
+ ) : (
+ <span className="tabular-nums">
+ {formatMoney(deal.amountCents, deal.currency)}
+ </span>
+ )}
+ </DetailSheetStat>
+ <DetailSheetStat label="Expected close">
+ {deal.expectedCloseDate ? (
+ dateFormat.format(new Date(deal.expectedCloseDate))
+ ) : (
+ <EmptyCellValue />
+ )}
+ </DetailSheetStat>
+ <DetailSheetStat label="Contacts">
+ <span className="tabular-nums">{deal.contacts.length}</span>
+ </DetailSheetStat>
+ <DetailSheetStat label="Owner">
+ <OwnerCell owner={deal.owner} />
+ </DetailSheetStat>
+ </DetailSheetStats>
+ ) : null
+ }
+ tabs={tabs}
+ tab={tab}
+ onTabChange={setTab}
+ />
+ );
+}
+
+function DealOverview({ deal }: { deal: Deal }) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ const users = useQuery(trpc.users.list.queryOptions());
+ const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
+
+ const update = useMutation(
+ trpc.deals.update.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.byId.queryKey({ id: deal.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const save = (data: Parameters<typeof update.mutate>[0]["data"]) =>
+ update.mutate({ id: deal.id, data });
+
+ return (
+ <DetailSheetBody>
+ {/* Moving a deal along is the most common thing anyone does here, so it
+ * is the first thing in the sheet rather than a field in a list. */}
+ <DetailSheetSection title="Stage">
+ <StageStepper dealId={deal.id} stage={deal.stage} />
+ </DetailSheetSection>
+
+ {deal.closedReason ? (
+ <DetailSheetSection>
+ <Alert>
+ <AlertTitle>
+ {deal.closedAt
+ ? `Closed ${dateFormat.format(new Date(deal.closedAt))}`
+ : "Closed"}
+ </AlertTitle>
+ <AlertDescription>{deal.closedReason}</AlertDescription>
+ </Alert>
+ </DetailSheetSection>
+ ) : null}
+
+ <DetailSheetSection title="Details">
+ <div className="grid gap-x-8 sm:grid-cols-2">
+ <InlineField
+ label="Name"
+ value={deal.name}
+ saving={update.isPending}
+ onSave={(name) => name && save({ name })}
+ />
+ <InlineField
+ label="Amount"
+ // Edited in whole currency; stored and summed in cents.
+ value={
+ deal.amountCents === null ? null : String(deal.amountCents / 100)
+ }
+ placeholder="24000"
+ saving={update.isPending}
+ onSave={(next) => {
+ if (next === "") return save({ amountCents: null });
+ const parsed = Number.parseFloat(next);
+ if (!Number.isFinite(parsed) || parsed < 0) {
+ toast.error("Amount has to be a number.");
+ return;
+ }
+ save({ amountCents: Math.round(parsed * 100) });
+ }}
+ render={(value) =>
+ formatMoney(Math.round(Number(value) * 100), deal.currency)
+ }
+ />
+ <InlineField
+ label="Currency"
+ value={deal.currency}
+ saving={update.isPending}
+ onSave={(currency) => {
+ if (currency.length !== 3) {
+ toast.error("Use a three-letter currency code, like USD.");
+ return;
+ }
+ save({ currency: currency.toUpperCase() });
+ }}
+ />
+ <InlineField
+ label="Close date"
+ value={toDateInput(deal.expectedCloseDate)}
+ placeholder="2026-12-31"
+ saving={update.isPending}
+ onSave={(next) => save({ expectedCloseDate: next || null })}
+ />
+ <InlineSelectField
+ label="Company"
+ value={deal.company.id}
+ options={(companies.data ?? []).map((company) => ({
+ value: company.id,
+ label: company.name,
+ }))}
+ onSave={(companyId) => save({ companyId })}
+ />
+ <InlineSelectField
+ label="Owner"
+ value={deal.owner.id}
+ options={(users.data ?? []).map((user) => ({
+ value: user.id,
+ label: user.name,
+ }))}
+ onSave={(ownerId) => save({ ownerId })}
+ />
+ </div>
+ </DetailSheetSection>
+ </DetailSheetBody>
+ );
+}
+
+function DealContacts({ deal }: { deal: Deal }) {
+ const openRecord = useOpenRecord();
+
+ if (deal.contacts.length === 0) {
+ return (
+ <DetailSheetEmpty>
+ Nobody from {deal.company.name} is on this deal yet.
+ </DetailSheetEmpty>
+ );
+ }
+
+ return (
+ <SimpleTable variant="panel" columns={CONTACT_COLUMNS}>
+ {deal.contacts.map((contact) => (
+ <SimpleTableRow
+ key={contact.id}
+ clickable
+ onClick={() => openRecord({ kind: "contact", id: contact.id })}
+ >
+ <TableCell className="truncate py-2.5 pr-3 pl-4 font-medium">
+ {[contact.firstName, contact.lastName].filter(Boolean).join(" ")}
+ </TableCell>
+ <TableCell className="truncate px-3 py-2.5">
+ {contact.role ?? <EmptyCellValue />}
+ </TableCell>
+ <TableCell className="truncate px-3 py-2.5 text-muted-foreground">
+ {contact.title ?? <EmptyCellValue />}
+ </TableCell>
+ <TableCell className="truncate px-3 py-2.5 text-muted-foreground">
+ {contact.email ?? <EmptyCellValue />}
+ </TableCell>
+ </SimpleTableRow>
+ ))}
+ </SimpleTable>
+ );
+}
diff --git a/apps/app/components/crm/record-sheet/record-link.tsx b/apps/app/components/crm/record-sheet/record-link.tsx
new file mode 100644
index 00000000..af026011
--- /dev/null
+++ b/apps/app/components/crm/record-sheet/record-link.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import ArrowLeft from "@carbon/icons-react/es/ArrowLeft";
+import { Button } from "@crm/ui/components/button";
+import { Icon } from "@crm/ui/components/icon";
+import { cn } from "@crm/ui/lib/utils";
+import type { ReactNode } from "react";
+import { type RecordKind, useOpenRecord, useRecordStack } from "./record-stack";
+
+/**
+ * A cross-reference to another record.
+ *
+ * A button rather than an anchor because there is nowhere to navigate to: the
+ * record opens over whatever you are already looking at, and the URL it would
+ * have pointed at is the one this sets.
+ */
+export function RecordLink({
+ kind,
+ id,
+ className,
+ children,
+}: {
+ kind: RecordKind;
+ id: string;
+ className?: string;
+ children: ReactNode;
+}) {
+ const open = useOpenRecord();
+
+ return (
+ <button
+ type="button"
+ onClick={(event) => {
+ // Rows and cards are clickable too; without this both fire and the
+ // wrong record wins.
+ event.stopPropagation();
+ open({ kind, id });
+ }}
+ className={cn(
+ "min-w-0 truncate text-left text-muted-foreground hover:text-foreground hover:underline",
+ className,
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+/**
+ * Back to the record you opened this one from.
+ *
+ * Only appears once there is somewhere to go back to — on the first record in
+ * a trail the close button beside it already does the same job.
+ */
+export function RecordBack() {
+ const { stack, close } = useRecordStack();
+
+ if (stack.length < 2) return null;
+
+ return (
+ <Button variant="ghost" size="sm" onClick={close}>
+ <Icon icon={ArrowLeft} data-icon="inline-start" />
+ Back
+ </Button>
+ );
+}
diff --git a/apps/app/components/crm/record-sheet/record-parts.tsx b/apps/app/components/crm/record-sheet/record-parts.tsx
new file mode 100644
index 00000000..f6b3bb0e
--- /dev/null
+++ b/apps/app/components/crm/record-sheet/record-parts.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { Spinner } from "@crm/ui/components/spinner";
+import { formatMoney } from "@crm/ui/lib/format";
+import type { ReactNode } from "react";
+import {
+ DetailSheet,
+ DetailSheetHeader,
+ type DetailSheetTab,
+ DetailSheetTabs,
+} from "@/components/detail-sheet";
+import { RecordBack } from "./record-link";
+import { useRecordStack } from "./record-stack";
+
+/**
+ * The frame every record sheet is poured into.
+ *
+ * The header renders before the record has loaded — a sheet has to have a
+ * title from the first frame or the dialog is unlabelled, and a panel that
+ * pops into existence a beat after the click reads as a bug rather than as
+ * loading.
+ */
+export function RecordSheetFrame({
+ open,
+ onOpenChange,
+ loading,
+ error,
+ title,
+ description,
+ media,
+ eyebrow,
+ actions,
+ stats,
+ tabs,
+ tab,
+ onTabChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ loading: boolean;
+ error: string | null;
+ title: string;
+ description?: ReactNode;
+ media?: ReactNode;
+ eyebrow?: ReactNode;
+ actions?: ReactNode;
+ stats?: ReactNode;
+ tabs: DetailSheetTab[];
+ tab: string;
+ onTabChange: (tab: string) => void;
+}) {
+ // The eyebrow row is skipped rather than rendered empty: `space-y` would
+ // still put a gap under a zero-height div, leaving the header top-heavy on
+ // the records that have nothing to say up there.
+ const { stack } = useRecordStack();
+ const nested = stack.length > 1;
+
+ return (
+ <DetailSheet open={open} onOpenChange={onOpenChange}>
+ <DetailSheetHeader
+ eyebrow={
+ nested || eyebrow ? (
+ <>
+ <RecordBack />
+ {eyebrow}
+ </>
+ ) : null
+ }
+ media={media}
+ title={title}
+ description={description}
+ actions={actions}
+ />
+
+ {loading ? (
+ <div className="flex min-h-0 flex-1 items-center justify-center">
+ <Spinner />
+ </div>
+ ) : error ? (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 p-6 text-center">
+ <p className="font-medium text-sm">This record could not be loaded</p>
+ <p className="text-muted-foreground text-xs">{error}</p>
+ </div>
+ ) : (
+ <>
+ {stats}
+ <DetailSheetTabs
+ tabs={tabs}
+ value={tab}
+ onValueChange={onTabChange}
+ />
+ </>
+ )}
+ </DetailSheet>
+ );
+}
+
+/** Money, or the dash that means nobody has put a number on it yet. */
+export function DealAmount({
+ amountCents,
+ currency,
+}: {
+ amountCents: number | null;
+ currency: string;
+}) {
+ if (amountCents === null) return <EmptyCellValue />;
+ return (
+ <span className="tabular-nums">{formatMoney(amountCents, currency)}</span>
+ );
+}
diff --git a/apps/app/components/crm/record-sheet/record-sheet-host.tsx b/apps/app/components/crm/record-sheet/record-sheet-host.tsx
new file mode 100644
index 00000000..22f3df01
--- /dev/null
+++ b/apps/app/components/crm/record-sheet/record-sheet-host.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { useState } from "react";
+import { CloseReasonDialog } from "@/components/crm/stage-change";
+import { CompanySheet } from "./company-sheet";
+import { ContactSheet } from "./contact-sheet";
+import { DealSheet } from "./deal-sheet";
+import { type RecordRef, recordKey, useRecordStack } from "./record-stack";
+
+/**
+ * The one place a company, contact or deal is rendered.
+ *
+ * Mounted in the app shell rather than per page, so opening a contact from a
+ * deal on the deals board works the same as opening one from the contacts
+ * table — and so no list has to carry a copy of every sheet a row might lead
+ * to.
+ */
+export function RecordSheetHost() {
+ const { top, closeAll } = useRecordStack();
+
+ // The record that was last open, kept a beat longer than the URL says.
+ // Unmounting the instant `?record=` clears would cut the close animation
+ // off halfway and make the sheet vanish rather than slide out.
+ const [shown, setShown] = useState<RecordRef | null>(top);
+ if (top && (!shown || recordKey(shown) !== recordKey(top))) {
+ setShown(top);
+ }
+
+ const open = top !== null;
+ // Escape, the X and the backdrop all mean "I am done here", so they leave
+ // the trail rather than stepping up one record at a time — going up is what
+ // the Back button in the header is for.
+ const onOpenChange = (next: boolean) => {
+ if (!next) closeAll();
+ };
+
+ return (
+ <>
+ {shown?.kind === "company" ? (
+ <CompanySheet
+ // A new company reuses the sheet, so remount to reset the tab and
+ // drop the last record's scroll position.
+ key={shown.id}
+ companyId={shown.id}
+ open={open}
+ onOpenChange={onOpenChange}
+ />
+ ) : null}
+
+ {shown?.kind === "contact" ? (
+ <ContactSheet
+ key={shown.id}
+ contactId={shown.id}
+ open={open}
+ onOpenChange={onOpenChange}
+ />
+ ) : null}
+
+ {shown?.kind === "deal" ? (
+ <DealSheet
+ key={shown.id}
+ dealId={shown.id}
+ open={open}
+ onOpenChange={onOpenChange}
+ />
+ ) : null}
+
+ {/*
+ * "Why did we lose it?" is asked from a table row, a board card and a
+ * deal sheet. One dialog for all of them, reading which deal from the
+ * URL, beats one per row.
+ */}
+ <CloseReasonDialog />
+ </>
+ );
+}
diff --git a/apps/app/components/crm/record-sheet/record-stack.ts b/apps/app/components/crm/record-sheet/record-stack.ts
new file mode 100644
index 00000000..7f43b978
--- /dev/null
+++ b/apps/app/components/crm/record-sheet/record-stack.ts
@@ -0,0 +1,93 @@
+"use client";
+
+import { parseAsArrayOf, parseAsString, useQueryState } from "nuqs";
+import { useCallback, useMemo } from "react";
+
+export const RECORD_KINDS = ["company", "contact", "deal"] as const;
+
+export type RecordKind = (typeof RECORD_KINDS)[number];
+
+export type RecordRef = { kind: RecordKind; id: string };
+
+/**
+ * Which records are open, innermost last.
+ *
+ * A stack rather than a single id because the interesting move is sideways:
+ * from a company to one of its deals to somebody on that deal. Closing the
+ * deal should put you back on the company you came from, not on the table.
+ */
+const stackParser = parseAsArrayOf(parseAsString, ",").withDefault([]);
+
+export function recordKey(ref: RecordRef): string {
+ return `${ref.kind}:${ref.id}`;
+}
+
+function parseRef(raw: string): RecordRef | null {
+ const [kind, ...rest] = raw.split(":");
+ const id = rest.join(":");
+ if (!id) return null;
+ return RECORD_KINDS.includes(kind as RecordKind)
+ ? { kind: kind as RecordKind, id }
+ : null;
+}
+
+export function useRecordStack() {
+ const [raw, setRaw] = useQueryState("record", stackParser);
+
+ const stack = useMemo(
+ () => raw.map(parseRef).filter((ref): ref is RecordRef => ref !== null),
+ [raw],
+ );
+
+ const write = useCallback(
+ (next: RecordRef[], history: "push" | "replace") => {
+ // `null` clears the param rather than leaving `?record=` behind.
+ void setRaw(next.length === 0 ? null : next.map(recordKey), { history });
+ },
+ [setRaw],
+ );
+
+ /**
+ * The whole trail is one history entry.
+ *
+ * Opening the first record pushes; stepping sideways to a related one
+ * replaces. So the browser's Back always means "put the sheet away and give
+ * me the list back" — one press, from however deep — and it never lands on
+ * a half-unwound trail or reopens something that was just dismissed. Moving
+ * up one level is what the sheet's own Back button is for.
+ */
+ const open = useCallback(
+ (ref: RecordRef) => {
+ const key = recordKey(ref);
+ // Re-opening something already below you promotes it instead of
+ // stacking a second copy, so the trail cannot loop back on itself.
+ write(
+ [...stack.filter((entry) => recordKey(entry) !== key), ref],
+ stack.length === 0 ? "push" : "replace",
+ );
+ },
+ [stack, write],
+ );
+
+ /** Up one level, to whatever you opened this record from. */
+ const close = useCallback(
+ () => write(stack.slice(0, -1), "replace"),
+ [stack, write],
+ );
+
+ /** Out of the trail entirely — the X, Escape, and clicking the backdrop. */
+ const closeAll = useCallback(() => write([], "replace"), [write]);
+
+ return {
+ stack,
+ top: stack.at(-1) ?? null,
+ open,
+ close,
+ closeAll,
+ };
+}
+
+/** Opens a record from anywhere — a table row, a link, a search hit. */
+export function useOpenRecord() {
+ return useRecordStack().open;
+}
diff --git a/apps/app/components/crm/stage-change.tsx b/apps/app/components/crm/stage-change.tsx
new file mode 100644
index 00000000..eb319a99
--- /dev/null
+++ b/apps/app/components/crm/stage-change.tsx
@@ -0,0 +1,215 @@
+"use client";
+
+import type { DealStage } from "@crm/db/enums";
+import { Button } from "@crm/ui/components/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@crm/ui/components/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@crm/ui/components/dropdown-menu";
+import { Field, FieldLabel } from "@crm/ui/components/field";
+import { Spinner } from "@crm/ui/components/spinner";
+import { Textarea } from "@crm/ui/components/textarea";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { parseAsString, useQueryStates } from "nuqs";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { useTRPC } from "@/lib/trpc/client";
+import {
+ DEAL_STAGE_OPTIONS,
+ DealStageIndicator,
+ LOSING_STAGES,
+} from "./deal-stage";
+
+/**
+ * Which deal is being closed out, and to what.
+ *
+ * In the URL rather than component state so one dialog can serve every row of
+ * the table as well as the detail page — and so a half-finished "why did we
+ * lose this?" survives a refresh instead of silently discarding the answer.
+ */
+const closeReasonParams = {
+ closing: parseAsString,
+ closingStage: parseAsString,
+};
+
+/** Invalidates everywhere a stage is visible. */
+function useStageMutation(onDone?: () => void) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ return useMutation(
+ trpc.deals.setStage.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.byId.queryKey(),
+ }),
+ // A stage change writes a STAGE_CHANGE activity stamped with the
+ // company, so the company page's timeline and last-activity change
+ // too.
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.list.queryKey(),
+ }),
+ ]);
+ onDone?.();
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+}
+
+/**
+ * The stage picker that appears on a deal row and on the deal page.
+ *
+ * Losing stages divert through `CloseReasonDialog`: the API refuses them
+ * without a reason, so asking here is friendlier than a toast full of the
+ * rejection.
+ */
+export function DealStageMenu({
+ dealId,
+ stage,
+}: {
+ dealId: string;
+ stage: DealStage;
+}) {
+ const [, setCloseParams] = useQueryStates(closeReasonParams);
+ const setStage = useStageMutation();
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ {/* The row underneath opens a record on click; this control does not. */}
+ <button
+ type="button"
+ onClick={(event) => event.stopPropagation()}
+ disabled={setStage.isPending}
+ className="flex min-w-0 items-center text-left hover:text-foreground disabled:opacity-50"
+ >
+ <DealStageIndicator stage={stage} />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="min-w-52"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <DropdownMenuRadioGroup
+ value={stage}
+ onValueChange={(next) => {
+ const chosen = next as DealStage;
+ if (chosen === stage) return;
+ if (LOSING_STAGES.includes(chosen)) {
+ void setCloseParams({
+ closing: dealId,
+ closingStage: chosen,
+ });
+ return;
+ }
+ setStage.mutate({ id: dealId, stage: chosen });
+ }}
+ >
+ {DEAL_STAGE_OPTIONS.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+/**
+ * Asks why a deal was lost or disqualified.
+ *
+ * Rendered once per page; which deal it is about comes from the URL, so every
+ * row can open it without each one carrying a dialog of its own.
+ */
+export function CloseReasonDialog() {
+ const reasonId = useId();
+ const [{ closing, closingStage }, setCloseParams] =
+ useQueryStates(closeReasonParams);
+ const [reason, setReason] = useState("");
+
+ const close = () => {
+ setReason("");
+ void setCloseParams({ closing: null, closingStage: null });
+ };
+
+ const setStage = useStageMutation(() => {
+ toast.success("Deal closed.");
+ close();
+ });
+
+ const stage = closingStage as DealStage | null;
+ const open = Boolean(closing && stage);
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => !next && close()}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ {stage === "CLOSED_LOST" ? "Close as lost" : "Mark as unqualified"}
+ </DialogTitle>
+ <DialogDescription>
+ {stage === "CLOSED_LOST"
+ ? "What did we lose it to? This is the only place that answer gets recorded."
+ : "Why is this not a fit? It goes on the timeline so nobody re-runs the same deal."}
+ </DialogDescription>
+ </DialogHeader>
+
+ <form
+ id="close-reason"
+ className="px-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (!closing || !stage) return;
+ setStage.mutate({ id: closing, stage, closedReason: reason });
+ }}
+ >
+ <Field>
+ <FieldLabel htmlFor={reasonId}>Reason</FieldLabel>
+ <Textarea
+ id={reasonId}
+ value={reason}
+ onChange={(event) => setReason(event.target.value)}
+ placeholder="Went with an incumbent vendor"
+ rows={3}
+ />
+ </Field>
+ </form>
+
+ <DialogFooter>
+ <Button
+ type="submit"
+ form="close-reason"
+ disabled={setStage.isPending || reason.trim() === ""}
+ >
+ {setStage.isPending ? <Spinner /> : null}
+ Save
+ </Button>
+ <Button variant="outline" onClick={close}>
+ Cancel
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/app/components/crm/stage-stepper.tsx b/apps/app/components/crm/stage-stepper.tsx
new file mode 100644
index 00000000..7677a71c
--- /dev/null
+++ b/apps/app/components/crm/stage-stepper.tsx
@@ -0,0 +1,118 @@
+"use client";
+
+import type { DealStage } from "@crm/db/enums";
+import { Button } from "@crm/ui/components/button";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { parseAsString, useQueryStates } from "nuqs";
+import { toast } from "sonner";
+import {
+ CLOSED_STAGES,
+ DealStageIndicator,
+ dealStageLabel,
+ LOSING_STAGES,
+ OPEN_STAGES,
+} from "@/components/crm/deal-stage";
+import { useTRPC } from "@/lib/trpc/client";
+
+/**
+ * The open pipeline as a row of steps, with the closing outcomes beside it.
+ *
+ * Only the four open stages are steps: `CLOSED_WON`, `CLOSED_LOST` and
+ * `UNQUALIFIED_TO_BUY` are outcomes, and drawing them as "further along the
+ * line" would say a lost deal is progress.
+ */
+export function StageStepper({
+ dealId,
+ stage,
+}: {
+ dealId: string;
+ stage: DealStage;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [, setCloseParams] = useQueryStates({
+ closing: parseAsString,
+ closingStage: parseAsString,
+ });
+
+ const setStage = useMutation(
+ trpc.deals.setStage.mutationOptions({
+ onSuccess: async (result) => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.byId.queryKey({ id: dealId }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.byId.queryKey(),
+ }),
+ ]);
+ if (result.changed) toast.success("Stage updated.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const currentIndex = OPEN_STAGES.indexOf(stage);
+ const isClosed = CLOSED_STAGES.includes(stage);
+
+ const move = (next: DealStage) => {
+ if (LOSING_STAGES.includes(next)) {
+ void setCloseParams({ closing: dealId, closingStage: next });
+ return;
+ }
+ setStage.mutate({ id: dealId, stage: next });
+ };
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-wrap items-center gap-1">
+ {OPEN_STAGES.map((option, index) => {
+ const reached = !isClosed && index <= currentIndex;
+ return (
+ <Button
+ key={option}
+ variant={reached ? "secondary" : "ghost"}
+ size="sm"
+ aria-current={option === stage ? "step" : undefined}
+ disabled={setStage.isPending}
+ onClick={() => move(option)}
+ >
+ {dealStageLabel(option)}
+ </Button>
+ );
+ })}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ {isClosed ? (
+ <>
+ <DealStageIndicator stage={stage} className="text-sm" />
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={setStage.isPending}
+ onClick={() => move("DEMO_BOOKED")}
+ >
+ Reopen
+ </Button>
+ </>
+ ) : (
+ CLOSED_STAGES.map((option) => (
+ <Button
+ key={option}
+ variant="outline"
+ size="sm"
+ disabled={setStage.isPending}
+ onClick={() => move(option)}
+ >
+ {dealStageLabel(option)}
+ </Button>
+ ))
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/app/components/crm/timeline/activity-composer.tsx b/apps/app/components/crm/timeline/activity-composer.tsx
new file mode 100644
index 00000000..4265b9e0
--- /dev/null
+++ b/apps/app/components/crm/timeline/activity-composer.tsx
@@ -0,0 +1,169 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { Input } from "@crm/ui/components/input";
+import { Spinner } from "@crm/ui/components/spinner";
+import { Textarea } from "@crm/ui/components/textarea";
+import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { useTRPC } from "@/lib/trpc/client";
+import { ActivityIcon, activityLabel } from "./activity-icon";
+import type { TimelineAnchor } from "./timeline";
+
+/** Only what a person can log. Stage changes and enrichment write themselves,
+ * and the API's create input refuses the other two for the same reason. */
+const TYPES = ["NOTE", "CALL", "EMAIL", "MEETING", "TASK"] as const;
+
+type ComposableType = (typeof TYPES)[number];
+
+export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ const [type, setType] = useState<ComposableType>("NOTE");
+ const [subject, setSubject] = useState("");
+ const [body, setBody] = useState("");
+ const [dueAt, setDueAt] = useState("");
+
+ const subjectId = useId();
+ const bodyId = useId();
+ const dueId = useId();
+
+ const isTask = type === "TASK";
+
+ const create = useMutation(
+ trpc.activities.create.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.timeline.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.timelineCounts.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.myTasks.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.dashboard.summary.queryKey(),
+ }),
+ // "Last activity" columns move whenever anything is logged.
+ queryClient.invalidateQueries({
+ queryKey: trpc.companies.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.contacts.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.deals.list.queryKey(),
+ }),
+ ]);
+ setSubject("");
+ setBody("");
+ setDueAt("");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const ready = isTask ? subject.trim() !== "" : body.trim() !== "";
+
+ return (
+ <form
+ className="flex flex-col gap-3 border-b pb-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ create.mutate({
+ ...anchor,
+ type,
+ subject: subject || undefined,
+ body: body || undefined,
+ dueAt: isTask ? dueAt || null : undefined,
+ });
+ }}
+ >
+ <ToggleGroup
+ type="single"
+ value={type}
+ onValueChange={(next) => next && setType(next as ComposableType)}
+ variant="outline"
+ size="sm"
+ >
+ {TYPES.map((option) => (
+ <ToggleGroupItem
+ key={option}
+ value={option}
+ aria-label={activityLabel(option)}
+ >
+ <ActivityIcon type={option} />
+ {activityLabel(option)}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+
+ {isTask ? (
+ <>
+ <Input
+ id={subjectId}
+ value={subject}
+ onChange={(event) => setSubject(event.target.value)}
+ placeholder="Send the security questionnaire"
+ aria-label="What needs doing"
+ autoComplete="off"
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <label htmlFor={dueId} className="text-muted-foreground text-xs">
+ Due
+ </label>
+ <Input
+ id={dueId}
+ type="date"
+ value={dueAt}
+ onChange={(event) => setDueAt(event.target.value)}
+ />
+ </div>
+ </>
+ ) : (
+ <>
+ {type !== "NOTE" ? (
+ <Input
+ id={subjectId}
+ value={subject}
+ onChange={(event) => setSubject(event.target.value)}
+ placeholder={
+ type === "CALL"
+ ? "Discovery call"
+ : type === "EMAIL"
+ ? "Re: next steps"
+ : "Product demo"
+ }
+ aria-label="Subject"
+ autoComplete="off"
+ />
+ ) : null}
+ <Textarea
+ id={bodyId}
+ value={body}
+ onChange={(event) => setBody(event.target.value)}
+ placeholder={
+ type === "NOTE"
+ ? "What happened?"
+ : "What came out of it? Anything the next person needs to know."
+ }
+ aria-label="Details"
+ rows={3}
+ />
+ </>
+ )}
+
+ <div className="flex items-center justify-end gap-2">
+ <Button type="submit" size="sm" disabled={create.isPending || !ready}>
+ {create.isPending ? <Spinner /> : null}
+ {isTask ? "Add task" : `Log ${activityLabel(type).toLowerCase()}`}
+ </Button>
+ </div>
+ </form>
+ );
+}
diff --git a/apps/app/components/crm/timeline/activity-icon.tsx b/apps/app/components/crm/timeline/activity-icon.tsx
new file mode 100644
index 00000000..1b16e526
--- /dev/null
+++ b/apps/app/components/crm/timeline/activity-icon.tsx
@@ -0,0 +1,33 @@
+import ArrowRight from "@carbon/icons-react/es/ArrowRight";
+import Chat from "@carbon/icons-react/es/Chat";
+import Email from "@carbon/icons-react/es/Email";
+import Events from "@carbon/icons-react/es/Events";
+import MagicWand from "@carbon/icons-react/es/MagicWand";
+import Phone from "@carbon/icons-react/es/Phone";
+import Task from "@carbon/icons-react/es/Task";
+import type { ActivityType } from "@crm/db/enums";
+import type { CarbonIcon } from "@crm/ui/components/icon";
+import { Icon } from "@crm/ui/components/icon";
+
+const PRESENTATION: Record<ActivityType, { icon: CarbonIcon; label: string }> =
+ {
+ NOTE: { icon: Chat, label: "Note" },
+ CALL: { icon: Phone, label: "Call" },
+ EMAIL: { icon: Email, label: "Email" },
+ MEETING: { icon: Events, label: "Meeting" },
+ TASK: { icon: Task, label: "Task" },
+ STAGE_CHANGE: { icon: ArrowRight, label: "Stage change" },
+ ENRICHMENT: { icon: MagicWand, label: "Enrichment" },
+ };
+
+export function activityLabel(type: ActivityType): string {
+ return PRESENTATION[type].label;
+}
+
+export function activityIcon(type: ActivityType): CarbonIcon {
+ return PRESENTATION[type].icon;
+}
+
+export function ActivityIcon({ type }: { type: ActivityType }) {
+ return <Icon icon={PRESENTATION[type].icon} />;
+}
diff --git a/apps/app/components/crm/timeline/timeline-entry.tsx b/apps/app/components/crm/timeline/timeline-entry.tsx
new file mode 100644
index 00000000..e1a7ba40
--- /dev/null
+++ b/apps/app/components/crm/timeline/timeline-entry.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { Checkbox } from "@crm/ui/components/checkbox";
+import { StatusIndicator } from "@crm/ui/components/status-indicator";
+import { relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { dealStageLabel } from "@/components/crm/deal-stage";
+import { RecordLink } from "@/components/crm/record-sheet/record-link";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { ActivityIcon, activityLabel } from "./activity-icon";
+
+export type TimelineEntryData =
+ RouterOutputs["activities"]["timeline"]["entries"][number];
+
+const timeFormat = new Intl.DateTimeFormat(undefined, {
+ hour: "numeric",
+ minute: "2-digit",
+});
+
+/** `{ from, to }` on a STAGE_CHANGE, read back defensively — it is `Json`. */
+function stageChange(meta: Record<string, unknown> | null) {
+ const from = typeof meta?.from === "string" ? meta.from : null;
+ const to = typeof meta?.to === "string" ? meta.to : null;
+ return from && to ? { from, to } : null;
+}
+
+export function TimelineEntry({
+ entry,
+ /** Hide the deal/contact chips on that record's own timeline. */
+ showContext = true,
+}: {
+ entry: TimelineEntryData;
+ showContext?: boolean;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ const complete = useMutation(
+ trpc.activities.complete.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.timeline.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.timelineCounts.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.activities.myTasks.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.dashboard.summary.queryKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const isTask = entry.type === "TASK";
+ const done = entry.completedAt !== null;
+ const overdue =
+ isTask &&
+ !done &&
+ entry.dueAt !== null &&
+ new Date(entry.dueAt) < new Date();
+
+ const change = entry.type === "STAGE_CHANGE" ? stageChange(entry.meta) : null;
+ const when = entry.occurredAt ?? entry.createdAt;
+
+ return (
+ <li className="flex gap-3 py-3">
+ <span className="mt-0.5 text-muted-foreground">
+ {isTask ? (
+ <Checkbox
+ checked={done}
+ disabled={complete.isPending}
+ aria-label={done ? "Mark as not done" : "Mark as done"}
+ onCheckedChange={(checked) =>
+ complete.mutate({ id: entry.id, completed: checked === true })
+ }
+ />
+ ) : (
+ <ActivityIcon type={entry.type} />
+ )}
+ </span>
+
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <span className="font-medium text-sm">
+ {change
+ ? `${dealStageLabel(change.from as never)} → ${dealStageLabel(change.to as never)}`
+ : (entry.subject ?? activityLabel(entry.type))}
+ </span>
+
+ {overdue ? (
+ <StatusIndicator
+ tone="error"
+ className="text-xs"
+ label={`Overdue ${relativeTimeFromIso(entry.dueAt)}`}
+ />
+ ) : isTask && !done && entry.dueAt ? (
+ <StatusIndicator
+ tone="info"
+ className="text-xs"
+ label={`Due ${relativeTimeFromIso(entry.dueAt)}`}
+ />
+ ) : null}
+
+ <span className="text-muted-foreground text-xs">
+ {entry.createdBy.name} · {timeFormat.format(new Date(when))}
+ </span>
+ </div>
+
+ {entry.body ? (
+ <p className="whitespace-pre-wrap text-pretty text-muted-foreground text-sm/6">
+ {entry.body}
+ </p>
+ ) : null}
+
+ {showContext && (entry.deal || entry.contact) ? (
+ <div className="flex flex-wrap items-center gap-3 text-xs">
+ {entry.deal ? (
+ <RecordLink kind="deal" id={entry.deal.id}>
+ {entry.deal.name}
+ </RecordLink>
+ ) : null}
+ {entry.contact ? (
+ <RecordLink kind="contact" id={entry.contact.id}>
+ {[entry.contact.firstName, entry.contact.lastName]
+ .filter(Boolean)
+ .join(" ")}
+ </RecordLink>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </li>
+ );
+}
diff --git a/apps/app/components/crm/timeline/timeline-search-params.ts b/apps/app/components/crm/timeline/timeline-search-params.ts
new file mode 100644
index 00000000..0fb3137e
--- /dev/null
+++ b/apps/app/components/crm/timeline/timeline-search-params.ts
@@ -0,0 +1,16 @@
+/**
+ * The timeline's filter.
+ *
+ * Component state rather than a URL param: the timeline now lives inside a
+ * record sheet, and the sheet's identity is already in `?record=`. Adding the
+ * filter there too would mean a glance at "Upcoming" becomes a history entry
+ * the back button has to walk through before it closes the sheet.
+ */
+export const TIMELINE_TABS = ["all", "notes", "upcoming", "done"] as const;
+
+export type TimelineTab = (typeof TIMELINE_TABS)[number];
+
+/** The API filter a tab maps to. `all` splits into pinned + history. */
+export function historyFilter(tab: TimelineTab) {
+ return tab === "all" ? ("history" as const) : tab;
+}
diff --git a/apps/app/components/crm/timeline/timeline.tsx b/apps/app/components/crm/timeline/timeline.tsx
new file mode 100644
index 00000000..03052615
--- /dev/null
+++ b/apps/app/components/crm/timeline/timeline.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { Spinner } from "@crm/ui/components/spinner";
+import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";
+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+import { useTRPC } from "@/lib/trpc/client";
+import { ActivityComposer } from "./activity-composer";
+import { TimelineEntry, type TimelineEntryData } from "./timeline-entry";
+import {
+ historyFilter,
+ TIMELINE_TABS,
+ type TimelineTab,
+} from "./timeline-search-params";
+
+/** Exactly one of these — a timeline is always about one record. */
+export type TimelineAnchor =
+ | { companyId: string }
+ | { contactId: string }
+ | { dealId: string };
+
+const TAB_LABELS: Record<TimelineTab, string> = {
+ all: "All",
+ notes: "Notes",
+ upcoming: "Upcoming",
+ done: "Done",
+};
+
+const dayFormat = new Intl.DateTimeFormat(undefined, {
+ weekday: "long",
+ month: "long",
+ day: "numeric",
+ year: "numeric",
+});
+
+/** Groups entries by calendar day, preserving the order they arrived in. */
+function byDay(entries: TimelineEntryData[]) {
+ const groups: { day: string; label: string; entries: TimelineEntryData[] }[] =
+ [];
+
+ for (const entry of entries) {
+ const at = new Date(entry.occurredAt ?? entry.createdAt);
+ const day = at.toDateString();
+ const last = groups[groups.length - 1];
+ if (last?.day === day) {
+ last.entries.push(entry);
+ } else {
+ groups.push({ day, label: dayFormat.format(at), entries: [entry] });
+ }
+ }
+
+ return groups;
+}
+
+/**
+ * Everything that has happened to a record, and the box for adding to it.
+ *
+ * Built as a panel that fills its tab: the composer stays put at the top,
+ * where a rep can log the call they just finished without scrolling past a
+ * year of history to reach it.
+ *
+ * A company's timeline picks up its deals' and contacts' entries for free —
+ * the API stamps `companyId` on every activity it can resolve one for, so this
+ * is one indexed range scan rather than three joins.
+ */
+export function Timeline({ anchor }: { anchor: TimelineAnchor }) {
+ const trpc = useTRPC();
+
+ const [tab, setTab] = useState<TimelineTab>("all");
+
+ const counts = useQuery(trpc.activities.timelineCounts.queryOptions(anchor));
+
+ // On the "All" tab, outstanding tasks are pinned above the history and the
+ // history excludes them, so nothing appears twice.
+ const pinned = useQuery({
+ ...trpc.activities.timeline.queryOptions({
+ ...anchor,
+ filter: "upcoming",
+ limit: 10,
+ }),
+ enabled: tab === "all",
+ });
+
+ const history = useInfiniteQuery({
+ ...trpc.activities.timeline.infiniteQueryOptions(
+ { ...anchor, filter: historyFilter(tab) },
+ { getNextPageParam: (page) => page.nextCursor ?? undefined },
+ ),
+ });
+
+ const entries = history.data?.pages.flatMap((page) => page.entries) ?? [];
+ const pinnedEntries = tab === "all" ? (pinned.data?.entries ?? []) : [];
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="shrink-0 border-b p-5">
+ <ActivityComposer anchor={anchor} />
+ </div>
+
+ <div className="flex shrink-0 items-center border-b px-5 py-2">
+ <ToggleGroup
+ type="single"
+ value={tab}
+ onValueChange={(next) => next && setTab(next as TimelineTab)}
+ variant="outline"
+ size="sm"
+ >
+ {TIMELINE_TABS.map((option) => (
+ <ToggleGroupItem key={option} value={option}>
+ {TAB_LABELS[option]}
+ {counts.data ? (
+ <span className="tabular-nums opacity-60">
+ {counts.data[option]}
+ </span>
+ ) : null}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto p-5">
+ {pinnedEntries.length > 0 ? (
+ <section>
+ <h3 className="pb-1 font-medium text-muted-foreground text-xs">
+ Outstanding
+ </h3>
+ <ul className="divide-y">
+ {pinnedEntries.map((entry) => (
+ <TimelineEntry key={entry.id} entry={entry} />
+ ))}
+ </ul>
+ </section>
+ ) : null}
+
+ {history.isPending ? (
+ <div className="flex justify-center py-6">
+ <Spinner />
+ </div>
+ ) : entries.length === 0 && pinnedEntries.length === 0 ? (
+ <p className="py-10 text-center text-muted-foreground text-xs">
+ Nothing here yet.
+ </p>
+ ) : (
+ byDay(entries).map((group) => (
+ <section key={group.day}>
+ <h3 className="pb-1 font-medium text-muted-foreground text-xs">
+ {group.label}
+ </h3>
+ <ul className="divide-y">
+ {group.entries.map((entry) => (
+ <TimelineEntry key={entry.id} entry={entry} />
+ ))}
+ </ul>
+ </section>
+ ))
+ )}
+
+ {history.hasNextPage ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start"
+ disabled={history.isFetchingNextPage}
+ onClick={() => history.fetchNextPage()}
+ >
+ {history.isFetchingNextPage ? <Spinner /> : null}
+ Show older
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/app/components/data-table/list-search-params.ts b/apps/app/components/data-table/list-search-params.ts
new file mode 100644
index 00000000..9ac2e37c
--- /dev/null
+++ b/apps/app/components/data-table/list-search-params.ts
@@ -0,0 +1,144 @@
+import type { SortDirection } from "@crm/ui/lib/table-query";
+import {
+ createLoader,
+ debounce,
+ type LoaderFunction,
+ type ParserBuilder,
+ parseAsInteger,
+ parseAsString,
+ parseAsStringLiteral,
+} from "nuqs/server";
+
+/**
+ * One parser map per list module, shared by the page (which parses
+ * `searchParams` to prefetch on the server) and the client panel (which reads
+ * the same keys through `useTableQuery`). Defining them twice is how a page
+ * ends up prefetching a different query than the one the browser then asks
+ * for — so they are defined once, here.
+ *
+ * Imported from `nuqs/server` deliberately: parsers are plain data, and this
+ * module is pulled into both a server component and a client one.
+ */
+
+const SORT_DIRECTIONS = ["asc", "desc"] as const;
+
+type StringParser = ParserBuilder<string> & { defaultValue: string };
+
+/**
+ * Base keys every list has, plus one string key per tab and facet.
+ *
+ * `TKey` is a union of literal key names rather than `string`: an index
+ * signature here would collide with `page: number` and make every setter
+ * untypeable.
+ */
+export type ListParsers<TKey extends string> = {
+ q: StringParser;
+ sort: StringParser;
+ dir: ParserBuilder<SortDirection> & { defaultValue: SortDirection };
+ page: ParserBuilder<number> & { defaultValue: number };
+} & { [K in TKey]: StringParser };
+
+export type ListSearchValues<TKey extends string> = {
+ q: string;
+ sort: string;
+ dir: SortDirection;
+ page: number;
+} & { [K in TKey]: string };
+
+/** What a list procedure receives: the shared `listInput` plus tab and facets. */
+export type ListInput<TKey extends string> = {
+ q: string;
+ sort: string;
+ dir: SortDirection;
+ page: number;
+ pageSize: number;
+} & { [K in TKey]: string };
+
+export type ListTableConfig<TTab extends string, TFacet extends string> = {
+ /** Column id sorted by default; `""` means the API's own ordering. */
+ defaultSort?: string;
+ defaultDir?: SortDirection;
+ pageSize?: number;
+ /** Query key for the tab selector, e.g. `"stage"`. */
+ tabId?: TTab;
+ /** Query keys for the facet dropdowns, e.g. `["owner", "industry"]`. */
+ facetIds?: readonly TFacet[];
+ /** Facet id → value to start on, when it should not be `"all"`. */
+ facetDefaults?: Partial<Record<TFacet, string>>;
+};
+
+export type ListSearchParams<TTab extends string, TFacet extends string> = {
+ config: ListTableConfig<TTab, TFacet> & {
+ defaultSort: string;
+ defaultDir: SortDirection;
+ pageSize: number;
+ };
+ parsers: ListParsers<TTab | TFacet>;
+ /** Server-side: `await load(searchParams)` in the page. */
+ load: LoaderFunction<ListParsers<TTab | TFacet>>;
+ /** Parsed URL values → the object the module's `list` procedure takes. */
+ toInput: (
+ values: ListSearchValues<TTab | TFacet>,
+ ) => ListInput<TTab | TFacet>;
+};
+
+export function createListSearchParams<
+ TTab extends string = never,
+ TFacet extends string = never,
+>(config: ListTableConfig<TTab, TFacet> = {}): ListSearchParams<TTab, TFacet> {
+ const {
+ defaultSort = "",
+ defaultDir = "asc",
+ pageSize = 25,
+ tabId,
+ facetIds = [],
+ facetDefaults,
+ } = config;
+
+ const extras: Record<string, StringParser> = {};
+
+ if (tabId) extras[tabId] = parseAsString.withDefault("all");
+ for (const id of facetIds) {
+ extras[id] = parseAsString.withDefault(facetDefaults?.[id] ?? "all");
+ }
+
+ const parsers = {
+ // Typing writes the URL once the user pauses. The value the input renders
+ // updates immediately regardless — nuqs returns the queued value — so this
+ // costs nothing in responsiveness; it just keeps the history clean.
+ q: parseAsString.withDefault("").withOptions({
+ limitUrlUpdates: debounce(300),
+ }),
+ sort: parseAsString.withDefault(defaultSort),
+ dir: parseAsStringLiteral(SORT_DIRECTIONS).withDefault(defaultDir),
+ // Paging is the one table change worth a Back button.
+ page: parseAsInteger.withDefault(1).withOptions({ history: "push" }),
+ ...extras,
+ } as ListParsers<TTab | TFacet>;
+
+ const keys = [...(tabId ? [tabId] : []), ...facetIds] as (TTab | TFacet)[];
+
+ return {
+ config: { ...config, defaultSort, defaultDir, pageSize },
+ parsers,
+ load: createLoader(parsers),
+ toInput: (values) => {
+ // `"all"` is passed through rather than stripped: every list procedure
+ // defaults its tab and facets to "all", so the two sides agree without
+ // either needing to know which keys are optional.
+ const selected: Record<string, string> = {};
+ for (const key of keys) {
+ selected[key] = values[key] ?? "all";
+ }
+
+ return {
+ q: values.q.trim(),
+ sort: values.sort,
+ dir: values.dir,
+ page: values.page > 0 ? values.page : 1,
+ pageSize,
+ ...selected,
+ } as ListInput<TTab | TFacet>;
+ },
+ };
+}
diff --git a/apps/app/components/data-table/use-table-query.ts b/apps/app/components/data-table/use-table-query.ts
new file mode 100644
index 00000000..2cabce4e
--- /dev/null
+++ b/apps/app/components/data-table/use-table-query.ts
@@ -0,0 +1,79 @@
+"use client";
+
+import type { TableQueryState } from "@crm/ui/lib/table-query";
+import { useQueryStates } from "nuqs";
+import { useDeferredValue } from "react";
+import type {
+ ListInput,
+ ListSearchParams,
+ ListSearchValues,
+} from "./list-search-params";
+
+export type TableQuery<TKey extends string> = {
+ /** Passed to `<DataTable query={…}>`. */
+ query: TableQueryState;
+ /** Passed to the module's `list` procedure. */
+ input: ListInput<TKey>;
+};
+
+/**
+ * Binds a module's URL parsers to the `DataTable` contract.
+ *
+ * Lives in the app rather than in `@crm/ui` because it is routing state: the
+ * design system renders the controls, the app decides what a URL means.
+ */
+export function useTableQuery<TTab extends string, TFacet extends string>(
+ searchParams: ListSearchParams<TTab, TFacet>,
+): TableQuery<TTab | TFacet> {
+ const { parsers, config, toInput } = searchParams;
+ const { defaultDir, pageSize, tabId, facetIds, facetDefaults } = config;
+
+ const [state, setState] = useQueryStates(parsers);
+ const values = state as ListSearchValues<TTab | TFacet>;
+
+ const page = values.page > 0 ? values.page : 1;
+ const tab = tabId ? values[tabId] : "all";
+
+ const filters: Record<string, string> = {};
+ if (tabId) filters[tabId] = tab;
+ for (const id of facetIds ?? []) {
+ filters[id] = values[id] ?? facetDefaults?.[id] ?? "all";
+ }
+
+ const query: TableQueryState = {
+ q: values.q,
+ sort: values.sort,
+ dir: values.dir,
+ page,
+ pageSize,
+ tab,
+ tabId,
+ filters,
+ // Every filter change resets to page 1: staying on page 7 of a result set
+ // that now has two pages shows an empty table.
+ setSearch: (value) => setState((prev) => ({ ...prev, q: value, page: 1 })),
+ toggleSort: (id) =>
+ setState((prev) =>
+ prev.sort === id
+ ? { ...prev, dir: prev.dir === "asc" ? "desc" : "asc", page: 1 }
+ : { ...prev, sort: id, dir: defaultDir, page: 1 },
+ ),
+ setSort: (id) => setState((prev) => ({ ...prev, sort: id, page: 1 })),
+ setDir: (dir) => setState((prev) => ({ ...prev, dir, page: 1 })),
+ setPage: (next) => setState((prev) => ({ ...prev, page: next })),
+ setTab: (value) => {
+ if (!tabId) return;
+ setState((prev) => ({ ...prev, [tabId]: value, page: 1 }));
+ },
+ setFilter: (id, value) =>
+ setState((prev) => ({ ...prev, [id]: value, page: 1 })),
+ };
+
+ // The search box is responsive because `q` updates on every keystroke; the
+ // fetch does not need to be. Deferring the value the query is built from lets
+ // a burst of typing collapse into a single request.
+ const deferredQ = useDeferredValue(values.q);
+ const input = toInput({ ...values, q: deferredQ });
+
+ return { query, input };
+}
diff --git a/apps/app/components/detail-sheet.tsx b/apps/app/components/detail-sheet.tsx
new file mode 100644
index 00000000..5ea007ba
--- /dev/null
+++ b/apps/app/components/detail-sheet.tsx
@@ -0,0 +1,263 @@
+"use client";
+
+import type { SheetSize } from "@crm/ui/components/sheet";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@crm/ui/components/tabs";
+import { cn } from "@crm/ui/lib/utils";
+import type { ReactNode } from "react";
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/responsive-sheet";
+
+/**
+ * The chrome every record sheet is built from.
+ *
+ * One shape for all of them — header, a strip of numbers, tabs, a scrolling
+ * body — so a rep who has opened a company knows where everything is on a deal
+ * without looking. The parts are separate components rather than props on one
+ * because the tabs' contents differ per record and a `renderX` prop for each
+ * would be worse than composing them.
+ */
+export function DetailSheet({
+ open,
+ onOpenChange,
+ size = "2xl",
+ className,
+ children,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ size?: SheetSize;
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ size={size}
+ className={cn("flex flex-col gap-0 p-0", className)}
+ >
+ {children}
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+export function DetailSheetHeader({
+ eyebrow,
+ title,
+ description,
+ media,
+ actions,
+ className,
+ children,
+}: {
+ eyebrow?: ReactNode;
+ title: ReactNode;
+ description?: ReactNode;
+ media?: ReactNode;
+ /** Buttons, wrapped so the close control never lands on top of them. */
+ actions?: ReactNode;
+ className?: string;
+ children?: ReactNode;
+}) {
+ return (
+ <SheetHeader
+ className={cn("gap-0 space-y-3 border-b p-5 pr-14", className)}
+ >
+ {eyebrow ? (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
+ {eyebrow}
+ </div>
+ ) : null}
+
+ <div className="flex items-start gap-4">
+ {media}
+ <div className="min-w-0 flex-1 space-y-1">
+ <SheetTitle size="lg" className="wrap-anywhere">
+ {title}
+ </SheetTitle>
+ {description ? (
+ <SheetDescription className="wrap-anywhere">
+ {description}
+ </SheetDescription>
+ ) : null}
+ </div>
+ </div>
+
+ {actions ? (
+ <div className="flex flex-wrap items-center gap-2">{actions}</div>
+ ) : null}
+
+ {children}
+ </SheetHeader>
+ );
+}
+
+/** A row of the four or five numbers you would otherwise go hunting for. */
+export function DetailSheetStats({
+ className,
+ children,
+}: {
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <dl className={cn("flex shrink-0 divide-x border-b", className)}>
+ {children}
+ </dl>
+ );
+}
+
+export function DetailSheetStat({
+ label,
+ className,
+ children,
+}: {
+ label: ReactNode;
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex min-w-0 flex-1 flex-col gap-1.5 px-5 py-3",
+ className,
+ )}
+ >
+ <dt className="truncate text-muted-foreground text-xs">{label}</dt>
+ <dd className="min-w-0 truncate text-sm">{children}</dd>
+ </div>
+ );
+}
+
+export type DetailSheetTab = {
+ value: string;
+ label: string;
+ /** Shown next to the label — omit rather than render a zero. */
+ count?: number | null;
+ content: ReactNode;
+};
+
+/**
+ * The tabs inside a record sheet.
+ *
+ * The active tab is component state, not a URL param: the sheet's identity is
+ * already in `?record=`, and putting the tab there too would mean every glance
+ * at "Activity" is a history entry the back button has to walk through before
+ * it closes the sheet.
+ */
+export function DetailSheetTabs({
+ tabs,
+ value,
+ onValueChange,
+ className,
+}: {
+ tabs: DetailSheetTab[];
+ value: string;
+ onValueChange: (value: string) => void;
+ className?: string;
+}) {
+ return (
+ <Tabs
+ value={value}
+ onValueChange={onValueChange}
+ className={cn("flex min-h-0 flex-1 flex-col gap-0", className)}
+ >
+ <TabsList
+ variant="line"
+ className="w-full shrink-0 justify-start gap-4 border-b px-5"
+ >
+ {tabs.map((tab) => (
+ <TabsTrigger key={tab.value} value={tab.value}>
+ {tab.label}
+ {tab.count ? (
+ <span className="tabular-nums opacity-60">{tab.count}</span>
+ ) : null}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+
+ {/*
+ * The panel does not scroll — whatever is inside it does. A tab of
+ * sections wraps itself in `DetailSheetBody`; a tab that is one long
+ * table lets the table scroll under its own pinned header. Scrolling
+ * here as well would give both of those a second scrollbar.
+ */}
+ {tabs.map((tab) => (
+ <TabsContent
+ key={tab.value}
+ value={tab.value}
+ className="flex min-h-0 flex-1 flex-col overflow-hidden outline-none"
+ >
+ {tab.content}
+ </TabsContent>
+ ))}
+ </Tabs>
+ );
+}
+
+/** The scroll container for a tab made of sections rather than one table. */
+export function DetailSheetBody({
+ className,
+ children,
+}: {
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <div
+ className={cn("flex min-h-0 flex-1 flex-col overflow-y-auto", className)}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function DetailSheetSection({
+ title,
+ action,
+ className,
+ children,
+}: {
+ title?: ReactNode;
+ action?: ReactNode;
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <section
+ className={cn("space-y-3 border-b p-5 last:border-b-0", className)}
+ >
+ {title || action ? (
+ <div className="flex items-center justify-between gap-3">
+ {title ? (
+ <h3 className="font-medium text-foreground text-sm">{title}</h3>
+ ) : (
+ <span />
+ )}
+ {action}
+ </div>
+ ) : null}
+ {children}
+ </section>
+ );
+}
+
+/** Nothing here yet, said once, the same way everywhere. */
+export function DetailSheetEmpty({ children }: { children: ReactNode }) {
+ return (
+ <p className="px-5 py-10 text-center text-muted-foreground text-xs">
+ {children}
+ </p>
+ );
+}
diff --git a/apps/app/components/mobile-nav.tsx b/apps/app/components/mobile-nav.tsx
new file mode 100644
index 00000000..b4acbb1c
--- /dev/null
+++ b/apps/app/components/mobile-nav.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import { createContext, useContext, useState } from "react";
+
+type MobileNavContextValue = {
+ open: boolean;
+ setOpen: (open: boolean) => void;
+};
+
+const MobileNavContext = createContext<MobileNavContextValue | null>(null);
+
+export function MobileNavProvider({ children }: { children: React.ReactNode }) {
+ const [open, setOpen] = useState(false);
+ return (
+ <MobileNavContext.Provider value={{ open, setOpen }}>
+ {children}
+ </MobileNavContext.Provider>
+ );
+}
+
+export function useMobileNav(): MobileNavContextValue {
+ const context = useContext(MobileNavContext);
+ if (!context) {
+ throw new Error("useMobileNav must be used within a MobileNavProvider");
+ }
+ return context;
+}
diff --git a/apps/app/components/page-shell.tsx b/apps/app/components/page-shell.tsx
new file mode 100644
index 00000000..a4d37a48
--- /dev/null
+++ b/apps/app/components/page-shell.tsx
@@ -0,0 +1,135 @@
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+import { PageTransition } from "./page-transition";
+
+function PageShell({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <PageTransition>
+ <main
+ data-slot="page-shell-scroll"
+ className="flex min-w-0 flex-1 flex-col overflow-y-auto px-4 pt-4 pb-4 md:px-6 md:pt-6 md:pb-6"
+ >
+ <div
+ data-slot="page-shell"
+ className={cn(
+ "mx-auto flex w-full min-w-0 max-w-7xl flex-1 flex-col gap-6",
+ className,
+ )}
+ {...props}
+ />
+ </main>
+ </PageTransition>
+ );
+}
+
+/**
+ * No breadcrumbs: the app is five lists and a sheet, so there is never a trail
+ * to draw. A record's own trail lives in the sheet, where the nesting is.
+ */
+function PageShellHeader({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <header
+ data-slot="page-shell-header"
+ className={cn(
+ "flex flex-col gap-3 [view-transition-name:page-header]",
+ className,
+ )}
+ {...props}
+ >
+ <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2">
+ {children}
+ </div>
+ </header>
+ );
+}
+
+function PageShellHeading({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="page-shell-heading"
+ className={cn("contents", className)}
+ {...props}
+ />
+ );
+}
+
+function PageShellTitle({ className, ...props }: React.ComponentProps<"h1">) {
+ return (
+ <h1
+ data-slot="page-shell-title"
+ className={cn(
+ "col-start-1 row-start-1 min-w-0 self-center text-balance font-medium text-2xl tracking-tight md:text-3xl",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function PageShellDescription({
+ className,
+ ...props
+}: React.ComponentProps<"p">) {
+ return (
+ <p
+ data-slot="page-shell-description"
+ className={cn(
+ "col-span-full row-start-2 text-balance text-muted-foreground text-sm",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function PageShellActions({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="page-shell-actions"
+ className={cn(
+ "col-start-2 row-start-1 flex flex-wrap items-center gap-2 self-center justify-self-end",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function PageShellContent({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="page-shell-content"
+ className={cn(
+ "@container/page-content flex flex-1 flex-col gap-6",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export {
+ PageShell,
+ PageShellActions,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellTitle,
+};
diff --git a/apps/app/components/page-transition.tsx b/apps/app/components/page-transition.tsx
new file mode 100644
index 00000000..a271d1cf
--- /dev/null
+++ b/apps/app/components/page-transition.tsx
@@ -0,0 +1,32 @@
+import type * as React from "react";
+import { ViewTransition } from "react";
+
+// Every transition is opt-in by name: "none" means the new view swaps in with
+// no animation. A page only moves when a <Link transitionTypes={[...]}> names
+// one of these, so navigation stays still by default.
+const directional = {
+ "nav-forward": "nav-forward",
+ "nav-back": "nav-back",
+ "nav-lateral": "nav-lateral",
+ default: "none",
+} as const;
+
+const enter = {
+ "nav-forward": "nav-forward",
+ "nav-back": "nav-back",
+ "nav-lateral": "nav-lateral",
+ default: "none",
+} as const;
+
+export function PageTransition({ children }: { children: React.ReactNode }) {
+ return (
+ <ViewTransition
+ enter={enter}
+ exit={directional}
+ update={directional}
+ default="none"
+ >
+ {children}
+ </ViewTransition>
+ );
+}
diff --git a/apps/app/components/responsive-sheet.tsx b/apps/app/components/responsive-sheet.tsx
new file mode 100644
index 00000000..3626c6fc
--- /dev/null
+++ b/apps/app/components/responsive-sheet.tsx
@@ -0,0 +1,171 @@
+"use client";
+
+import {
+ Drawer,
+ DrawerClose,
+ DrawerContent,
+ DrawerDescription,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ DrawerTrigger,
+} from "@crm/ui/components/drawer";
+import {
+ type SheetSize,
+ Sheet as UISheet,
+ SheetClose as UISheetClose,
+ SheetContent as UISheetContent,
+ SheetDescription as UISheetDescription,
+ SheetFooter as UISheetFooter,
+ SheetHeader as UISheetHeader,
+ SheetTitle as UISheetTitle,
+ SheetTrigger as UISheetTrigger,
+} from "@crm/ui/components/sheet";
+import { useIsMobile } from "@crm/ui/hooks/use-mobile";
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+import { createContext, useContext } from "react";
+
+/**
+ * A sheet on a desktop, a drawer on a phone, one set of imports either way.
+ *
+ * Everything in this app that would have been a sub-page is a sheet, and a
+ * 5xl panel sliding in from the right of a 390px screen is not a sheet, it is
+ * a broken page. Swapping the primitive here rather than at each call site
+ * means no screen has to know which one it got.
+ */
+const ResponsiveContext = createContext(false);
+const useResponsive = () => useContext(ResponsiveContext);
+
+type RootProps = {
+ open?: boolean;
+ defaultOpen?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ modal?: boolean;
+ children?: React.ReactNode;
+};
+
+function Sheet({ children, ...props }: RootProps) {
+ const isMobile = useIsMobile();
+ return (
+ <ResponsiveContext.Provider value={isMobile}>
+ {isMobile ? (
+ <Drawer {...props}>{children}</Drawer>
+ ) : (
+ <UISheet {...props}>{children}</UISheet>
+ )}
+ </ResponsiveContext.Provider>
+ );
+}
+
+function SheetTrigger(
+ props: React.ComponentProps<"button"> & { asChild?: boolean },
+) {
+ return useResponsive() ? (
+ <DrawerTrigger {...props} />
+ ) : (
+ <UISheetTrigger {...props} />
+ );
+}
+
+function SheetClose(
+ props: React.ComponentProps<"button"> & { asChild?: boolean },
+) {
+ return useResponsive() ? (
+ <DrawerClose {...props} />
+ ) : (
+ <UISheetClose {...props} />
+ );
+}
+
+function SheetContent({
+ children,
+ side,
+ size,
+ showCloseButton,
+ className,
+ ...props
+}: React.ComponentProps<"div"> & {
+ side?: "top" | "right" | "bottom" | "left";
+ size?: SheetSize;
+ showCloseButton?: boolean;
+}) {
+ if (useResponsive()) {
+ // A bottom drawer is otherwise content-height, so a short body (or a tab
+ // switch to a near-empty panel) collapses it and shifts the page. Pin a
+ // stable default height for every drawer app-wide; callers can still
+ // override via `className` since it merges last.
+ return (
+ <DrawerContent
+ className={cn(
+ "data-[vaul-drawer-direction=bottom]:h-[88dvh]",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </DrawerContent>
+ );
+ }
+ return (
+ <UISheetContent
+ side={side}
+ size={size}
+ showCloseButton={showCloseButton}
+ className={className}
+ {...props}
+ >
+ {children}
+ </UISheetContent>
+ );
+}
+
+function SheetHeader(props: React.ComponentProps<"div">) {
+ return useResponsive() ? (
+ <DrawerHeader {...props} />
+ ) : (
+ <UISheetHeader {...props} />
+ );
+}
+
+function SheetFooter(props: React.ComponentProps<"div">) {
+ return useResponsive() ? (
+ <DrawerFooter {...props} />
+ ) : (
+ <UISheetFooter {...props} />
+ );
+}
+
+function SheetTitle(props: {
+ className?: string;
+ size?: "default" | "lg";
+ children?: React.ReactNode;
+}) {
+ return useResponsive() ? (
+ <DrawerTitle {...props} />
+ ) : (
+ <UISheetTitle {...props} />
+ );
+}
+
+function SheetDescription(props: {
+ className?: string;
+ children?: React.ReactNode;
+}) {
+ return useResponsive() ? (
+ <DrawerDescription {...props} />
+ ) : (
+ <UISheetDescription {...props} />
+ );
+}
+
+export {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ SheetTrigger,
+};
diff --git a/apps/app/components/theme-provider.tsx b/apps/app/components/theme-provider.tsx
new file mode 100644
index 00000000..179ae36e
--- /dev/null
+++ b/apps/app/components/theme-provider.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { ThemeProvider as NextThemesProvider } from "next-themes";
+import type * as React from "react";
+
+export function ThemeProvider({
+ children,
+ ...props
+}: React.ComponentProps<typeof NextThemesProvider>) {
+ return (
+ <NextThemesProvider
+ attribute="class"
+ defaultTheme="system"
+ enableSystem
+ disableTransitionOnChange
+ {...props}
+ >
+ {children}
+ </NextThemesProvider>
+ );
+}
diff --git a/apps/app/lib/env.ts b/apps/app/lib/env.ts
new file mode 100644
index 00000000..400d0bef
--- /dev/null
+++ b/apps/app/lib/env.ts
@@ -0,0 +1,8 @@
+/**
+ * Where the NestJS API lives.
+ *
+ * Public because the browser needs it for sign-in redirects; the server uses
+ * the same value so there is only ever one origin to configure.
+ */
+export const API_URL =
+ process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:3001";
diff --git a/apps/app/lib/record-href.ts b/apps/app/lib/record-href.ts
new file mode 100644
index 00000000..d1c4c70c
--- /dev/null
+++ b/apps/app/lib/record-href.ts
@@ -0,0 +1,15 @@
+/**
+ * The URL that opens a record over a list.
+ *
+ * Records used to be pages, and links to those pages are already in Slack
+ * threads and calendar invites. The old routes still exist and redirect here,
+ * which is the only reason this is a shared helper rather than a string built
+ * where it is needed.
+ */
+export function recordHref(
+ list: "/companies" | "/contacts" | "/deals",
+ kind: "company" | "contact" | "deal",
+ id: string,
+): string {
+ return `${list}?${new URLSearchParams({ record: `${kind}:${id}` })}`;
+}
diff --git a/apps/app/lib/session.ts b/apps/app/lib/session.ts
new file mode 100644
index 00000000..accd9fc7
--- /dev/null
+++ b/apps/app/lib/session.ts
@@ -0,0 +1,19 @@
+import { auth, type Session } from "@crm/auth";
+import { headers } from "next/headers";
+import { redirect } from "next/navigation";
+import { cache } from "react";
+
+export const getSession = cache(
+ async (): Promise<Session | null> =>
+ auth.api.getSession({ headers: await headers() }),
+);
+
+export async function requireSession(): Promise<Session> {
+ const session = await getSession();
+
+ if (!session) {
+ redirect("/sign-in");
+ }
+
+ return session;
+}
diff --git a/apps/app/lib/trpc/client.tsx b/apps/app/lib/trpc/client.tsx
new file mode 100644
index 00000000..7b6ca290
--- /dev/null
+++ b/apps/app/lib/trpc/client.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import { type QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+import { createTRPCClient, httpBatchLink, type TRPCClient } from "@trpc/client";
+import {
+ createTRPCContext,
+ type TRPCOptionsProxy,
+} from "@trpc/tanstack-react-query";
+import type { AppRouter } from "api/app-router";
+import type { FC, ReactNode } from "react";
+import { useState } from "react";
+import { getQueryClient } from "./query-client";
+
+const { TRPCProvider: ContextProvider, useTRPC: useTRPCContext } =
+ createTRPCContext<AppRouter>();
+
+export const TRPCProvider: FC<{
+ children: ReactNode;
+ queryClient: QueryClient;
+ trpcClient: TRPCClient<AppRouter>;
+ keyPrefix?: never;
+}> = ContextProvider;
+
+export const useTRPC: () => TRPCOptionsProxy<AppRouter> = useTRPCContext;
+
+export function TRPCReactProvider({ children }: { children: ReactNode }) {
+ const queryClient = getQueryClient();
+ const [trpcClient] = useState(() =>
+ createTRPCClient<AppRouter>({
+ links: [
+ // Same-origin: `app/api/[...path]/route.ts` forwards to the API, so
+ // the session cookie rides along without any CORS or credentials
+ // choreography.
+ httpBatchLink({ url: "/api/trpc" }),
+ ],
+ }),
+ );
+
+ return (
+ <QueryClientProvider client={queryClient}>
+ <TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>
+ {children}
+ {process.env.NODE_ENV === "development" ? (
+ <ReactQueryDevtools initialIsOpen={false} />
+ ) : null}
+ </TRPCProvider>
+ </QueryClientProvider>
+ );
+}
diff --git a/apps/app/lib/trpc/hydrate.tsx b/apps/app/lib/trpc/hydrate.tsx
new file mode 100644
index 00000000..050e4c2a
--- /dev/null
+++ b/apps/app/lib/trpc/hydrate.tsx
@@ -0,0 +1,19 @@
+import "server-only";
+import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { getServerQueryClient } from "./server";
+
+/**
+ * Ships everything the page prefetched to the browser, so the client component
+ * inside renders with data instead of a spinner.
+ *
+ * Must be rendered after the `prefetchQuery` calls it is meant to carry —
+ * `dehydrate` is a snapshot, not a subscription.
+ */
+export function HydrateClient({ children }: { children: ReactNode }) {
+ return (
+ <HydrationBoundary state={dehydrate(getServerQueryClient())}>
+ {children}
+ </HydrationBoundary>
+ );
+}
diff --git a/apps/app/lib/trpc/query-client.ts b/apps/app/lib/trpc/query-client.ts
new file mode 100644
index 00000000..ccf253ec
--- /dev/null
+++ b/apps/app/lib/trpc/query-client.ts
@@ -0,0 +1,35 @@
+import {
+ defaultShouldDehydrateQuery,
+ QueryClient,
+} from "@tanstack/react-query";
+
+export function makeQueryClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: {
+ // Long enough that a server-prefetched query is not immediately refetched
+ // on hydration, short enough that a stale list corrects itself.
+ queries: { staleTime: 30_000 },
+ dehydrate: {
+ // Ship in-flight queries too, so a page can stream a prefetch it
+ // started but did not await.
+ shouldDehydrateQuery: (query) =>
+ defaultShouldDehydrateQuery(query) ||
+ query.state.status === "pending",
+ },
+ },
+ });
+}
+
+let browserQueryClient: QueryClient | undefined;
+
+/**
+ * One client per browser tab, a fresh one per server request — sharing a client
+ * across requests would leak one user's data into another's cache.
+ */
+export function getQueryClient(): QueryClient {
+ if (typeof window === "undefined") {
+ return makeQueryClient();
+ }
+ browserQueryClient ??= makeQueryClient();
+ return browserQueryClient;
+}
diff --git a/apps/app/lib/trpc/server.ts b/apps/app/lib/trpc/server.ts
new file mode 100644
index 00000000..07865d62
--- /dev/null
+++ b/apps/app/lib/trpc/server.ts
@@ -0,0 +1,44 @@
+import "server-only";
+import { createTRPCClient, httpBatchLink } from "@trpc/client";
+import {
+ createTRPCOptionsProxy,
+ type TRPCOptionsProxy,
+} from "@trpc/tanstack-react-query";
+import type { AppRouter } from "api/app-router";
+import { cookies } from "next/headers";
+import { cache } from "react";
+import { API_URL } from "@/lib/env";
+import { makeQueryClient } from "./query-client";
+
+/**
+ * The query client a server render prefetches into and then dehydrates.
+ * `cache` keeps it to one per request, so several `prefetchQuery` calls across
+ * a page land in the same store.
+ */
+export const getServerQueryClient = cache(makeQueryClient);
+
+/**
+ * tRPC for server components. Goes straight to the API rather than through the
+ * app's own proxy route — there is no browser in the loop, so there is no
+ * same-origin problem to solve, and one fewer hop.
+ */
+export function getServerTrpc(): TRPCOptionsProxy<AppRouter> {
+ const client = createTRPCClient<AppRouter>({
+ links: [
+ httpBatchLink({
+ url: `${API_URL}/api/trpc`,
+ headers: async () => {
+ // Forward the incoming session cookie so the API's AuthMiddleware
+ // resolves the same user this render is for.
+ const cookie = (await cookies()).toString();
+ return cookie ? { cookie } : {};
+ },
+ }),
+ ],
+ });
+
+ return createTRPCOptionsProxy<AppRouter>({
+ client,
+ queryClient: getServerQueryClient,
+ });
+}
diff --git a/apps/app/lib/trpc/types.ts b/apps/app/lib/trpc/types.ts
new file mode 100644
index 00000000..05e61a4d
--- /dev/null
+++ b/apps/app/lib/trpc/types.ts
@@ -0,0 +1,11 @@
+import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
+import type { AppRouter } from "api/app-router";
+
+/**
+ * The API's own types, reachable from anywhere in the app.
+ *
+ * Prefer these over hand-written row types: `RouterOutputs["companies"]["list"]`
+ * changes the moment the service's `select` does, which is the point.
+ */
+export type RouterInputs = inferRouterInputs<AppRouter>;
+export type RouterOutputs = inferRouterOutputs<AppRouter>;
diff --git a/apps/app/next.config.ts b/apps/app/next.config.ts
new file mode 100644
index 00000000..f9a7859d
--- /dev/null
+++ b/apps/app/next.config.ts
@@ -0,0 +1,25 @@
+import type { NextConfig } from "next";
+
+const nextConfig: NextConfig = {
+ // The @crm/* packages are just-in-time: they ship TypeScript sources, so
+ // Next has to compile them rather than treat them as prebuilt dependencies.
+ transpilePackages: ["@crm/auth", "@crm/db", "@crm/ui"],
+
+ // Prisma's runtime and the pg driver are Node-only and resolve files at
+ // runtime; bundling them breaks that. @crm/db itself is still transpiled.
+ serverExternalPackages: ["@prisma/client", "@prisma/adapter-pg", "pg"],
+
+ images: {
+ remotePatterns: [
+ // Google account avatars, which arrive as `user.image`.
+ { protocol: "https", hostname: "lh3.googleusercontent.com" },
+ ],
+ },
+
+ experimental: {
+ // The app shell uses `view-transition-name` and <Link transitionTypes>.
+ viewTransition: true,
+ },
+};
+
+export default nextConfig;
diff --git a/apps/app/package.json b/apps/app/package.json
new file mode 100644
index 00000000..ed206050
--- /dev/null
+++ b/apps/app/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "app",
+ "version": "0.1.0",
+ "private": true,
+ "scripts": {
+ "dev": "next dev",
+ "build": "next build",
+ "start": "next start",
+ "check-types": "tsc --noEmit",
+ "lint": "biome check ."
+ },
+ "dependencies": {
+ "@carbon/icons-react": "^11.82.0",
+ "@crm/auth": "workspace:*",
+ "@crm/db": "workspace:*",
+ "@crm/ui": "workspace:*",
+ "@tanstack/react-query": "^5.101.2",
+ "@trpc/client": "^11.18.0",
+ "@trpc/server": "^11.18.0",
+ "@trpc/tanstack-react-query": "^11.18.0",
+ "api": "workspace:*",
+ "better-auth": "^1.6.25",
+ "next": "16.2.12",
+ "next-themes": "^0.4.6",
+ "nuqs": "^2.8.9",
+ "react": "19.2.4",
+ "react-dom": "19.2.4",
+ "sonner": "^2.0.7",
+ "zod": "^4.4.3"
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@tailwindcss/postcss": "^4",
+ "@tanstack/react-query-devtools": "^5.101.2",
+ "@types/node": "^20",
+ "@types/react": "^19",
+ "@types/react-dom": "^19",
+ "tailwindcss": "^4",
+ "typescript": "^5"
+ },
+ "ignoreScripts": [
+ "sharp",
+ "unrs-resolver"
+ ],
+ "trustedDependencies": [
+ "sharp",
+ "unrs-resolver"
+ ]
+}
diff --git a/apps/app/postcss.config.mjs b/apps/app/postcss.config.mjs
new file mode 100644
index 00000000..a342880d
--- /dev/null
+++ b/apps/app/postcss.config.mjs
@@ -0,0 +1,2 @@
+// Single source of truth for PostCSS/Tailwind lives in @crm/ui.
+export { default } from "@crm/ui/postcss.config";
diff --git a/apps/app/proxy.ts b/apps/app/proxy.ts
new file mode 100644
index 00000000..dd8241a7
--- /dev/null
+++ b/apps/app/proxy.ts
@@ -0,0 +1,44 @@
+import { getSessionCookie } from "better-auth/cookies";
+import { type NextRequest, NextResponse } from "next/server";
+
+/**
+ * Optimistic auth routing.
+ *
+ * This only looks at whether a session cookie is *present* — no database
+ * round-trip, because proxy runs on prefetches too. The real check lives in
+ * `requireSession()`, which every protected page calls.
+ *
+ * Deliberately one-directional. Turning anonymous traffic away from protected
+ * routes is safe to guess at: the worst case is a redirect the authoritative
+ * check would have made anyway. Turning cookie-bearing traffic away from
+ * `/sign-in` is not, because a cookie can be present and still not resolve to a
+ * session — expired, database reset, secret rotated, database down. Then this
+ * bounces the browser to `/`, `requireSession()` bounces it straight back to
+ * `/sign-in`, and neither side ever wins. Sending genuinely signed-in users off
+ * `/sign-in` belongs on the sign-in page, where the session can be verified.
+ */
+export function proxy(request: NextRequest) {
+ const isSignedIn = getSessionCookie(request) !== null;
+ const isSignInPage = request.nextUrl.pathname === "/sign-in";
+
+ if (!isSignedIn && !isSignInPage) {
+ return NextResponse.redirect(new URL("/sign-in", request.nextUrl));
+ }
+
+ return NextResponse.next();
+}
+
+export const config = {
+ // Static assets are excluded by extension rather than by name: the icon set
+ // in `public/` (favicon.svg, favicon-96x96.png, apple-touch-icon.png,
+ // site.webmanifest, web-app-manifest-*.png) is fetched by the browser with no
+ // regard for auth, and redirecting those to /sign-in serves HTML where an
+ // image or a manifest was expected.
+ //
+ // `/api/*` is excluded for the same reason: it is the passthrough to the
+ // NestJS API, which does its own auth and answers with a 401. A caller
+ // expecting JSON should get that, not a 307 to a sign-in page.
+ matcher: [
+ "/((?!api|_next/static|_next/image|.*\\.(?:ico|png|svg|jpg|jpeg|gif|webp|webmanifest)$).*)",
+ ],
+};
diff --git a/apps/app/public/apple-touch-icon.png b/apps/app/public/apple-touch-icon.png
new file mode 100644
index 00000000..145bc407
Binary files /dev/null and b/apps/app/public/apple-touch-icon.png differ
diff --git a/apps/app/public/favicon-96x96.png b/apps/app/public/favicon-96x96.png
new file mode 100644
index 00000000..20a5bd2d
Binary files /dev/null and b/apps/app/public/favicon-96x96.png differ
diff --git a/apps/app/public/favicon.ico b/apps/app/public/favicon.ico
new file mode 100644
index 00000000..712b9754
Binary files /dev/null and b/apps/app/public/favicon.ico differ
diff --git a/apps/app/public/favicon.svg b/apps/app/public/favicon.svg
new file mode 100644
index 00000000..4b7f78ce
--- /dev/null
+++ b/apps/app/public/favicon.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" width="1000" height="1000"><g clip-path="url(#SvgjsClipPath1010)"><rect width="1000" height="1000" fill="#ffffff"></rect><g transform="matrix(12.5,0,0,12.5,150,150)"><svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" width="56" height="56"><svg width="56" height="56" viewBox="0 0 56 56" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M41 13.3327L39.3682 12.16L28.5853 4.41866C28.2368 4.16845 27.7675 4.16844 27.419 4.41863L2.41685 22.3661C2.15517 22.5539 2 22.8563 2 23.1784V32.8194C2 33.1415 2.15515 33.4439 2.41681 33.6317L27.4189 51.5813C27.7675 51.8315 28.2368 51.8315 28.5854 51.5812L53.5833 33.6317C53.8449 33.4439 54 33.1415 54 32.8194V23.1784C54 22.8563 53.8448 22.5539 53.5832 22.3661L41 13.3327ZM27.419 9.11825C27.7675 8.86804 28.2368 8.86802 28.5854 9.11822L34.9638 13.6969C35.5198 14.096 35.5195 14.9232 34.9633 15.322L31.9378 17.4913C31.7156 17.6504 31.4167 17.6502 31.1947 17.4908L28.5853 15.6178C28.2368 15.3676 27.7675 15.3676 27.419 15.6178L18.7338 21.8529C18.178 22.2519 18.178 23.0787 18.7339 23.4776L21.1661 25.2235L24.4382 27.5755L27.4188 29.7149C27.7674 29.9651 28.2368 29.965 28.5854 29.7146L37.2698 23.4751C37.8251 23.0761 37.8252 22.25 37.2699 21.8509L35.2116 20.3717C35.0294 20.2407 35.0296 19.9695 35.2121 19.8389L38.7873 17.2754C39.1358 17.0255 39.6049 17.0257 39.9532 17.2758L46.3287 21.8531C46.8844 22.252 46.8844 23.0786 46.3288 23.4777L43.3017 25.6513L28.5875 36.2167C28.239 36.467 27.7696 36.467 27.4211 36.2168L19.9104 30.8253L16.6382 28.4777L12.7026 25.6535L9.67725 23.48C9.12177 23.0809 9.12192 22.2544 9.67753 21.8555L27.419 9.11825Z" fill="#16171B"></path>
+</svg></svg></g></g><defs><clipPath id="SvgjsClipPath1010"><rect width="1000" height="1000" x="0" y="0" rx="350" ry="350"></rect></clipPath></defs></svg>
\ No newline at end of file
diff --git a/apps/app/public/site.webmanifest b/apps/app/public/site.webmanifest
new file mode 100644
index 00000000..60c94353
--- /dev/null
+++ b/apps/app/public/site.webmanifest
@@ -0,0 +1,21 @@
+{
+ "name": "Comp AI CRM",
+ "short_name": "Comp AI CRM",
+ "icons": [
+ {
+ "src": "/web-app-manifest-192x192.png",
+ "sizes": "192x192",
+ "type": "image/png",
+ "purpose": "maskable"
+ },
+ {
+ "src": "/web-app-manifest-512x512.png",
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "maskable"
+ }
+ ],
+ "theme_color": "#ffffff",
+ "background_color": "#ffffff",
+ "display": "standalone"
+}
diff --git a/apps/app/public/web-app-manifest-192x192.png b/apps/app/public/web-app-manifest-192x192.png
new file mode 100644
index 00000000..1cc01ee0
Binary files /dev/null and b/apps/app/public/web-app-manifest-192x192.png differ
diff --git a/apps/app/public/web-app-manifest-512x512.png b/apps/app/public/web-app-manifest-512x512.png
new file mode 100644
index 00000000..caae0682
Binary files /dev/null and b/apps/app/public/web-app-manifest-512x512.png differ
diff --git a/apps/app/tsconfig.json b/apps/app/tsconfig.json
new file mode 100644
index 00000000..6bf93e30
--- /dev/null
+++ b/apps/app/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "@crm/typescript-config/nextjs.json",
+ "compilerOptions": {
+ // `api/app-router` re-exports the router classes as types, so tsc walks
+ // into apps/api and meets NestJS's legacy decorators. Nothing in this app
+ // uses a decorator; this is purely so the imported sources parse.
+ "experimentalDecorators": true,
+ "paths": {
+ "@/*": ["./*"]
+ }
+ },
+ "include": [
+ "next-env.d.ts",
+ "**/*.ts",
+ "**/*.tsx",
+ ".next/types/**/*.ts",
+ ".next/dev/types/**/*.ts",
+ "**/*.mts"
+ ],
+ "exclude": ["node_modules"]
+}
diff --git a/apps/app/turbo.json b/apps/app/turbo.json
new file mode 100644
index 00000000..d75f2a47
--- /dev/null
+++ b/apps/app/turbo.json
@@ -0,0 +1,32 @@
+{
+ "$schema": "https://turborepo.dev/schema.json",
+ "extends": ["//"],
+ "tasks": {
+ "build": {
+ "dependsOn": ["^build"],
+ "inputs": ["$TURBO_DEFAULT$", ".env*"],
+ "outputs": [".next/**", "!.next/cache/**", "!.next/dev/**"],
+ "env": ["NEXT_PUBLIC_API_URL", "NEXT_PUBLIC_AUTH_URL"],
+ "passThroughEnv": [
+ "AUTH_COOKIE_DOMAIN",
+ "AUTH_TRUSTED_ORIGINS",
+ "BETTER_AUTH_SECRET",
+ "BETTER_AUTH_URL",
+ "DATABASE_URL"
+ ]
+ },
+ "dev": {
+ "cache": false,
+ "persistent": true,
+ "passThroughEnv": [
+ "AUTH_COOKIE_DOMAIN",
+ "AUTH_TRUSTED_ORIGINS",
+ "BETTER_AUTH_SECRET",
+ "BETTER_AUTH_URL",
+ "DATABASE_URL",
+ "NEXT_PUBLIC_API_URL",
+ "NEXT_PUBLIC_AUTH_URL"
+ ]
+ }
+ }
+}
diff --git a/apps/docs/.gitignore b/apps/docs/.gitignore
deleted file mode 100644
index f886745c..00000000
--- a/apps/docs/.gitignore
+++ /dev/null
@@ -1,36 +0,0 @@
-# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
-
-# dependencies
-/node_modules
-/.pnp
-.pnp.js
-.yarn/install-state.gz
-
-# testing
-/coverage
-
-# next.js
-/.next/
-/out/
-
-# production
-/build
-
-# misc
-.DS_Store
-*.pem
-
-# debug
-npm-debug.log*
-yarn-debug.log*
-yarn-error.log*
-
-# env files (can opt-in for commiting if needed)
-.env*
-
-# vercel
-.vercel
-
-# typescript
-*.tsbuildinfo
-next-env.d.ts
diff --git a/apps/docs/README.md b/apps/docs/README.md
deleted file mode 100644
index a98bfa81..00000000
--- a/apps/docs/README.md
+++ /dev/null
@@ -1,36 +0,0 @@
-This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/create-next-app).
-
-## Getting Started
-
-First, run the development server:
-
-```bash
-npm run dev
-# or
-yarn dev
-# or
-pnpm dev
-# or
-bun dev
-```
-
-Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
-
-You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
-
-This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load Inter, a custom Google Font.
-
-## Learn More
-
-To learn more about Next.js, take a look at the following resources:
-
-- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
-- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
-
-You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
-
-## Deploy on Vercel
-
-The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
-
-Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
diff --git a/apps/docs/app/favicon.ico b/apps/docs/app/favicon.ico
deleted file mode 100644
index 718d6fea..00000000
Binary files a/apps/docs/app/favicon.ico and /dev/null differ
diff --git a/apps/docs/app/fonts/GeistMonoVF.woff b/apps/docs/app/fonts/GeistMonoVF.woff
deleted file mode 100644
index f2ae185c..00000000
Binary files a/apps/docs/app/fonts/GeistMonoVF.woff and /dev/null differ
diff --git a/apps/docs/app/fonts/GeistVF.woff b/apps/docs/app/fonts/GeistVF.woff
deleted file mode 100644
index 1b62daac..00000000
Binary files a/apps/docs/app/fonts/GeistVF.woff and /dev/null differ
diff --git a/apps/docs/app/globals.css b/apps/docs/app/globals.css
deleted file mode 100644
index 6af7ecbb..00000000
--- a/apps/docs/app/globals.css
+++ /dev/null
@@ -1,50 +0,0 @@
-:root {
- --background: #ffffff;
- --foreground: #171717;
-}
-
-@media (prefers-color-scheme: dark) {
- :root {
- --background: #0a0a0a;
- --foreground: #ededed;
- }
-}
-
-html,
-body {
- max-width: 100vw;
- overflow-x: hidden;
-}
-
-body {
- color: var(--foreground);
- background: var(--background);
-}
-
-* {
- box-sizing: border-box;
- padding: 0;
- margin: 0;
-}
-
-a {
- color: inherit;
- text-decoration: none;
-}
-
-.imgDark {
- display: none;
-}
-
-@media (prefers-color-scheme: dark) {
- html {
- color-scheme: dark;
- }
-
- .imgLight {
- display: none;
- }
- .imgDark {
- display: unset;
- }
-}
diff --git a/apps/docs/app/layout.tsx b/apps/docs/app/layout.tsx
deleted file mode 100644
index 84695375..00000000
--- a/apps/docs/app/layout.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { Metadata } from "next";
-import localFont from "next/font/local";
-import "./globals.css";
-
-const geistSans = localFont({
- src: "./fonts/GeistVF.woff",
- variable: "--font-geist-sans",
-});
-const geistMono = localFont({
- src: "./fonts/GeistMonoVF.woff",
- variable: "--font-geist-mono",
-});
-
-export const metadata: Metadata = {
- title: "Create Next App",
- description: "Generated by create next app",
-};
-
-export default function RootLayout({
- children,
-}: Readonly<{
- children: React.ReactNode;
-}>) {
- return (
- <html lang="en">
- <body className={`${geistSans.variable} ${geistMono.variable}`}>
- {children}
- </body>
- </html>
- );
-}
diff --git a/apps/docs/app/page.module.css b/apps/docs/app/page.module.css
deleted file mode 100644
index 6108b60b..00000000
--- a/apps/docs/app/page.module.css
+++ /dev/null
@@ -1,186 +0,0 @@
-.page {
- --gray-rgb: 0, 0, 0;
- --gray-alpha-200: rgba(var(--gray-rgb), 0.08);
- --gray-alpha-100: rgba(var(--gray-rgb), 0.05);
-
- --button-primary-hover: #383838;
- --button-secondary-hover: #f2f2f2;
-
- display: grid;
- grid-template-rows: 20px 1fr 20px;
- align-items: center;
- justify-items: center;
- min-height: 100svh;
- padding: 80px;
- gap: 64px;
- font-synthesis: none;
-}
-
-@media (prefers-color-scheme: dark) {
- .page {
- --gray-rgb: 255, 255, 255;
- --gray-alpha-200: rgba(var(--gray-rgb), 0.145);
- --gray-alpha-100: rgba(var(--gray-rgb), 0.06);
-
- --button-primary-hover: #ccc;
- --button-secondary-hover: #1a1a1a;
- }
-}
-
-.main {
- display: flex;
- flex-direction: column;
- gap: 32px;
- grid-row-start: 2;
-}
-
-.main ol {
- font-family: var(--font-geist-mono);
- padding-left: 0;
- margin: 0;
- font-size: 14px;
- line-height: 24px;
- letter-spacing: -0.01em;
- list-style-position: inside;
-}
-
-.main li:not(:last-of-type) {
- margin-bottom: 8px;
-}
-
-.main code {
- font-family: inherit;
- background: var(--gray-alpha-100);
- padding: 2px 4px;
- border-radius: 4px;
- font-weight: 600;
-}
-
-.ctas {
- display: flex;
- gap: 16px;
-}
-
-.ctas a {
- appearance: none;
- border-radius: 128px;
- height: 48px;
- padding: 0 20px;
- font-family: var(--font-geist-sans);
- border: 1px solid transparent;
- transition: background 0.2s, color 0.2s, border-color 0.2s;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 16px;
- line-height: 20px;
- font-weight: 500;
-}
-
-a.primary {
- background: var(--foreground);
- color: var(--background);
- gap: 8px;
-}
-
-a.secondary {
- border-color: var(--gray-alpha-200);
- min-width: 180px;
-}
-
-button.secondary {
- appearance: none;
- border-radius: 128px;
- height: 48px;
- padding: 0 20px;
- font-family: var(--font-geist-sans);
- border: 1px solid transparent;
- transition: background 0.2s, color 0.2s, border-color 0.2s;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 16px;
- line-height: 20px;
- font-weight: 500;
- background: transparent;
- border-color: var(--gray-alpha-200);
- min-width: 180px;
-}
-
-.footer {
- font-family: var(--font-geist-sans);
- grid-row-start: 3;
- display: flex;
- gap: 24px;
-}
-
-.footer a {
- display: flex;
- align-items: center;
- gap: 8px;
-}
-
-.footer img {
- flex-shrink: 0;
-}
-
-/* Enable hover only on non-touch devices */
-@media (hover: hover) and (pointer: fine) {
- a.primary:hover {
- background: var(--button-primary-hover);
- border-color: transparent;
- }
-
- a.secondary:hover {
- background: var(--button-secondary-hover);
- border-color: transparent;
- }
-
- .footer a:hover {
- text-decoration: underline;
- text-underline-offset: 4px;
- }
-}
-
-@media (max-width: 600px) {
- .page {
- padding: 32px;
- padding-bottom: 80px;
- }
-
- .main {
- align-items: center;
- }
-
- .main ol {
- text-align: center;
- }
-
- .ctas {
- flex-direction: column;
- }
-
- .ctas a {
- font-size: 14px;
- height: 40px;
- padding: 0 16px;
- }
-
- a.secondary {
- min-width: auto;
- }
-
- .footer {
- flex-wrap: wrap;
- align-items: center;
- justify-content: center;
- }
-}
-
-@media (prefers-color-scheme: dark) {
- .logo {
- filter: invert();
- }
-}
diff --git a/apps/docs/app/page.tsx b/apps/docs/app/page.tsx
deleted file mode 100644
index efb86f08..00000000
--- a/apps/docs/app/page.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import Image, { type ImageProps } from "next/image";
-import { Button } from "@repo/ui/button";
-import styles from "./page.module.css";
-
-type Props = Omit<ImageProps, "src"> & {
- srcLight: string;
- srcDark: string;
-};
-
-const ThemeImage = (props: Props) => {
- const { srcLight, srcDark, ...rest } = props;
-
- return (
- <>
- <Image {...rest} src={srcLight} className="imgLight" />
- <Image {...rest} src={srcDark} className="imgDark" />
- </>
- );
-};
-
-export default function Home() {
- return (
- <div className={styles.page}>
- <main className={styles.main}>
- <ThemeImage
- className={styles.logo}
- srcLight="turborepo-dark.svg"
- srcDark="turborepo-light.svg"
- alt="Turborepo logo"
- width={180}
- height={38}
- priority
- />
- <ol>
- <li>
- Get started by editing <code>apps/docs/app/page.tsx</code>
- </li>
- <li>Save and see your changes instantly.</li>
- </ol>
-
- <div className={styles.ctas}>
- <a
- className={styles.primary}
- href="https://vercel.com/new/clone?demo-description=Learn+to+implement+a+monorepo+with+a+two+Next.js+sites+that+has+installed+three+local+packages.&demo-image=%2F%2Fimages.ctfassets.net%2Fe5382hct74si%2F4K8ZISWAzJ8X1504ca0zmC%2F0b21a1c6246add355e55816278ef54bc%2FBasic.png&demo-title=Monorepo+with+Turborepo&demo-url=https%3A%2F%2Fexamples-basic-web.vercel.sh%2F&from=templates&project-name=Monorepo+with+Turborepo&repository-name=monorepo-turborepo&repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fturborepo%2Ftree%2Fmain%2Fexamples%2Fbasic&root-directory=apps%2Fdocs&skippable-integrations=1&teamSlug=vercel&utm_source=create-turbo"
- target="_blank"
- rel="noopener noreferrer"
- >
- <Image
- className={styles.logo}
- src="/vercel.svg"
- alt="Vercel logomark"
- width={20}
- height={20}
- />
- Deploy now
- </a>
- <a
- href="https://turborepo.dev/docs?utm_source"
- target="_blank"
- rel="noopener noreferrer"
- className={styles.secondary}
- >
- Read our docs
- </a>
- </div>
- <Button appName="docs" className={styles.secondary}>
- Open alert
- </Button>
- </main>
- <footer className={styles.footer}>
- <a
- href="https://vercel.com/templates?search=turborepo&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
- target="_blank"
- rel="noopener noreferrer"
- >
- <Image
- aria-hidden
- src="/window.svg"
- alt="Window icon"
- width={16}
- height={16}
- />
- Examples
- </a>
- <a
- href="https://turborepo.dev?utm_source=create-turbo"
- target="_blank"
- rel="noopener noreferrer"
- >
- <Image
- aria-hidden
- src="/globe.svg"
- alt="Globe icon"
- width={16}
- height={16}
- />
- Go to turborepo.dev →
- </a>
- </footer>
- </div>
- );
-}
diff --git a/apps/docs/eslint.config.js b/apps/docs/eslint.config.js
deleted file mode 100644
index 47b0670b..00000000
--- a/apps/docs/eslint.config.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import { nextJsConfig } from "@repo/eslint-config/next-js";
-
-/** @type {import("eslint").Linter.Config[]} */
-export default nextJsConfig;
diff --git a/apps/docs/next.config.js b/apps/docs/next.config.js
deleted file mode 100644
index 4678774e..00000000
--- a/apps/docs/next.config.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/** @type {import('next').NextConfig} */
-const nextConfig = {};
-
-export default nextConfig;
diff --git a/apps/docs/package.json b/apps/docs/package.json
deleted file mode 100644
index 21f31c00..00000000
--- a/apps/docs/package.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "name": "docs",
- "version": "0.1.0",
- "type": "module",
- "private": true,
- "scripts": {
- "dev": "next dev --port 3001",
- "build": "next build",
- "start": "next start",
- "lint": "eslint --max-warnings 0",
- "check-types": "next typegen && tsc --noEmit"
- },
- "dependencies": {
- "@repo/ui": "*",
- "next": "16.2.0",
- "react": "^19.2.0",
- "react-dom": "^19.2.0"
- },
- "devDependencies": {
- "@repo/eslint-config": "*",
- "@repo/typescript-config": "*",
- "@types/node": "^22.15.3",
- "@types/react": "19.2.2",
- "@types/react-dom": "19.2.2",
- "eslint": "^9.39.1",
- "typescript": "5.9.2"
- }
-}
diff --git a/apps/docs/public/file-text.svg b/apps/docs/public/file-text.svg
deleted file mode 100644
index 9cfb3c98..00000000
--- a/apps/docs/public/file-text.svg
+++ /dev/null
@@ -1,3 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path fill-rule="evenodd" clip-rule="evenodd" d="M14.5 13.5V6.5V5.41421C14.5 5.149 14.3946 4.89464 14.2071 4.70711L9.79289 0.292893C9.60536 0.105357 9.351 0 9.08579 0H8H3H1.5V1.5V13.5C1.5 14.8807 2.61929 16 4 16H12C13.3807 16 14.5 14.8807 14.5 13.5ZM13 13.5V6.5H9.5H8V5V1.5H3V13.5C3 14.0523 3.44772 14.5 4 14.5H12C12.5523 14.5 13 14.0523 13 13.5ZM9.5 5V2.12132L12.3787 5H9.5ZM5.13 5.00062H4.505V6.25062H5.13H6H6.625V5.00062H6H5.13ZM4.505 8H5.13H11H11.625V9.25H11H5.13H4.505V8ZM5.13 11H4.505V12.25H5.13H11H11.625V11H11H5.13Z" fill="#666666"/>
-</svg>
diff --git a/apps/docs/public/globe.svg b/apps/docs/public/globe.svg
deleted file mode 100644
index 4230a3d2..00000000
--- a/apps/docs/public/globe.svg
+++ /dev/null
@@ -1,10 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
-<g clip-path="url(#clip0_868_525)">
-<path fill-rule="evenodd" clip-rule="evenodd" d="M10.268 14.0934C11.9051 13.4838 13.2303 12.2333 13.9384 10.6469C13.1192 10.7941 12.2138 10.9111 11.2469 10.9925C11.0336 12.2005 10.695 13.2621 10.268 14.0934ZM8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM8.48347 14.4823C8.32384 14.494 8.16262 14.5 8 14.5C7.83738 14.5 7.67616 14.494 7.51654 14.4823C7.5132 14.4791 7.50984 14.4759 7.50647 14.4726C7.2415 14.2165 6.94578 13.7854 6.67032 13.1558C6.41594 12.5744 6.19979 11.8714 6.04101 11.0778C6.67605 11.1088 7.33104 11.125 8 11.125C8.66896 11.125 9.32395 11.1088 9.95899 11.0778C9.80021 11.8714 9.58406 12.5744 9.32968 13.1558C9.05422 13.7854 8.7585 14.2165 8.49353 14.4726C8.49016 14.4759 8.4868 14.4791 8.48347 14.4823ZM11.4187 9.72246C12.5137 9.62096 13.5116 9.47245 14.3724 9.28806C14.4561 8.87172 14.5 8.44099 14.5 8C14.5 7.55901 14.4561 7.12828 14.3724 6.71194C13.5116 6.52755 12.5137 6.37904 11.4187 6.27753C11.4719 6.83232 11.5 7.40867 11.5 8C11.5 8.59133 11.4719 9.16768 11.4187 9.72246ZM10.1525 6.18401C10.2157 6.75982 10.25 7.36805 10.25 8C10.25 8.63195 10.2157 9.24018 10.1525 9.81598C9.46123 9.85455 8.7409 9.875 8 9.875C7.25909 9.875 6.53877 9.85455 5.84749 9.81598C5.7843 9.24018 5.75 8.63195 5.75 8C5.75 7.36805 5.7843 6.75982 5.84749 6.18401C6.53877 6.14545 7.25909 6.125 8 6.125C8.74091 6.125 9.46123 6.14545 10.1525 6.18401ZM11.2469 5.00748C12.2138 5.08891 13.1191 5.20593 13.9384 5.35306C13.2303 3.7667 11.9051 2.51622 10.268 1.90662C10.695 2.73788 11.0336 3.79953 11.2469 5.00748ZM8.48347 1.51771C8.4868 1.52089 8.49016 1.52411 8.49353 1.52737C8.7585 1.78353 9.05422 2.21456 9.32968 2.84417C9.58406 3.42562 9.80021 4.12856 9.95899 4.92219C9.32395 4.89118 8.66896 4.875 8 4.875C7.33104 4.875 6.67605 4.89118 6.04101 4.92219C6.19978 4.12856 6.41594 3.42562 6.67032 2.84417C6.94578 2.21456 7.2415 1.78353 7.50647 1.52737C7.50984 1.52411 7.51319 1.52089 7.51653 1.51771C7.67615 1.50597 7.83738 1.5 8 1.5C8.16262 1.5 8.32384 1.50597 8.48347 1.51771ZM5.73202 1.90663C4.0949 2.51622 2.76975 3.7667 2.06159 5.35306C2.88085 5.20593 3.78617 5.08891 4.75309 5.00748C4.96639 3.79953 5.30497 2.73788 5.73202 1.90663ZM4.58133 6.27753C3.48633 6.37904 2.48837 6.52755 1.62761 6.71194C1.54392 7.12828 1.5 7.55901 1.5 8C1.5 8.44099 1.54392 8.87172 1.62761 9.28806C2.48837 9.47245 3.48633 9.62096 4.58133 9.72246C4.52807 9.16768 4.5 8.59133 4.5 8C4.5 7.40867 4.52807 6.83232 4.58133 6.27753ZM4.75309 10.9925C3.78617 10.9111 2.88085 10.7941 2.06159 10.6469C2.76975 12.2333 4.0949 13.4838 5.73202 14.0934C5.30497 13.2621 4.96639 12.2005 4.75309 10.9925Z" fill="#666666"/>
-</g>
-<defs>
-<clipPath id="clip0_868_525">
-<rect width="16" height="16" fill="white"/>
-</clipPath>
-</defs>
-</svg>
diff --git a/apps/docs/public/next.svg b/apps/docs/public/next.svg
deleted file mode 100644
index 5174b28c..00000000
--- a/apps/docs/public/next.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
\ No newline at end of file
diff --git a/apps/docs/public/turborepo-dark.svg b/apps/docs/public/turborepo-dark.svg
deleted file mode 100644
index dae38fed..00000000
--- a/apps/docs/public/turborepo-dark.svg
+++ /dev/null
@@ -1,19 +0,0 @@
-<svg width="473" height="76" viewBox="0 0 473 76" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path d="M130.998 30.6565V22.3773H91.0977V30.6565H106.16V58.1875H115.935V30.6565H130.998Z" fill="black"/>
-<path d="M153.542 58.7362C165.811 58.7362 172.544 52.5018 172.544 42.2275V22.3773H162.768V41.2799C162.768 47.0155 159.776 50.2574 153.542 50.2574C147.307 50.2574 144.315 47.0155 144.315 41.2799V22.3773H134.539V42.2275C134.539 52.5018 141.272 58.7362 153.542 58.7362Z" fill="black"/>
-<path d="M187.508 46.3173H197.234L204.914 58.1875H216.136L207.458 45.2699C212.346 43.5243 215.338 39.634 215.338 34.3473C215.338 26.6665 209.603 22.3773 200.874 22.3773H177.732V58.1875H187.508V46.3173ZM187.508 38.5867V30.5568H200.376C203.817 30.5568 205.712 32.053 205.712 34.5967C205.712 36.9907 203.817 38.5867 200.376 38.5867H187.508Z" fill="black"/>
-<path d="M219.887 58.1875H245.472C253.452 58.1875 258.041 54.397 258.041 48.0629C258.041 43.8235 255.348 40.9308 252.156 39.634C254.35 38.5867 257.043 36.0929 257.043 32.1528C257.043 25.8187 252.555 22.3773 244.625 22.3773H219.887V58.1875ZM229.263 36.3922V30.3074H243.627C246.32 30.3074 247.817 31.3548 247.817 33.3498C247.817 35.3448 246.32 36.3922 243.627 36.3922H229.263ZM229.263 43.7238H244.525C247.168 43.7238 248.615 45.0205 248.615 46.9657C248.615 48.9108 247.168 50.2075 244.525 50.2075H229.263V43.7238Z" fill="black"/>
-<path d="M281.942 21.7788C269.423 21.7788 260.396 29.6092 260.396 40.2824C260.396 50.9557 269.423 58.786 281.942 58.786C294.461 58.786 303.438 50.9557 303.438 40.2824C303.438 29.6092 294.461 21.7788 281.942 21.7788ZM281.942 30.2575C288.525 30.2575 293.463 34.1478 293.463 40.2824C293.463 46.417 288.525 50.3073 281.942 50.3073C275.359 50.3073 270.421 46.417 270.421 40.2824C270.421 34.1478 275.359 30.2575 281.942 30.2575Z" fill="black"/>
-<path d="M317.526 46.3173H327.251L334.932 58.1875H346.154L337.476 45.2699C342.364 43.5243 345.356 39.634 345.356 34.3473C345.356 26.6665 339.62 22.3773 330.892 22.3773H307.75V58.1875H317.526V46.3173ZM317.526 38.5867V30.5568H330.394C333.835 30.5568 335.73 32.053 335.73 34.5967C335.73 36.9907 333.835 38.5867 330.394 38.5867H317.526Z" fill="black"/>
-<path d="M349.904 22.3773V58.1875H384.717V49.9083H359.48V44.0729H381.874V35.9932H359.48V30.6565H384.717V22.3773H349.904Z" fill="black"/>
-<path d="M399.204 46.7662H412.221C420.95 46.7662 426.685 42.5767 426.685 34.5967C426.685 26.5668 420.95 22.3773 412.221 22.3773H389.428V58.1875H399.204V46.7662ZM399.204 38.6365V30.5568H411.673C415.164 30.5568 417.059 32.053 417.059 34.5967C417.059 37.0904 415.164 38.6365 411.673 38.6365H399.204Z" fill="black"/>
-<path d="M450.948 21.7788C438.43 21.7788 429.402 29.6092 429.402 40.2824C429.402 50.9557 438.43 58.786 450.948 58.786C463.467 58.786 472.444 50.9557 472.444 40.2824C472.444 29.6092 463.467 21.7788 450.948 21.7788ZM450.948 30.2575C457.532 30.2575 462.469 34.1478 462.469 40.2824C462.469 46.417 457.532 50.3073 450.948 50.3073C444.365 50.3073 439.427 46.417 439.427 40.2824C439.427 34.1478 444.365 30.2575 450.948 30.2575Z" fill="black"/>
-<path d="M38.5017 18.0956C27.2499 18.0956 18.0957 27.2498 18.0957 38.5016C18.0957 49.7534 27.2499 58.9076 38.5017 58.9076C49.7535 58.9076 58.9077 49.7534 58.9077 38.5016C58.9077 27.2498 49.7535 18.0956 38.5017 18.0956ZM38.5017 49.0618C32.6687 49.0618 27.9415 44.3346 27.9415 38.5016C27.9415 32.6686 32.6687 27.9414 38.5017 27.9414C44.3347 27.9414 49.0619 32.6686 49.0619 38.5016C49.0619 44.3346 44.3347 49.0618 38.5017 49.0618Z" fill="black"/>
-<path fill-rule="evenodd" clip-rule="evenodd" d="M40.2115 14.744V7.125C56.7719 8.0104 69.9275 21.7208 69.9275 38.5016C69.9275 55.2824 56.7719 68.989 40.2115 69.8782V62.2592C52.5539 61.3776 62.3275 51.0644 62.3275 38.5016C62.3275 25.9388 52.5539 15.6256 40.2115 14.744ZM20.5048 54.0815C17.233 50.3043 15.124 45.4935 14.7478 40.2115H7.125C7.5202 47.6025 10.4766 54.3095 15.1088 59.4737L20.501 54.0815H20.5048ZM36.7916 69.8782V62.2592C31.5058 61.883 26.695 59.7778 22.9178 56.5022L17.5256 61.8944C22.6936 66.5304 29.4006 69.483 36.7878 69.8782H36.7916Z" fill="url(#paint0_linear_2028_278)"/>
-<defs>
-<linearGradient id="paint0_linear_2028_278" x1="41.443" y1="11.5372" x2="10.5567" y2="42.4236" gradientUnits="userSpaceOnUse">
-<stop stop-color="#0096FF"/>
-<stop offset="1" stop-color="#FF1E56"/>
-</linearGradient>
-</defs>
-</svg>
diff --git a/apps/docs/public/turborepo-light.svg b/apps/docs/public/turborepo-light.svg
deleted file mode 100644
index ddea9158..00000000
--- a/apps/docs/public/turborepo-light.svg
+++ /dev/null
@@ -1,19 +0,0 @@
-<svg width="473" height="76" viewBox="0 0 473 76" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path d="M130.998 30.6566V22.3773H91.0977V30.6566H106.16V58.1876H115.935V30.6566H130.998Z" fill="white"/>
-<path d="M153.542 58.7362C165.811 58.7362 172.544 52.5018 172.544 42.2276V22.3773H162.768V41.2799C162.768 47.0156 159.776 50.2574 153.542 50.2574C147.307 50.2574 144.315 47.0156 144.315 41.2799V22.3773H134.539V42.2276C134.539 52.5018 141.272 58.7362 153.542 58.7362Z" fill="white"/>
-<path d="M187.508 46.3173H197.234L204.914 58.1876H216.136L207.458 45.2699C212.346 43.5243 215.338 39.6341 215.338 34.3473C215.338 26.6666 209.603 22.3773 200.874 22.3773H177.732V58.1876H187.508V46.3173ZM187.508 38.5867V30.5568H200.376C203.817 30.5568 205.712 32.0531 205.712 34.5967C205.712 36.9907 203.817 38.5867 200.376 38.5867H187.508Z" fill="white"/>
-<path d="M219.887 58.1876H245.472C253.452 58.1876 258.041 54.3971 258.041 48.0629C258.041 43.8236 255.348 40.9308 252.156 39.6341C254.35 38.5867 257.043 36.0929 257.043 32.1528C257.043 25.8187 252.555 22.3773 244.625 22.3773H219.887V58.1876ZM229.263 36.3922V30.3074H243.627C246.32 30.3074 247.817 31.3548 247.817 33.3498C247.817 35.3448 246.32 36.3922 243.627 36.3922H229.263ZM229.263 43.7238H244.525C247.168 43.7238 248.615 45.0206 248.615 46.9657C248.615 48.9108 247.168 50.2076 244.525 50.2076H229.263V43.7238Z" fill="white"/>
-<path d="M281.942 21.7788C269.423 21.7788 260.396 29.6092 260.396 40.2824C260.396 50.9557 269.423 58.7861 281.942 58.7861C294.461 58.7861 303.438 50.9557 303.438 40.2824C303.438 29.6092 294.461 21.7788 281.942 21.7788ZM281.942 30.2576C288.525 30.2576 293.463 34.1478 293.463 40.2824C293.463 46.4171 288.525 50.3073 281.942 50.3073C275.359 50.3073 270.421 46.4171 270.421 40.2824C270.421 34.1478 275.359 30.2576 281.942 30.2576Z" fill="white"/>
-<path d="M317.526 46.3173H327.251L334.932 58.1876H346.154L337.476 45.2699C342.364 43.5243 345.356 39.6341 345.356 34.3473C345.356 26.6666 339.62 22.3773 330.892 22.3773H307.75V58.1876H317.526V46.3173ZM317.526 38.5867V30.5568H330.394C333.835 30.5568 335.73 32.0531 335.73 34.5967C335.73 36.9907 333.835 38.5867 330.394 38.5867H317.526Z" fill="white"/>
-<path d="M349.904 22.3773V58.1876H384.717V49.9083H359.48V44.0729H381.874V35.9932H359.48V30.6566H384.717V22.3773H349.904Z" fill="white"/>
-<path d="M399.204 46.7662H412.221C420.95 46.7662 426.685 42.5767 426.685 34.5967C426.685 26.5668 420.95 22.3773 412.221 22.3773H389.428V58.1876H399.204V46.7662ZM399.204 38.6366V30.5568H411.673C415.164 30.5568 417.059 32.0531 417.059 34.5967C417.059 37.0904 415.164 38.6366 411.673 38.6366H399.204Z" fill="white"/>
-<path d="M450.948 21.7788C438.43 21.7788 429.402 29.6092 429.402 40.2824C429.402 50.9557 438.43 58.7861 450.948 58.7861C463.467 58.7861 472.444 50.9557 472.444 40.2824C472.444 29.6092 463.467 21.7788 450.948 21.7788ZM450.948 30.2576C457.532 30.2576 462.469 34.1478 462.469 40.2824C462.469 46.4171 457.532 50.3073 450.948 50.3073C444.365 50.3073 439.427 46.4171 439.427 40.2824C439.427 34.1478 444.365 30.2576 450.948 30.2576Z" fill="white"/>
-<path d="M38.5017 18.0956C27.2499 18.0956 18.0957 27.2498 18.0957 38.5016C18.0957 49.7534 27.2499 58.9076 38.5017 58.9076C49.7535 58.9076 58.9077 49.7534 58.9077 38.5016C58.9077 27.2498 49.7535 18.0956 38.5017 18.0956ZM38.5017 49.0618C32.6687 49.0618 27.9415 44.3346 27.9415 38.5016C27.9415 32.6686 32.6687 27.9414 38.5017 27.9414C44.3347 27.9414 49.0619 32.6686 49.0619 38.5016C49.0619 44.3346 44.3347 49.0618 38.5017 49.0618Z" fill="white"/>
-<path fill-rule="evenodd" clip-rule="evenodd" d="M40.2115 14.744V7.125C56.7719 8.0104 69.9275 21.7208 69.9275 38.5016C69.9275 55.2824 56.7719 68.989 40.2115 69.8782V62.2592C52.5539 61.3776 62.3275 51.0644 62.3275 38.5016C62.3275 25.9388 52.5539 15.6256 40.2115 14.744ZM20.5048 54.0815C17.233 50.3043 15.124 45.4935 14.7478 40.2115H7.125C7.5202 47.6025 10.4766 54.3095 15.1088 59.4737L20.501 54.0815H20.5048ZM36.7916 69.8782V62.2592C31.5058 61.883 26.695 59.7778 22.9178 56.5022L17.5256 61.8944C22.6936 66.5304 29.4006 69.483 36.7878 69.8782H36.7916Z" fill="url(#paint0_linear_2028_477)"/>
-<defs>
-<linearGradient id="paint0_linear_2028_477" x1="41.443" y1="11.5372" x2="10.5567" y2="42.4236" gradientUnits="userSpaceOnUse">
-<stop stop-color="#0096FF"/>
-<stop offset="1" stop-color="#FF1E56"/>
-</linearGradient>
-</defs>
-</svg>
diff --git a/apps/docs/public/vercel.svg b/apps/docs/public/vercel.svg
deleted file mode 100644
index 0164ddc5..00000000
--- a/apps/docs/public/vercel.svg
+++ /dev/null
@@ -1,10 +0,0 @@
-<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
-<g clip-path="url(#clip0_977_547)">
-<path fill-rule="evenodd" clip-rule="evenodd" d="M10.5 3L18.5 17H2.5L10.5 3Z" fill="white"/>
-</g>
-<defs>
-<clipPath id="clip0_977_547">
-<rect width="16" height="16" fill="white" transform="translate(2.5 2)"/>
-</clipPath>
-</defs>
-</svg>
diff --git a/apps/docs/public/window.svg b/apps/docs/public/window.svg
deleted file mode 100644
index bbc78006..00000000
--- a/apps/docs/public/window.svg
+++ /dev/null
@@ -1,3 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5H14.5V12.5C14.5 13.0523 14.0523 13.5 13.5 13.5H2.5C1.94772 13.5 1.5 13.0523 1.5 12.5V2.5ZM0 1H1.5H14.5H16V2.5V12.5C16 13.8807 14.8807 15 13.5 15H2.5C1.11929 15 0 13.8807 0 12.5V2.5V1ZM3.75 5.5C4.16421 5.5 4.5 5.16421 4.5 4.75C4.5 4.33579 4.16421 4 3.75 4C3.33579 4 3 4.33579 3 4.75C3 5.16421 3.33579 5.5 3.75 5.5ZM7 4.75C7 5.16421 6.66421 5.5 6.25 5.5C5.83579 5.5 5.5 5.16421 5.5 4.75C5.5 4.33579 5.83579 4 6.25 4C6.66421 4 7 4.33579 7 4.75ZM8.75 5.5C9.16421 5.5 9.5 5.16421 9.5 4.75C9.5 4.33579 9.16421 4 8.75 4C8.33579 4 8 4.33579 8 4.75C8 5.16421 8.33579 5.5 8.75 5.5Z" fill="#666666"/>
-</svg>
diff --git a/apps/docs/tsconfig.json b/apps/docs/tsconfig.json
deleted file mode 100644
index c0346be0..00000000
--- a/apps/docs/tsconfig.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "extends": "@repo/typescript-config/nextjs.json",
- "compilerOptions": {
- "plugins": [
- {
- "name": "next"
- }
- ],
- "strictNullChecks": true
- },
- "include": [
- "**/*.ts",
- "**/*.tsx",
- "next-env.d.ts",
- "next.config.js",
- ".next/types/**/*.ts"
- ],
- "exclude": ["node_modules"]
-}
diff --git a/apps/web/app/favicon.ico b/apps/web/app/favicon.ico
deleted file mode 100644
index 718d6fea..00000000
Binary files a/apps/web/app/favicon.ico and /dev/null differ
diff --git a/apps/web/app/fonts/GeistMonoVF.woff b/apps/web/app/fonts/GeistMonoVF.woff
deleted file mode 100644
index f2ae185c..00000000
Binary files a/apps/web/app/fonts/GeistMonoVF.woff and /dev/null differ
diff --git a/apps/web/app/fonts/GeistVF.woff b/apps/web/app/fonts/GeistVF.woff
deleted file mode 100644
index 1b62daac..00000000
Binary files a/apps/web/app/fonts/GeistVF.woff and /dev/null differ
diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css
deleted file mode 100644
index 6af7ecbb..00000000
--- a/apps/web/app/globals.css
+++ /dev/null
@@ -1,50 +0,0 @@
-:root {
- --background: #ffffff;
- --foreground: #171717;
-}
-
-@media (prefers-color-scheme: dark) {
- :root {
- --background: #0a0a0a;
- --foreground: #ededed;
- }
-}
-
-html,
-body {
- max-width: 100vw;
- overflow-x: hidden;
-}
-
-body {
- color: var(--foreground);
- background: var(--background);
-}
-
-* {
- box-sizing: border-box;
- padding: 0;
- margin: 0;
-}
-
-a {
- color: inherit;
- text-decoration: none;
-}
-
-.imgDark {
- display: none;
-}
-
-@media (prefers-color-scheme: dark) {
- html {
- color-scheme: dark;
- }
-
- .imgLight {
- display: none;
- }
- .imgDark {
- display: unset;
- }
-}
diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx
deleted file mode 100644
index 84695375..00000000
--- a/apps/web/app/layout.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { Metadata } from "next";
-import localFont from "next/font/local";
-import "./globals.css";
-
-const geistSans = localFont({
- src: "./fonts/GeistVF.woff",
- variable: "--font-geist-sans",
-});
-const geistMono = localFont({
- src: "./fonts/GeistMonoVF.woff",
- variable: "--font-geist-mono",
-});
-
-export const metadata: Metadata = {
- title: "Create Next App",
- description: "Generated by create next app",
-};
-
-export default function RootLayout({
- children,
-}: Readonly<{
- children: React.ReactNode;
-}>) {
- return (
- <html lang="en">
- <body className={`${geistSans.variable} ${geistMono.variable}`}>
- {children}
- </body>
- </html>
- );
-}
diff --git a/apps/web/app/page.module.css b/apps/web/app/page.module.css
deleted file mode 100644
index 6108b60b..00000000
--- a/apps/web/app/page.module.css
+++ /dev/null
@@ -1,186 +0,0 @@
-.page {
- --gray-rgb: 0, 0, 0;
- --gray-alpha-200: rgba(var(--gray-rgb), 0.08);
- --gray-alpha-100: rgba(var(--gray-rgb), 0.05);
-
- --button-primary-hover: #383838;
- --button-secondary-hover: #f2f2f2;
-
- display: grid;
- grid-template-rows: 20px 1fr 20px;
- align-items: center;
- justify-items: center;
- min-height: 100svh;
- padding: 80px;
- gap: 64px;
- font-synthesis: none;
-}
-
-@media (prefers-color-scheme: dark) {
- .page {
- --gray-rgb: 255, 255, 255;
- --gray-alpha-200: rgba(var(--gray-rgb), 0.145);
- --gray-alpha-100: rgba(var(--gray-rgb), 0.06);
-
- --button-primary-hover: #ccc;
- --button-secondary-hover: #1a1a1a;
- }
-}
-
-.main {
- display: flex;
- flex-direction: column;
- gap: 32px;
- grid-row-start: 2;
-}
-
-.main ol {
- font-family: var(--font-geist-mono);
- padding-left: 0;
- margin: 0;
- font-size: 14px;
- line-height: 24px;
- letter-spacing: -0.01em;
- list-style-position: inside;
-}
-
-.main li:not(:last-of-type) {
- margin-bottom: 8px;
-}
-
-.main code {
- font-family: inherit;
- background: var(--gray-alpha-100);
- padding: 2px 4px;
- border-radius: 4px;
- font-weight: 600;
-}
-
-.ctas {
- display: flex;
- gap: 16px;
-}
-
-.ctas a {
- appearance: none;
- border-radius: 128px;
- height: 48px;
- padding: 0 20px;
- font-family: var(--font-geist-sans);
- border: 1px solid transparent;
- transition: background 0.2s, color 0.2s, border-color 0.2s;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 16px;
- line-height: 20px;
- font-weight: 500;
-}
-
-a.primary {
- background: var(--foreground);
- color: var(--background);
- gap: 8px;
-}
-
-a.secondary {
- border-color: var(--gray-alpha-200);
- min-width: 180px;
-}
-
-button.secondary {
- appearance: none;
- border-radius: 128px;
- height: 48px;
- padding: 0 20px;
- font-family: var(--font-geist-sans);
- border: 1px solid transparent;
- transition: background 0.2s, color 0.2s, border-color 0.2s;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 16px;
- line-height: 20px;
- font-weight: 500;
- background: transparent;
- border-color: var(--gray-alpha-200);
- min-width: 180px;
-}
-
-.footer {
- font-family: var(--font-geist-sans);
- grid-row-start: 3;
- display: flex;
- gap: 24px;
-}
-
-.footer a {
- display: flex;
- align-items: center;
- gap: 8px;
-}
-
-.footer img {
- flex-shrink: 0;
-}
-
-/* Enable hover only on non-touch devices */
-@media (hover: hover) and (pointer: fine) {
- a.primary:hover {
- background: var(--button-primary-hover);
- border-color: transparent;
- }
-
- a.secondary:hover {
- background: var(--button-secondary-hover);
- border-color: transparent;
- }
-
- .footer a:hover {
- text-decoration: underline;
- text-underline-offset: 4px;
- }
-}
-
-@media (max-width: 600px) {
- .page {
- padding: 32px;
- padding-bottom: 80px;
- }
-
- .main {
- align-items: center;
- }
-
- .main ol {
- text-align: center;
- }
-
- .ctas {
- flex-direction: column;
- }
-
- .ctas a {
- font-size: 14px;
- height: 40px;
- padding: 0 16px;
- }
-
- a.secondary {
- min-width: auto;
- }
-
- .footer {
- flex-wrap: wrap;
- align-items: center;
- justify-content: center;
- }
-}
-
-@media (prefers-color-scheme: dark) {
- .logo {
- filter: invert();
- }
-}
diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx
deleted file mode 100644
index 593833ba..00000000
--- a/apps/web/app/page.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import Image, { type ImageProps } from "next/image";
-import { Button } from "@repo/ui/button";
-import styles from "./page.module.css";
-
-type Props = Omit<ImageProps, "src"> & {
- srcLight: string;
- srcDark: string;
-};
-
-const ThemeImage = (props: Props) => {
- const { srcLight, srcDark, ...rest } = props;
-
- return (
- <>
- <Image {...rest} src={srcLight} className="imgLight" />
- <Image {...rest} src={srcDark} className="imgDark" />
- </>
- );
-};
-
-export default function Home() {
- return (
- <div className={styles.page}>
- <main className={styles.main}>
- <ThemeImage
- className={styles.logo}
- srcLight="turborepo-dark.svg"
- srcDark="turborepo-light.svg"
- alt="Turborepo logo"
- width={180}
- height={38}
- priority
- />
- <ol>
- <li>
- Get started by editing <code>apps/web/app/page.tsx</code>
- </li>
- <li>Save and see your changes instantly.</li>
- </ol>
-
- <div className={styles.ctas}>
- <a
- className={styles.primary}
- href="https://vercel.com/new/clone?demo-description=Learn+to+implement+a+monorepo+with+a+two+Next.js+sites+that+has+installed+three+local+packages.&demo-image=%2F%2Fimages.ctfassets.net%2Fe5382hct74si%2F4K8ZISWAzJ8X1504ca0zmC%2F0b21a1c6246add355e55816278ef54bc%2FBasic.png&demo-title=Monorepo+with+Turborepo&demo-url=https%3A%2F%2Fexamples-basic-web.vercel.sh%2F&from=templates&project-name=Monorepo+with+Turborepo&repository-name=monorepo-turborepo&repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fturborepo%2Ftree%2Fmain%2Fexamples%2Fbasic&root-directory=apps%2Fdocs&skippable-integrations=1&teamSlug=vercel&utm_source=create-turbo"
- target="_blank"
- rel="noopener noreferrer"
- >
- <Image
- className={styles.logo}
- src="/vercel.svg"
- alt="Vercel logomark"
- width={20}
- height={20}
- />
- Deploy now
- </a>
- <a
- href="https://turborepo.dev/docs?utm_source"
- target="_blank"
- rel="noopener noreferrer"
- className={styles.secondary}
- >
- Read our docs
- </a>
- </div>
- <Button appName="web" className={styles.secondary}>
- Open alert
- </Button>
- </main>
- <footer className={styles.footer}>
- <a
- href="https://vercel.com/templates?search=turborepo&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
- target="_blank"
- rel="noopener noreferrer"
- >
- <Image
- aria-hidden
- src="/window.svg"
- alt="Window icon"
- width={16}
- height={16}
- />
- Examples
- </a>
- <a
- href="https://turborepo.dev?utm_source=create-turbo"
- target="_blank"
- rel="noopener noreferrer"
- >
- <Image
- aria-hidden
- src="/globe.svg"
- alt="Globe icon"
- width={16}
- height={16}
- />
- Go to turborepo.dev →
- </a>
- </footer>
- </div>
- );
-}
diff --git a/apps/web/eslint.config.js b/apps/web/eslint.config.js
deleted file mode 100644
index 47b0670b..00000000
--- a/apps/web/eslint.config.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import { nextJsConfig } from "@repo/eslint-config/next-js";
-
-/** @type {import("eslint").Linter.Config[]} */
-export default nextJsConfig;
diff --git a/apps/web/next.config.js b/apps/web/next.config.js
deleted file mode 100644
index 4678774e..00000000
--- a/apps/web/next.config.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/** @type {import('next').NextConfig} */
-const nextConfig = {};
-
-export default nextConfig;
diff --git a/apps/web/package.json b/apps/web/package.json
deleted file mode 100644
index f9931fbb..00000000
--- a/apps/web/package.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "name": "web",
- "version": "0.1.0",
- "type": "module",
- "private": true,
- "scripts": {
- "dev": "next dev --port 3000",
- "build": "next build",
- "start": "next start",
- "lint": "eslint --max-warnings 0",
- "check-types": "next typegen && tsc --noEmit"
- },
- "dependencies": {
- "@repo/ui": "*",
- "next": "16.2.0",
- "react": "^19.2.0",
- "react-dom": "^19.2.0"
- },
- "devDependencies": {
- "@repo/eslint-config": "*",
- "@repo/typescript-config": "*",
- "@types/node": "^22.15.3",
- "@types/react": "19.2.2",
- "@types/react-dom": "19.2.2",
- "eslint": "^9.39.1",
- "typescript": "5.9.2"
- }
-}
diff --git a/apps/web/public/file-text.svg b/apps/web/public/file-text.svg
deleted file mode 100644
index 9cfb3c98..00000000
--- a/apps/web/public/file-text.svg
+++ /dev/null
@@ -1,3 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path fill-rule="evenodd" clip-rule="evenodd" d="M14.5 13.5V6.5V5.41421C14.5 5.149 14.3946 4.89464 14.2071 4.70711L9.79289 0.292893C9.60536 0.105357 9.351 0 9.08579 0H8H3H1.5V1.5V13.5C1.5 14.8807 2.61929 16 4 16H12C13.3807 16 14.5 14.8807 14.5 13.5ZM13 13.5V6.5H9.5H8V5V1.5H3V13.5C3 14.0523 3.44772 14.5 4 14.5H12C12.5523 14.5 13 14.0523 13 13.5ZM9.5 5V2.12132L12.3787 5H9.5ZM5.13 5.00062H4.505V6.25062H5.13H6H6.625V5.00062H6H5.13ZM4.505 8H5.13H11H11.625V9.25H11H5.13H4.505V8ZM5.13 11H4.505V12.25H5.13H11H11.625V11H11H5.13Z" fill="#666666"/>
-</svg>
diff --git a/apps/web/public/globe.svg b/apps/web/public/globe.svg
deleted file mode 100644
index 4230a3d2..00000000
--- a/apps/web/public/globe.svg
+++ /dev/null
@@ -1,10 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
-<g clip-path="url(#clip0_868_525)">
-<path fill-rule="evenodd" clip-rule="evenodd" d="M10.268 14.0934C11.9051 13.4838 13.2303 12.2333 13.9384 10.6469C13.1192 10.7941 12.2138 10.9111 11.2469 10.9925C11.0336 12.2005 10.695 13.2621 10.268 14.0934ZM8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM8.48347 14.4823C8.32384 14.494 8.16262 14.5 8 14.5C7.83738 14.5 7.67616 14.494 7.51654 14.4823C7.5132 14.4791 7.50984 14.4759 7.50647 14.4726C7.2415 14.2165 6.94578 13.7854 6.67032 13.1558C6.41594 12.5744 6.19979 11.8714 6.04101 11.0778C6.67605 11.1088 7.33104 11.125 8 11.125C8.66896 11.125 9.32395 11.1088 9.95899 11.0778C9.80021 11.8714 9.58406 12.5744 9.32968 13.1558C9.05422 13.7854 8.7585 14.2165 8.49353 14.4726C8.49016 14.4759 8.4868 14.4791 8.48347 14.4823ZM11.4187 9.72246C12.5137 9.62096 13.5116 9.47245 14.3724 9.28806C14.4561 8.87172 14.5 8.44099 14.5 8C14.5 7.55901 14.4561 7.12828 14.3724 6.71194C13.5116 6.52755 12.5137 6.37904 11.4187 6.27753C11.4719 6.83232 11.5 7.40867 11.5 8C11.5 8.59133 11.4719 9.16768 11.4187 9.72246ZM10.1525 6.18401C10.2157 6.75982 10.25 7.36805 10.25 8C10.25 8.63195 10.2157 9.24018 10.1525 9.81598C9.46123 9.85455 8.7409 9.875 8 9.875C7.25909 9.875 6.53877 9.85455 5.84749 9.81598C5.7843 9.24018 5.75 8.63195 5.75 8C5.75 7.36805 5.7843 6.75982 5.84749 6.18401C6.53877 6.14545 7.25909 6.125 8 6.125C8.74091 6.125 9.46123 6.14545 10.1525 6.18401ZM11.2469 5.00748C12.2138 5.08891 13.1191 5.20593 13.9384 5.35306C13.2303 3.7667 11.9051 2.51622 10.268 1.90662C10.695 2.73788 11.0336 3.79953 11.2469 5.00748ZM8.48347 1.51771C8.4868 1.52089 8.49016 1.52411 8.49353 1.52737C8.7585 1.78353 9.05422 2.21456 9.32968 2.84417C9.58406 3.42562 9.80021 4.12856 9.95899 4.92219C9.32395 4.89118 8.66896 4.875 8 4.875C7.33104 4.875 6.67605 4.89118 6.04101 4.92219C6.19978 4.12856 6.41594 3.42562 6.67032 2.84417C6.94578 2.21456 7.2415 1.78353 7.50647 1.52737C7.50984 1.52411 7.51319 1.52089 7.51653 1.51771C7.67615 1.50597 7.83738 1.5 8 1.5C8.16262 1.5 8.32384 1.50597 8.48347 1.51771ZM5.73202 1.90663C4.0949 2.51622 2.76975 3.7667 2.06159 5.35306C2.88085 5.20593 3.78617 5.08891 4.75309 5.00748C4.96639 3.79953 5.30497 2.73788 5.73202 1.90663ZM4.58133 6.27753C3.48633 6.37904 2.48837 6.52755 1.62761 6.71194C1.54392 7.12828 1.5 7.55901 1.5 8C1.5 8.44099 1.54392 8.87172 1.62761 9.28806C2.48837 9.47245 3.48633 9.62096 4.58133 9.72246C4.52807 9.16768 4.5 8.59133 4.5 8C4.5 7.40867 4.52807 6.83232 4.58133 6.27753ZM4.75309 10.9925C3.78617 10.9111 2.88085 10.7941 2.06159 10.6469C2.76975 12.2333 4.0949 13.4838 5.73202 14.0934C5.30497 13.2621 4.96639 12.2005 4.75309 10.9925Z" fill="#666666"/>
-</g>
-<defs>
-<clipPath id="clip0_868_525">
-<rect width="16" height="16" fill="white"/>
-</clipPath>
-</defs>
-</svg>
diff --git a/apps/web/public/next.svg b/apps/web/public/next.svg
deleted file mode 100644
index 5174b28c..00000000
--- a/apps/web/public/next.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
\ No newline at end of file
diff --git a/apps/web/public/turborepo-dark.svg b/apps/web/public/turborepo-dark.svg
deleted file mode 100644
index dae38fed..00000000
--- a/apps/web/public/turborepo-dark.svg
+++ /dev/null
@@ -1,19 +0,0 @@
-<svg width="473" height="76" viewBox="0 0 473 76" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path d="M130.998 30.6565V22.3773H91.0977V30.6565H106.16V58.1875H115.935V30.6565H130.998Z" fill="black"/>
-<path d="M153.542 58.7362C165.811 58.7362 172.544 52.5018 172.544 42.2275V22.3773H162.768V41.2799C162.768 47.0155 159.776 50.2574 153.542 50.2574C147.307 50.2574 144.315 47.0155 144.315 41.2799V22.3773H134.539V42.2275C134.539 52.5018 141.272 58.7362 153.542 58.7362Z" fill="black"/>
-<path d="M187.508 46.3173H197.234L204.914 58.1875H216.136L207.458 45.2699C212.346 43.5243 215.338 39.634 215.338 34.3473C215.338 26.6665 209.603 22.3773 200.874 22.3773H177.732V58.1875H187.508V46.3173ZM187.508 38.5867V30.5568H200.376C203.817 30.5568 205.712 32.053 205.712 34.5967C205.712 36.9907 203.817 38.5867 200.376 38.5867H187.508Z" fill="black"/>
-<path d="M219.887 58.1875H245.472C253.452 58.1875 258.041 54.397 258.041 48.0629C258.041 43.8235 255.348 40.9308 252.156 39.634C254.35 38.5867 257.043 36.0929 257.043 32.1528C257.043 25.8187 252.555 22.3773 244.625 22.3773H219.887V58.1875ZM229.263 36.3922V30.3074H243.627C246.32 30.3074 247.817 31.3548 247.817 33.3498C247.817 35.3448 246.32 36.3922 243.627 36.3922H229.263ZM229.263 43.7238H244.525C247.168 43.7238 248.615 45.0205 248.615 46.9657C248.615 48.9108 247.168 50.2075 244.525 50.2075H229.263V43.7238Z" fill="black"/>
-<path d="M281.942 21.7788C269.423 21.7788 260.396 29.6092 260.396 40.2824C260.396 50.9557 269.423 58.786 281.942 58.786C294.461 58.786 303.438 50.9557 303.438 40.2824C303.438 29.6092 294.461 21.7788 281.942 21.7788ZM281.942 30.2575C288.525 30.2575 293.463 34.1478 293.463 40.2824C293.463 46.417 288.525 50.3073 281.942 50.3073C275.359 50.3073 270.421 46.417 270.421 40.2824C270.421 34.1478 275.359 30.2575 281.942 30.2575Z" fill="black"/>
-<path d="M317.526 46.3173H327.251L334.932 58.1875H346.154L337.476 45.2699C342.364 43.5243 345.356 39.634 345.356 34.3473C345.356 26.6665 339.62 22.3773 330.892 22.3773H307.75V58.1875H317.526V46.3173ZM317.526 38.5867V30.5568H330.394C333.835 30.5568 335.73 32.053 335.73 34.5967C335.73 36.9907 333.835 38.5867 330.394 38.5867H317.526Z" fill="black"/>
-<path d="M349.904 22.3773V58.1875H384.717V49.9083H359.48V44.0729H381.874V35.9932H359.48V30.6565H384.717V22.3773H349.904Z" fill="black"/>
-<path d="M399.204 46.7662H412.221C420.95 46.7662 426.685 42.5767 426.685 34.5967C426.685 26.5668 420.95 22.3773 412.221 22.3773H389.428V58.1875H399.204V46.7662ZM399.204 38.6365V30.5568H411.673C415.164 30.5568 417.059 32.053 417.059 34.5967C417.059 37.0904 415.164 38.6365 411.673 38.6365H399.204Z" fill="black"/>
-<path d="M450.948 21.7788C438.43 21.7788 429.402 29.6092 429.402 40.2824C429.402 50.9557 438.43 58.786 450.948 58.786C463.467 58.786 472.444 50.9557 472.444 40.2824C472.444 29.6092 463.467 21.7788 450.948 21.7788ZM450.948 30.2575C457.532 30.2575 462.469 34.1478 462.469 40.2824C462.469 46.417 457.532 50.3073 450.948 50.3073C444.365 50.3073 439.427 46.417 439.427 40.2824C439.427 34.1478 444.365 30.2575 450.948 30.2575Z" fill="black"/>
-<path d="M38.5017 18.0956C27.2499 18.0956 18.0957 27.2498 18.0957 38.5016C18.0957 49.7534 27.2499 58.9076 38.5017 58.9076C49.7535 58.9076 58.9077 49.7534 58.9077 38.5016C58.9077 27.2498 49.7535 18.0956 38.5017 18.0956ZM38.5017 49.0618C32.6687 49.0618 27.9415 44.3346 27.9415 38.5016C27.9415 32.6686 32.6687 27.9414 38.5017 27.9414C44.3347 27.9414 49.0619 32.6686 49.0619 38.5016C49.0619 44.3346 44.3347 49.0618 38.5017 49.0618Z" fill="black"/>
-<path fill-rule="evenodd" clip-rule="evenodd" d="M40.2115 14.744V7.125C56.7719 8.0104 69.9275 21.7208 69.9275 38.5016C69.9275 55.2824 56.7719 68.989 40.2115 69.8782V62.2592C52.5539 61.3776 62.3275 51.0644 62.3275 38.5016C62.3275 25.9388 52.5539 15.6256 40.2115 14.744ZM20.5048 54.0815C17.233 50.3043 15.124 45.4935 14.7478 40.2115H7.125C7.5202 47.6025 10.4766 54.3095 15.1088 59.4737L20.501 54.0815H20.5048ZM36.7916 69.8782V62.2592C31.5058 61.883 26.695 59.7778 22.9178 56.5022L17.5256 61.8944C22.6936 66.5304 29.4006 69.483 36.7878 69.8782H36.7916Z" fill="url(#paint0_linear_2028_278)"/>
-<defs>
-<linearGradient id="paint0_linear_2028_278" x1="41.443" y1="11.5372" x2="10.5567" y2="42.4236" gradientUnits="userSpaceOnUse">
-<stop stop-color="#0096FF"/>
-<stop offset="1" stop-color="#FF1E56"/>
-</linearGradient>
-</defs>
-</svg>
diff --git a/apps/web/public/turborepo-light.svg b/apps/web/public/turborepo-light.svg
deleted file mode 100644
index ddea9158..00000000
--- a/apps/web/public/turborepo-light.svg
+++ /dev/null
@@ -1,19 +0,0 @@
-<svg width="473" height="76" viewBox="0 0 473 76" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path d="M130.998 30.6566V22.3773H91.0977V30.6566H106.16V58.1876H115.935V30.6566H130.998Z" fill="white"/>
-<path d="M153.542 58.7362C165.811 58.7362 172.544 52.5018 172.544 42.2276V22.3773H162.768V41.2799C162.768 47.0156 159.776 50.2574 153.542 50.2574C147.307 50.2574 144.315 47.0156 144.315 41.2799V22.3773H134.539V42.2276C134.539 52.5018 141.272 58.7362 153.542 58.7362Z" fill="white"/>
-<path d="M187.508 46.3173H197.234L204.914 58.1876H216.136L207.458 45.2699C212.346 43.5243 215.338 39.6341 215.338 34.3473C215.338 26.6666 209.603 22.3773 200.874 22.3773H177.732V58.1876H187.508V46.3173ZM187.508 38.5867V30.5568H200.376C203.817 30.5568 205.712 32.0531 205.712 34.5967C205.712 36.9907 203.817 38.5867 200.376 38.5867H187.508Z" fill="white"/>
-<path d="M219.887 58.1876H245.472C253.452 58.1876 258.041 54.3971 258.041 48.0629C258.041 43.8236 255.348 40.9308 252.156 39.6341C254.35 38.5867 257.043 36.0929 257.043 32.1528C257.043 25.8187 252.555 22.3773 244.625 22.3773H219.887V58.1876ZM229.263 36.3922V30.3074H243.627C246.32 30.3074 247.817 31.3548 247.817 33.3498C247.817 35.3448 246.32 36.3922 243.627 36.3922H229.263ZM229.263 43.7238H244.525C247.168 43.7238 248.615 45.0206 248.615 46.9657C248.615 48.9108 247.168 50.2076 244.525 50.2076H229.263V43.7238Z" fill="white"/>
-<path d="M281.942 21.7788C269.423 21.7788 260.396 29.6092 260.396 40.2824C260.396 50.9557 269.423 58.7861 281.942 58.7861C294.461 58.7861 303.438 50.9557 303.438 40.2824C303.438 29.6092 294.461 21.7788 281.942 21.7788ZM281.942 30.2576C288.525 30.2576 293.463 34.1478 293.463 40.2824C293.463 46.4171 288.525 50.3073 281.942 50.3073C275.359 50.3073 270.421 46.4171 270.421 40.2824C270.421 34.1478 275.359 30.2576 281.942 30.2576Z" fill="white"/>
-<path d="M317.526 46.3173H327.251L334.932 58.1876H346.154L337.476 45.2699C342.364 43.5243 345.356 39.6341 345.356 34.3473C345.356 26.6666 339.62 22.3773 330.892 22.3773H307.75V58.1876H317.526V46.3173ZM317.526 38.5867V30.5568H330.394C333.835 30.5568 335.73 32.0531 335.73 34.5967C335.73 36.9907 333.835 38.5867 330.394 38.5867H317.526Z" fill="white"/>
-<path d="M349.904 22.3773V58.1876H384.717V49.9083H359.48V44.0729H381.874V35.9932H359.48V30.6566H384.717V22.3773H349.904Z" fill="white"/>
-<path d="M399.204 46.7662H412.221C420.95 46.7662 426.685 42.5767 426.685 34.5967C426.685 26.5668 420.95 22.3773 412.221 22.3773H389.428V58.1876H399.204V46.7662ZM399.204 38.6366V30.5568H411.673C415.164 30.5568 417.059 32.0531 417.059 34.5967C417.059 37.0904 415.164 38.6366 411.673 38.6366H399.204Z" fill="white"/>
-<path d="M450.948 21.7788C438.43 21.7788 429.402 29.6092 429.402 40.2824C429.402 50.9557 438.43 58.7861 450.948 58.7861C463.467 58.7861 472.444 50.9557 472.444 40.2824C472.444 29.6092 463.467 21.7788 450.948 21.7788ZM450.948 30.2576C457.532 30.2576 462.469 34.1478 462.469 40.2824C462.469 46.4171 457.532 50.3073 450.948 50.3073C444.365 50.3073 439.427 46.4171 439.427 40.2824C439.427 34.1478 444.365 30.2576 450.948 30.2576Z" fill="white"/>
-<path d="M38.5017 18.0956C27.2499 18.0956 18.0957 27.2498 18.0957 38.5016C18.0957 49.7534 27.2499 58.9076 38.5017 58.9076C49.7535 58.9076 58.9077 49.7534 58.9077 38.5016C58.9077 27.2498 49.7535 18.0956 38.5017 18.0956ZM38.5017 49.0618C32.6687 49.0618 27.9415 44.3346 27.9415 38.5016C27.9415 32.6686 32.6687 27.9414 38.5017 27.9414C44.3347 27.9414 49.0619 32.6686 49.0619 38.5016C49.0619 44.3346 44.3347 49.0618 38.5017 49.0618Z" fill="white"/>
-<path fill-rule="evenodd" clip-rule="evenodd" d="M40.2115 14.744V7.125C56.7719 8.0104 69.9275 21.7208 69.9275 38.5016C69.9275 55.2824 56.7719 68.989 40.2115 69.8782V62.2592C52.5539 61.3776 62.3275 51.0644 62.3275 38.5016C62.3275 25.9388 52.5539 15.6256 40.2115 14.744ZM20.5048 54.0815C17.233 50.3043 15.124 45.4935 14.7478 40.2115H7.125C7.5202 47.6025 10.4766 54.3095 15.1088 59.4737L20.501 54.0815H20.5048ZM36.7916 69.8782V62.2592C31.5058 61.883 26.695 59.7778 22.9178 56.5022L17.5256 61.8944C22.6936 66.5304 29.4006 69.483 36.7878 69.8782H36.7916Z" fill="url(#paint0_linear_2028_477)"/>
-<defs>
-<linearGradient id="paint0_linear_2028_477" x1="41.443" y1="11.5372" x2="10.5567" y2="42.4236" gradientUnits="userSpaceOnUse">
-<stop stop-color="#0096FF"/>
-<stop offset="1" stop-color="#FF1E56"/>
-</linearGradient>
-</defs>
-</svg>
diff --git a/apps/web/public/vercel.svg b/apps/web/public/vercel.svg
deleted file mode 100644
index 0164ddc5..00000000
--- a/apps/web/public/vercel.svg
+++ /dev/null
@@ -1,10 +0,0 @@
-<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
-<g clip-path="url(#clip0_977_547)">
-<path fill-rule="evenodd" clip-rule="evenodd" d="M10.5 3L18.5 17H2.5L10.5 3Z" fill="white"/>
-</g>
-<defs>
-<clipPath id="clip0_977_547">
-<rect width="16" height="16" fill="white" transform="translate(2.5 2)"/>
-</clipPath>
-</defs>
-</svg>
diff --git a/apps/web/public/window.svg b/apps/web/public/window.svg
deleted file mode 100644
index bbc78006..00000000
--- a/apps/web/public/window.svg
+++ /dev/null
@@ -1,3 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5H14.5V12.5C14.5 13.0523 14.0523 13.5 13.5 13.5H2.5C1.94772 13.5 1.5 13.0523 1.5 12.5V2.5ZM0 1H1.5H14.5H16V2.5V12.5C16 13.8807 14.8807 15 13.5 15H2.5C1.11929 15 0 13.8807 0 12.5V2.5V1ZM3.75 5.5C4.16421 5.5 4.5 5.16421 4.5 4.75C4.5 4.33579 4.16421 4 3.75 4C3.33579 4 3 4.33579 3 4.75C3 5.16421 3.33579 5.5 3.75 5.5ZM7 4.75C7 5.16421 6.66421 5.5 6.25 5.5C5.83579 5.5 5.5 5.16421 5.5 4.75C5.5 4.33579 5.83579 4 6.25 4C6.66421 4 7 4.33579 7 4.75ZM8.75 5.5C9.16421 5.5 9.5 5.16421 9.5 4.75C9.5 4.33579 9.16421 4 8.75 4C8.33579 4 8 4.33579 8 4.75C8 5.16421 8.33579 5.5 8.75 5.5Z" fill="#666666"/>
-</svg>
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
deleted file mode 100644
index c0346be0..00000000
--- a/apps/web/tsconfig.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "extends": "@repo/typescript-config/nextjs.json",
- "compilerOptions": {
- "plugins": [
- {
- "name": "next"
- }
- ],
- "strictNullChecks": true
- },
- "include": [
- "**/*.ts",
- "**/*.tsx",
- "next-env.d.ts",
- "next.config.js",
- ".next/types/**/*.ts"
- ],
- "exclude": ["node_modules"]
-}
diff --git a/biome.jsonc b/biome.jsonc
new file mode 100644
index 00000000..395e9b66
--- /dev/null
+++ b/biome.jsonc
@@ -0,0 +1,87 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.5.6/schema.json",
+ "vcs": {
+ "enabled": true,
+ "clientKind": "git",
+ "useIgnoreFile": true
+ },
+ "files": {
+ "ignoreUnknown": false,
+ "includes": [
+ "**",
+ // Prisma Client output — regenerated, never edited.
+ "!**/src/generated",
+ // Vendored shadcn/ui source. Left in upstream formatting so that
+ // `shadcn add --diff <component>` stays readable when re-syncing.
+ // use-mobile.ts arrives the same way, pulled in by `sidebar`.
+ "!packages/ui/src/components",
+ "!packages/ui/src/hooks/use-mobile.ts",
+ "!**/.next",
+ "!**/dist",
+ // Static assets, not source.
+ "!**/*.svg",
+ // Agent tooling, managed outside this repo.
+ "!.claude",
+ "!.agents",
+ "!skills-lock.json"
+ ]
+ },
+ "formatter": {
+ "enabled": true,
+ "indentStyle": "tab"
+ },
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "preset": "recommended"
+ }
+ },
+ "css": {
+ "parser": {
+ // Tailwind v4 uses @theme / @apply in globals.css.
+ "tailwindDirectives": true
+ }
+ },
+ "javascript": {
+ "formatter": {
+ "quoteStyle": "double"
+ },
+ "parser": {
+ // NestJS relies on parameter decorators (@Inject, @Session, @Body).
+ "unsafeParameterDecoratorsEnabled": true
+ }
+ },
+ "assist": {
+ "enabled": true,
+ "actions": {
+ "source": {
+ "organizeImports": "on"
+ }
+ }
+ },
+ "overrides": [
+ {
+ // Replaces eslint-config-next / eslint-plugin-react.
+ "includes": ["apps/app/**"],
+ "linter": {
+ "domains": {
+ "next": "recommended",
+ "react": "recommended"
+ }
+ }
+ },
+ {
+ // Nest resolves constructor dependencies from `design:paramtypes`
+ // metadata, which only exists for value imports. Rewriting them to
+ // `import type` erases the metadata and breaks DI at runtime.
+ "includes": ["apps/api/**"],
+ "linter": {
+ "rules": {
+ "style": {
+ "useImportType": "off"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/bun.lock b/bun.lock
index 8010c7c1..791b0a5d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,118 +5,339 @@
"": {
"name": "crm",
"devDependencies": {
- "prettier": "^3.7.4",
+ "@biomejs/biome": "^2.4.10",
"turbo": "^2.10.8",
"typescript": "5.9.2",
},
},
- "apps/docs": {
- "name": "docs",
- "version": "0.1.0",
+ "apps/api": {
+ "name": "api",
+ "version": "0.0.1",
"dependencies": {
- "@repo/ui": "*",
- "next": "16.2.0",
- "react": "^19.2.0",
- "react-dom": "^19.2.0",
+ "@crm/auth": "workspace:*",
+ "@crm/db": "workspace:*",
+ "@keyv/redis": "^5.1.6",
+ "@nestjs/cache-manager": "^3.1.3",
+ "@nestjs/common": "^11.0.1",
+ "@nestjs/config": "^4.0.4",
+ "@nestjs/core": "^11.0.1",
+ "@nestjs/platform-express": "^11.0.1",
+ "@thallesp/nestjs-better-auth": "^2.7.0",
+ "@trpc/server": "^11.18.0",
+ "better-auth": "^1.6.25",
+ "cache-manager": "^7.2.9",
+ "class-transformer": "^0.5.1",
+ "class-validator": "^0.15.1",
+ "context.dev": "^2.7.0",
+ "helmet": "^8.3.0",
+ "nestjs-trpc": "^2.13.0",
+ "reflect-metadata": "^0.2.2",
+ "rxjs": "^7.8.1",
+ "zod": "^4.4.3",
},
"devDependencies": {
- "@repo/eslint-config": "*",
- "@repo/typescript-config": "*",
- "@types/node": "^22.15.3",
- "@types/react": "19.2.2",
- "@types/react-dom": "19.2.2",
- "eslint": "^9.39.1",
- "typescript": "5.9.2",
+ "@crm/typescript-config": "workspace:*",
+ "@nestjs/cli": "^11.0.0",
+ "@nestjs/schematics": "^11.0.0",
+ "@nestjs/testing": "^11.0.1",
+ "@types/bun": "^1.3.14",
+ "@types/express": "^5.0.0",
+ "@types/node": "^24.0.0",
+ "@types/supertest": "^7.0.0",
+ "concurrently": "^9.1.0",
+ "supertest": "^7.0.0",
+ "typescript": "^5.9.2",
},
},
- "apps/web": {
- "name": "web",
+ "apps/app": {
+ "name": "app",
"version": "0.1.0",
"dependencies": {
- "@repo/ui": "*",
- "next": "16.2.0",
- "react": "^19.2.0",
- "react-dom": "^19.2.0",
+ "@carbon/icons-react": "^11.82.0",
+ "@crm/auth": "workspace:*",
+ "@crm/db": "workspace:*",
+ "@crm/ui": "workspace:*",
+ "@tanstack/react-query": "^5.101.2",
+ "@trpc/client": "^11.18.0",
+ "@trpc/server": "^11.18.0",
+ "@trpc/tanstack-react-query": "^11.18.0",
+ "api": "workspace:*",
+ "better-auth": "^1.6.25",
+ "next": "16.2.12",
+ "next-themes": "^0.4.6",
+ "nuqs": "^2.8.9",
+ "react": "19.2.4",
+ "react-dom": "19.2.4",
+ "sonner": "^2.0.7",
+ "zod": "^4.4.3",
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@tailwindcss/postcss": "^4",
+ "@tanstack/react-query-devtools": "^5.101.2",
+ "@types/node": "^20",
+ "@types/react": "^19",
+ "@types/react-dom": "^19",
+ "tailwindcss": "^4",
+ "typescript": "^5",
+ },
+ },
+ "packages/auth": {
+ "name": "@crm/auth",
+ "version": "0.0.0",
+ "dependencies": {
+ "@crm/db": "workspace:*",
+ "better-auth": "^1.6.25",
},
"devDependencies": {
- "@repo/eslint-config": "*",
- "@repo/typescript-config": "*",
- "@types/node": "^22.15.3",
- "@types/react": "19.2.2",
- "@types/react-dom": "19.2.2",
- "eslint": "^9.39.1",
+ "@better-auth/cli": "^1.4.22",
+ "@crm/typescript-config": "workspace:*",
+ "@types/node": "^24.10.1",
+ "@types/react": "^19.2.18",
+ "react": "^19.2.8",
"typescript": "5.9.2",
},
+ "peerDependencies": {
+ "react": "^19.2.0",
+ },
+ "optionalPeers": [
+ "react",
+ ],
},
- "packages/eslint-config": {
- "name": "@repo/eslint-config",
+ "packages/db": {
+ "name": "@crm/db",
"version": "0.0.0",
+ "dependencies": {
+ "@prisma/adapter-pg": "^7.9.1",
+ "@prisma/client": "^7.9.1",
+ "pg": "^8.22.0",
+ },
"devDependencies": {
- "@eslint/js": "^9.39.1",
- "@next/eslint-plugin-next": "^16.2.0",
- "eslint": "^9.39.1",
- "eslint-config-prettier": "^10.1.1",
- "eslint-plugin-only-warn": "^1.1.0",
- "eslint-plugin-react": "^7.37.5",
- "eslint-plugin-react-hooks": "^5.2.0",
- "eslint-plugin-turbo": "^2.7.1",
- "globals": "^16.5.0",
- "typescript": "^5.9.2",
- "typescript-eslint": "^8.50.0",
+ "@crm/typescript-config": "workspace:*",
+ "@types/node": "^24.10.1",
+ "@types/pg": "^8.20.0",
+ "dotenv": "^17.2.4",
+ "prisma": "^7.9.1",
+ "typescript": "5.9.2",
},
},
"packages/typescript-config": {
- "name": "@repo/typescript-config",
+ "name": "@crm/typescript-config",
"version": "0.0.0",
},
"packages/ui": {
- "name": "@repo/ui",
+ "name": "@crm/ui",
"version": "0.0.0",
"dependencies": {
- "react": "^19.2.0",
- "react-dom": "^19.2.0",
+ "@carbon/icons-react": "^11.82.0",
+ "@shadcn/react": "^0.2.1",
+ "class-variance-authority": "^0.7.1",
+ "clsx": "^2.1.1",
+ "cmdk": "^1.1.1",
+ "embla-carousel-react": "^8.6.0",
+ "input-otp": "^1.4.2",
+ "lucide-react": "^1.28.0",
+ "next-themes": "^0.4.6",
+ "nuqs": "^2.8.9",
+ "radix-ui": "^1.6.0",
+ "react-day-picker": "^10.0.1",
+ "react-hook-form": "^7.80.0",
+ "react-resizable-panels": "^4.12.2",
+ "recharts": "3.8.0",
+ "sonner": "^2.0.7",
+ "tailwind-merge": "^3.6.0",
+ "tw-animate-css": "^1.4.0",
+ "vaul": "^1.1.2",
},
"devDependencies": {
- "@repo/eslint-config": "*",
- "@repo/typescript-config": "*",
- "@types/node": "^22.15.3",
- "@types/react": "19.2.2",
- "@types/react-dom": "19.2.2",
- "eslint": "^9.39.1",
+ "@crm/typescript-config": "workspace:*",
+ "@tailwindcss/postcss": "^4",
+ "@types/node": "^24.10.1",
+ "@types/react": "^19.2.18",
+ "@types/react-dom": "^19",
+ "react": "19.2.4",
+ "react-dom": "19.2.4",
+ "shadcn": "^4.16.1",
+ "tailwindcss": "^4",
"typescript": "5.9.2",
},
+ "peerDependencies": {
+ "react": "^19.2.0",
+ "react-dom": "^19.2.0",
+ },
},
},
+ "trustedDependencies": [
+ "sharp",
+ ],
"packages": {
- "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+ "@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
+
+ "@angular-devkit/core": ["@angular-devkit/[email protected]", "", { "dependencies": { "ajv": "8.18.0", "ajv-formats": "3.0.1", "jsonc-parser": "3.3.1", "picomatch": "4.0.4", "rxjs": "7.8.1", "source-map": "0.7.4" }, "peerDependencies": { "chokidar": "^4.0.0" }, "optionalPeers": ["chokidar"] }, "sha512-3amNzoCVSKd7ah6l6lBQL4onwwJvqvam7FMoQBILrxtW5LB5ezh8gMSPuA4zJjKjoRzf9uoWdlzqv/84I52xZA=="],
+
+ "@angular-devkit/schematics": ["@angular-devkit/[email protected]", "", { "dependencies": { "@angular-devkit/core": "19.2.27", "jsonc-parser": "3.3.1", "magic-string": "0.30.17", "ora": "5.4.1", "rxjs": "7.8.1" } }, "sha512-/PZmyAlb2NGWPikRRuiWLdfHQd8Wrx6lX4HqvTcaDhlU43M3T0ud4PH2T3QDp7BzHYY92xtD8iPxX2asg67G1A=="],
+
+ "@angular-devkit/schematics-cli": ["@angular-devkit/[email protected]", "", { "dependencies": { "@angular-devkit/core": "19.2.27", "@angular-devkit/schematics": "19.2.27", "@inquirer/prompts": "7.3.2", "ansi-colors": "4.1.3", "symbol-observable": "4.0.0", "yargs-parser": "21.1.1" }, "bin": { "schematics": "bin/schematics.js" } }, "sha512-wHYH6SVXVykhLzovUHtYor3Nl4SpIiITi7r9DQDaKYUD4hpRBx25W6N9eGuakT9Vd5tV/x6wmvQFWQZQwFB7eA=="],
+
+ "@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@babel/compat-data": ["@babel/[email protected]", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="],
+
+ "@babel/core": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="],
+
+ "@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="],
+
+ "@babel/helper-annotate-as-pure": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw=="],
+
+ "@babel/helper-compilation-targets": ["@babel/[email protected]", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g=="],
+
+ "@babel/helper-create-class-features-plugin": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/helper-replace-supers": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/traverse": "^7.29.7", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg=="],
+
+ "@babel/helper-globals": ["@babel/[email protected]", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="],
+
+ "@babel/helper-member-expression-to-functions": ["@babel/[email protected]", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg=="],
+
+ "@babel/helper-module-imports": ["@babel/[email protected]", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g=="],
+
+ "@babel/helper-module-transforms": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg=="],
+
+ "@babel/helper-optimise-call-expression": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong=="],
+
+ "@babel/helper-plugin-utils": ["@babel/[email protected]", "", {}, "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw=="],
+
+ "@babel/helper-replace-supers": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ=="],
+
+ "@babel/helper-skip-transparent-expression-wrappers": ["@babel/[email protected]", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ=="],
+
+ "@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@babel/helper-validator-option": ["@babel/[email protected]", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="],
+
+ "@babel/helpers": ["@babel/[email protected]", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg=="],
+
+ "@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@babel/plugin-syntax-jsx": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A=="],
+
+ "@babel/plugin-syntax-typescript": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA=="],
+
+ "@babel/plugin-transform-modules-commonjs": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-module-transforms": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ=="],
+
+ "@babel/plugin-transform-react-display-name": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-+1wdDMGNb4UPeY3Q4L5yLiYe6TXPXubs4NjrgRFw13hPRLJfEMw2Q5OXkee6/IfdqePIeW4Jjwe3aBh7SdKz4Q=="],
+
+ "@babel/plugin-transform-react-jsx": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-module-imports": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", "@babel/plugin-syntax-jsx": "^7.29.7", "@babel/types": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-WsZulLVBUHXVj2cUcPVx6UE21TpalB6bHbSFErKT0Ib++ax24jjXe73FqlWvdylFOjiuPHYi6VCcgRad1ItN+A=="],
+
+ "@babel/plugin-transform-react-jsx-development": ["@babel/[email protected]", "", { "dependencies": { "@babel/plugin-transform-react-jsx": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-Xfy3UVMF04+ypnFbkhvfqtmvwfe92qwQdbGZVonhE+6v35GzlofmOnA1szaZqzb9xYWr0nl1e5EMmzi0DNON1g=="],
+
+ "@babel/plugin-transform-react-pure-annotations": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-H5E+HBgDpr6Q5t+Aj11tL7XkIui1jhbIoArVQnqjgXo5/3YxkN7ZEBcWF4RQlB0T4rrxJQbXS6kiFV6B7XTqUA=="],
+
+ "@babel/plugin-transform-typescript": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-create-class-features-plugin": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/plugin-syntax-typescript": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-jK52h8LaLc7JarhQV2ofeFMts4H7vnOXnqZNA6fYglBTZewRBE51KWt3BUltW1P+KoPsYkHoJeXePuz4zo2LMw=="],
+
+ "@babel/preset-react": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "@babel/plugin-transform-react-display-name": "^7.29.7", "@babel/plugin-transform-react-jsx": "^7.29.7", "@babel/plugin-transform-react-jsx-development": "^7.29.7", "@babel/plugin-transform-react-pure-annotations": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-C+PV1TFUPTmBQGoPBL8j2QmLpZ117YTCwxIZeJOM96GbYMFSc7/pOXU5lVykwnZxyTqQxRsvoRk6f2FktZgGHA=="],
+
+ "@babel/preset-typescript": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "@babel/plugin-syntax-jsx": "^7.29.7", "@babel/plugin-transform-modules-commonjs": "^7.29.7", "@babel/plugin-transform-typescript": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ=="],
+
+ "@babel/template": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
+
+ "@babel/traverse": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/types": "^7.29.7", "debug": "^4.3.1" } }, "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw=="],
+
+ "@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@better-auth/cli": ["@better-auth/[email protected]", "", { "dependencies": { "@babel/core": "^7.28.4", "@babel/preset-react": "^7.27.1", "@babel/preset-typescript": "^7.27.1", "@better-auth/core": "1.4.22", "@better-auth/telemetry": "1.4.22", "@better-auth/utils": "0.3.0", "@clack/prompts": "^0.11.0", "@mrleebo/prisma-ast": "^0.13.0", "@prisma/client": "^5.22.0", "@types/pg": "^8.15.5", "better-auth": "1.4.22", "better-sqlite3": "^12.2.0", "c12": "^3.2.0", "chalk": "^5.6.2", "commander": "^12.1.0", "dotenv": "^17.2.2", "drizzle-orm": "^0.41.0", "open": "^10.2.0", "pg": "^8.16.3", "prettier": "^3.6.2", "prompts": "^2.4.2", "semver": "^7.7.2", "yocto-spinner": "^0.2.3", "zod": "^4.3.5" }, "bin": { "better-auth": "dist/index.mjs" } }, "sha512-7azgrNiP1zJXMLqoLgCVj3KsZeYWLHeaGMapYlLblS6yU/o5n//sn1HBasRD2z4HBy2Etz/C7V483/mYvRHI2g=="],
+
+ "@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "zod": "^4.3.5" }, "peerDependencies": { "@better-auth/utils": "0.3.0", "@better-fetch/fetch": "1.1.21", "better-call": "1.1.8", "jose": "^6.1.0", "kysely": "^0.28.5", "nanostores": "^1.0.1" } }, "sha512-l20Ia10lI9iGL+bkjggamQP9lQuiAeB/EYfEx5EQ4AcPrLojG6Doc0UDw5VZM66VXcMGs3bgC8P7WiaJv4Walg=="],
+
+ "@better-auth/drizzle-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.25", "@better-auth/utils": "0.4.2", "drizzle-orm": "^0.45.2" }, "optionalPeers": ["drizzle-orm"] }, "sha512-ru/DeKjFPQUVeKkxF/ScazmPqIY7lwfkAV5Yt4j24wmn1Y8vFwoiPRnHgXUeZqBs10+nubaRwEqLF39CP6EhRw=="],
- "@eslint-community/eslint-utils": ["@eslint-community/[email protected]", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg=="],
+ "@better-auth/kysely-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.25", "@better-auth/utils": "0.4.2", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-zxiePhtN1YClS1irKYPVwWfN6kYp+QoYlz1hdQUOj8hXyo2aE/ny4RNAb6v332b0+U6Vu88EhYITRPdmvCo6uA=="],
- "@eslint-community/regexpp": ["@eslint-community/[email protected]", "", {}, "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew=="],
+ "@better-auth/memory-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.25", "@better-auth/utils": "0.4.2" } }, "sha512-GhEzTumc8yfTz+OZ6pMg06BA49xob49x1bX+1mEl/FStDJoSF+6mTfI5M2ytFxaiN89336/aUjkW8u+qRyLexw=="],
- "@eslint/config-array": ["@eslint/[email protected]", "", { "dependencies": { "@eslint/object-schema": "^2.1.7", "debug": "^4.3.1", "minimatch": "^3.1.5" } }, "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw=="],
+ "@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.25", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-ZtMmjcOdXR2Ziqx5y8ptTOaNpe0snNfALbBUPXJsgeyeRkDJDYzyLZ8MpuvNBTNllNeIFDbiXWAK5k+pEBZrUQ=="],
- "@eslint/config-helpers": ["@eslint/[email protected]", "", { "dependencies": { "@eslint/core": "^0.17.0" } }, "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw=="],
+ "@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.25", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-ym7B6Iqcry+/4aQnYpFwqP/GBIiXvjrm/5B6+0qmx8mkTY/apHFTpHuGzUYYNf4vPTtzF3eYY2+s2GOsomKaRg=="],
- "@eslint/core": ["@eslint/[email protected]", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ=="],
+ "@better-auth/telemetry": ["@better-auth/[email protected]", "", { "dependencies": { "@better-auth/utils": "0.3.0", "@better-fetch/fetch": "1.1.21" }, "peerDependencies": { "@better-auth/core": "1.4.22" } }, "sha512-ltoRysWQIbVlSgmVvn2EiFDkmLmtLAs9IVBvvwavGNFAklE7UcSlzR4BM5fllx5Vax927sou9MvZgUhgHRI62A=="],
- "@eslint/eslintrc": ["@eslint/[email protected]", "", { "dependencies": { "ajv": "^6.14.0", "debug": "^4.3.2", "espree": "^10.0.1", "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.3.0", "minimatch": "^3.1.5", "strip-json-comments": "^3.1.1" } }, "sha512-l2Ul9PrHsPCKcEY/ac7VgFj9D80C7S68sOKc618SyHDPK36s1XcFebXY0iTzUVn4Yq+YbwvSnDmCz9yxjX+QrA=="],
+ "@better-auth/utils": ["@better-auth/[email protected]", "", {}, "sha512-W+Adw6ZA6mgvnSnhOki270rwJ42t4XzSK6YWGF//BbVXL6SwCLWfyzBc1lN2m/4RM28KubdBKQ4X5VMoLRNPQw=="],
- "@eslint/js": ["@eslint/[email protected]", "", {}, "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A=="],
+ "@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g=="],
- "@eslint/object-schema": ["@eslint/[email protected]", "", {}, "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA=="],
+ "@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.6", "@biomejs/cli-darwin-x64": "2.5.6", "@biomejs/cli-linux-arm64": "2.5.6", "@biomejs/cli-linux-arm64-musl": "2.5.6", "@biomejs/cli-linux-x64": "2.5.6", "@biomejs/cli-linux-x64-musl": "2.5.6", "@biomejs/cli-win32-arm64": "2.5.6", "@biomejs/cli-win32-x64": "2.5.6" }, "bin": { "biome": "bin/biome" } }, "sha512-lxVNjv7UF6KfhMJfL9gaUHbWdJdHbsAj6OSmwSYNdhRuG67NxNQ4Xdvh3TUxsSK9sBzJBQhEJj3AopmmNJ5pSA=="],
- "@eslint/plugin-kit": ["@eslint/[email protected]", "", { "dependencies": { "@eslint/core": "^0.17.0", "levn": "^0.4.1" } }, "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA=="],
+ "@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zMOLZP4oMrjh6m1zcSj1ud2awUPgTuMVbmQhYYWL7J8HwCnbHHBvTm7VBTRuY7epT5bez76IpKYQ11ZAqHFlnw=="],
- "@humanfs/core": ["@humanfs/[email protected]", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="],
+ "@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-JAC1VqzvO7Th5ZplU0G2uGfkZbxEe9uDDektPAhF0JLusoz1w+T4okp2bkykI0bbaO2vslKiRfj4gU43JaGreA=="],
- "@humanfs/node": ["@humanfs/[email protected]", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="],
+ "@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-6XsYwCFkp5sMxl85ffhgeGpGgs6A7dRYFnkceZ7WVxvycuTnGdD5xa534Z3xfrBQ0JCMK/mujT6ZNPJoghedwg=="],
- "@humanfs/types": ["@humanfs/[email protected]", "", {}, "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q=="],
+ "@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-eUa3jeeYvfMt19LBeh6E5PUZpxnTC4JqNWo+EDjTtQjAr2xLGnWaxACtVU1DQqmHYbvThlJzLX+ZsYgrqh2qVw=="],
- "@humanwhocodes/module-importer": ["@humanwhocodes/[email protected]", "", {}, "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA=="],
+ "@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-Pop9VXCFUhFTMfFefZ39S+u2rOPyNp5iHlxbZRwXGACHLy2r0jjiRgJHmaEKJzL3SyxlVeGShXhvvElvWowonA=="],
- "@humanwhocodes/retry": ["@humanwhocodes/[email protected]", "", {}, "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ=="],
+ "@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-2Vp13QdKysH3HIWLaYLhUUwbK+jbZonJD1K+Lr0d0RO4wH7mkYd43vJixEDm8cUWrowoRz4UUHF1nm9Ae7ym8A=="],
+
+ "@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-tDGshcm6BdkZOCGnTDX0Y8/U4IfBSlnUU7T56nNDuPEfed+aHg+u8G36NB43fJVl0Os6+QURXIE1yuD7AaEofA=="],
+
+ "@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-WN05KwXnTO/2J45RQPvzZMXf7tZUIofHoR35xIPfCo7pQ2RFidxI8sfb5mGsaTxdMmEOzHzOPRCdA5/fCpc7xQ=="],
+
+ "@borewit/text-codec": ["@borewit/[email protected]", "", {}, "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ=="],
+
+ "@cacheable/utils": ["@cacheable/[email protected]", "", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="],
+
+ "@carbon/icon-helpers": ["@carbon/[email protected]", "", { "dependencies": { "@ibm/telemetry-js": "^1.5.0" } }, "sha512-sg5bL9Y/Vns4W7iNRaIMoNc/FtuzJE8G5VvCbC8xcrrNoZmfhhiPFHyU8CFhrf19HJdAxOvXShIBxmm3glLAYw=="],
+
+ "@carbon/icons-react": ["@carbon/[email protected]", "", { "dependencies": { "@carbon/icon-helpers": "^10.79.0", "@ibm/telemetry-js": "^1.5.0", "prop-types": "^15.8.1" }, "peerDependencies": { "react": ">=16" } }, "sha512-+fRNYyqR8aCZRSgMA8sJ+GVfCmS0pK8FaDl9rQDuy4ZqYldZ4Yj8K3YIxmcSLlvTxMmNtGAxoa80xlhXROYDQg=="],
+
+ "@chevrotain/cst-dts-gen": ["@chevrotain/[email protected]", "", { "dependencies": { "@chevrotain/gast": "10.5.0", "@chevrotain/types": "10.5.0", "lodash": "4.17.21" } }, "sha512-lhmC/FyqQ2o7pGK4Om+hzuDrm9rhFYIJ/AXoQBeongmn870Xeb0L6oGEiuR8nohFNL5sMaQEJWCxr1oIVIVXrw=="],
+
+ "@chevrotain/gast": ["@chevrotain/[email protected]", "", { "dependencies": { "@chevrotain/types": "10.5.0", "lodash": "4.17.21" } }, "sha512-pXdMJ9XeDAbgOWKuD1Fldz4ieCs6+nLNmyVhe2gZVqoO7v8HXuHYs5OV2EzUtbuai37TlOAQHrTDvxMnvMJz3A=="],
+
+ "@chevrotain/types": ["@chevrotain/[email protected]", "", {}, "sha512-f1MAia0x/pAVPWH/T73BJVyO2XU5tI4/iE7cnxb7tqdNTNhQI3Uq3XkqcoteTmD4t1aM0LbHCJOhgIDn07kl2A=="],
+
+ "@chevrotain/utils": ["@chevrotain/[email protected]", "", {}, "sha512-hBzuU5+JjB2cqNZyszkDHZgOSrUUT8V3dhgRl8Q9Gp6dAj/H5+KILGjbhDpc3Iy9qmqlm/akuOI2ut9VUtzJxQ=="],
+
+ "@clack/core": ["@clack/[email protected]", "", { "dependencies": { "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "sha512-p3y0FIOwaYRUPRcMO7+dlmLh8PSRcrjuTndsiA0WAFbWES0mLZlrjVoBRZ9DzkPFJZG6KGkJmoEAY0ZcVWTkow=="],
+
+ "@clack/prompts": ["@clack/[email protected]", "", { "dependencies": { "@clack/core": "0.5.0", "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "sha512-pMN5FcrEw9hUkZA4f+zLlzivQSeQf5dRGJjSUbvVYDLvpKCdQx5OaknvKzgbtXOizhP+SJJJjqEbOe55uKKfAw=="],
+
+ "@colors/colors": ["@colors/[email protected]", "", {}, "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ=="],
+
+ "@crm/auth": ["@crm/auth@workspace:packages/auth"],
+
+ "@crm/db": ["@crm/db@workspace:packages/db"],
+
+ "@crm/typescript-config": ["@crm/typescript-config@workspace:packages/typescript-config"],
+
+ "@crm/ui": ["@crm/ui@workspace:packages/ui"],
+
+ "@date-fns/tz": ["@date-fns/[email protected]", "", {}, "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg=="],
+
+ "@dotenvx/dotenvx": ["@dotenvx/[email protected]", "", { "dependencies": { "@dotenvx/primitives": "^0.8.0", "commander": "^11.1.0", "conf": "^10.2.0", "dotenv": "^17.2.1", "enquirer": "^2.4.1", "env-paths": "^2.2.1", "execa": "^5.1.1", "fdir": "^6.2.0", "ignore": "^5.3.0", "object-treeify": "1.1.33", "open": "^8.4.2", "picomatch": "^4.0.4", "systeminformation": "^5.22.11", "undici": "^7.11.0", "which": "^4.0.0", "yocto-spinner": "^1.1.0" }, "bin": { "dotenvx": "src/cli/dotenvx.js" } }, "sha512-/BITOC9dmS/edY2zQwZNicQ059O6RKabtQfyEafV0nGtfYRNHYy1DIPiYVcov40+tob9hfmBnbR963dS+EQ1DQ=="],
+
+ "@dotenvx/primitives": ["@dotenvx/[email protected]", "", {}, "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg=="],
+
+ "@electric-sql/pglite": ["@electric-sql/[email protected]", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="],
+
+ "@electric-sql/pglite-socket": ["@electric-sql/[email protected]", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.3" }, "bin": { "pglite-server": "dist/scripts/server.js" } }, "sha512-LAciWM0M1dCL8hlsxu2venbVZcdxema0BtDfpWYVqr+Y468UADw0pFWidhKw1M8sfJ8rdLT71tjMmnirf/IZRQ=="],
+
+ "@electric-sql/pglite-tools": ["@electric-sql/[email protected]", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.3" } }, "sha512-AlzLJTRJ8+UFgK8CmxIpyIpJ0+YaFw02IiOSdYrqxwPXdSyeIShz8aa9Tq+tYFXdPwcaMp/Fc80mQZ1dkOQ/wg=="],
+
+ "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+
+ "@floating-ui/core": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="],
+
+ "@floating-ui/dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/core": "^1.8.0", "@floating-ui/utils": "^0.2.12" } }, "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg=="],
+
+ "@floating-ui/react-dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/dom": "^1.8.0" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg=="],
+
+ "@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww=="],
+
+ "@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg=="],
+
+ "@ibm/telemetry-js": ["@ibm/[email protected]", "", { "bin": { "ibmtelemetry": "dist/collect.js" } }, "sha512-RO/9j+URJnSfseWg9ZkEX9p+a3Ousd33DBU7rOafoZB08RqdzxFVYJ2/iM50dkBuD0o7WX7GYt1sLbNgCoE+pA=="],
"@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
@@ -168,25 +389,97 @@
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
- "@next/env": ["@next/[email protected]", "", {}, "sha512-OZIbODWWAi0epQRCRjNe1VO45LOFBzgiyqmTLzIqWq6u1wrxKnAyz1HH6tgY/Mc81YzIjRPoYsPAEr4QV4l9TA=="],
+ "@inquirer/ansi": ["@inquirer/[email protected]", "", {}, "sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ=="],
+
+ "@inquirer/checkbox": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/ansi": "^1.0.2", "@inquirer/core": "^10.3.2", "@inquirer/figures": "^1.0.15", "@inquirer/type": "^3.0.10", "yoctocolors-cjs": "^2.1.3" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-VXukHf0RR1doGe6Sm4F0Em7SWYLTHSsbGfJdS9Ja2bX5/D5uwVOEjr07cncLROdBvmnvCATYEWlHqYmXv2IlQA=="],
+
+ "@inquirer/confirm": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/type": "^3.0.10" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ=="],
+
+ "@inquirer/core": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/ansi": "^1.0.2", "@inquirer/figures": "^1.0.15", "@inquirer/type": "^3.0.10", "cli-width": "^4.1.0", "mute-stream": "^2.0.0", "signal-exit": "^4.1.0", "wrap-ansi": "^6.2.0", "yoctocolors-cjs": "^2.1.3" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-43RTuEbfP8MbKzedNqBrlhhNKVwoK//vUFNW3Q3vZ88BLcrs4kYpGg+B2mm5p2K/HfygoCxuKwJJiv8PbGmE0A=="],
+
+ "@inquirer/editor": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/external-editor": "^1.0.3", "@inquirer/type": "^3.0.10" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-aLSROkEwirotxZ1pBaP8tugXRFCxW94gwrQLxXfrZsKkfjOYC1aRvAZuhpJOb5cu4IBTJdsCigUlf2iCOu4ZDQ=="],
+
+ "@inquirer/expand": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/type": "^3.0.10", "yoctocolors-cjs": "^2.1.3" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-nRzdOyFYnpeYTTR2qFwEVmIWypzdAx/sIkCMeTNTcflFOovfqUk+HcFhQQVBftAh9gmGrpFj6QcGEqrDMDOiew=="],
+
+ "@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],
+
+ "@inquirer/figures": ["@inquirer/[email protected]", "", {}, "sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g=="],
+
+ "@inquirer/input": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/type": "^3.0.10" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-kN0pAM4yPrLjJ1XJBjDxyfDduXOuQHrBB8aLDMueuwUGn+vNpF7Gq7TvyVxx8u4SHlFFj4trmj+a2cbpG4Jn1g=="],
+
+ "@inquirer/number": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/type": "^3.0.10" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-5Smv0OK7K0KUzUfYUXDXQc9jrf8OHo4ktlEayFlelCjwMXz0299Y8OrI+lj7i4gCBY15UObk76q0QtxjzFcFcg=="],
+
+ "@inquirer/password": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/ansi": "^1.0.2", "@inquirer/core": "^10.3.2", "@inquirer/type": "^3.0.10" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-zREJHjhT5vJBMZX/IUbyI9zVtVfOLiTO66MrF/3GFZYZ7T4YILW5MSkEYHceSii/KtRk+4i3RE7E1CUXA2jHcA=="],
+
+ "@inquirer/prompts": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/checkbox": "^4.3.2", "@inquirer/confirm": "^5.1.21", "@inquirer/editor": "^4.2.23", "@inquirer/expand": "^4.0.23", "@inquirer/input": "^4.3.1", "@inquirer/number": "^3.0.23", "@inquirer/password": "^4.0.23", "@inquirer/rawlist": "^4.1.11", "@inquirer/search": "^3.2.2", "@inquirer/select": "^4.4.2" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg=="],
+
+ "@inquirer/rawlist": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/type": "^3.0.10", "yoctocolors-cjs": "^2.1.3" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-+LLQB8XGr3I5LZN/GuAHo+GpDJegQwuPARLChlMICNdwW7OwV2izlCSCxN6cqpL0sMXmbKbFcItJgdQq5EBXTw=="],
+
+ "@inquirer/search": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/figures": "^1.0.15", "@inquirer/type": "^3.0.10", "yoctocolors-cjs": "^2.1.3" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-p2bvRfENXCZdWF/U2BXvnSI9h+tuA8iNqtUKb9UWbmLYCRQxd8WkvwWvYn+3NgYaNwdUkHytJMGG4MMLucI1kA=="],
+
+ "@inquirer/select": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/ansi": "^1.0.2", "@inquirer/core": "^10.3.2", "@inquirer/figures": "^1.0.15", "@inquirer/type": "^3.0.10", "yoctocolors-cjs": "^2.1.3" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-l4xMuJo55MAe+N7Qr4rX90vypFwCajSakx59qe/tMaC1aEHWLyw68wF4o0A4SLAY4E0nd+Vt+EyskeDIqu1M6w=="],
+
+ "@inquirer/type": ["@inquirer/[email protected]", "", { "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA=="],
+
+ "@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
+
+ "@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
+
+ "@jridgewell/resolve-uri": ["@jridgewell/[email protected]", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
+
+ "@jridgewell/source-map": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25" } }, "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA=="],
+
+ "@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
+
+ "@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@keyv/redis": ["@keyv/[email protected]", "", { "dependencies": { "@redis/client": "^5.10.0", "cluster-key-slot": "^1.1.2", "hookified": "^1.13.0" }, "peerDependencies": { "keyv": "^5.6.0" } }, "sha512-eKvW6pspvVaU5dxigaIDZr635/Uw6urTXL3gNbY9WTR8d3QigZQT+r8gxYSEOsw4+1cCBsC4s7T2ptR0WC9LfQ=="],
+
+ "@keyv/serialize": ["@keyv/[email protected]", "", {}, "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA=="],
+
+ "@lukeed/csprng": ["@lukeed/[email protected]", "", {}, "sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA=="],
+
+ "@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="],
+
+ "@mrleebo/prisma-ast": ["@mrleebo/[email protected]", "", { "dependencies": { "chevrotain": "^10.5.0", "lilconfig": "^2.1.0" } }, "sha512-XyroGQXcHrZdvmrGJvsA9KNeOOgGMg1Vg9OlheUsBOSKznLMDl+YChxbkboRHvtFYJEMRYmlV3uoo/njCw05iw=="],
+
+ "@nestjs/cache-manager": ["@nestjs/[email protected]", "", { "peerDependencies": { "@nestjs/common": "^9.0.0 || ^10.0.0 || ^11.0.0", "@nestjs/core": "^9.0.0 || ^10.0.0 || ^11.0.0", "cache-manager": ">=6", "keyv": ">=5", "rxjs": "^7.8.1" } }, "sha512-HMtiOfHz75NZX7mJn1VnZGLSachVI04TnUc5wvEogIaKwk5BDQHgtP5htxreizjv7oxKalJbuTyxtiF6bE+bgQ=="],
+
+ "@nestjs/cli": ["@nestjs/[email protected]", "", { "dependencies": { "@angular-devkit/core": "19.2.27", "@angular-devkit/schematics": "19.2.27", "@angular-devkit/schematics-cli": "19.2.27", "@inquirer/prompts": "7.10.1", "@nestjs/schematics": "^11.0.1", "ansis": "4.2.0", "chokidar": "4.0.3", "cli-table3": "0.6.5", "commander": "4.1.1", "fork-ts-checker-webpack-plugin": "9.1.0", "glob": "13.0.6", "node-emoji": "1.11.0", "ora": "5.4.1", "tsconfig-paths": "4.2.0", "tsconfig-paths-webpack-plugin": "4.2.0", "typescript": "5.9.3", "webpack": "5.106.2", "webpack-node-externals": "3.0.0" }, "peerDependencies": { "@swc/cli": "^0.1.62 || ^0.3.0 || ^0.4.0 || ^0.5.0 || ^0.6.0 || ^0.7.0 || ^0.8.0", "@swc/core": "^1.3.62" }, "optionalPeers": ["@swc/cli", "@swc/core"], "bin": { "nest": "bin/nest.js" } }, "sha512-aIHxQLSYtXShifA3zwWIeznEsZnNa3Iz2QRykFj+sl9IcbERBHr5nH87FRgywM+He3NxoF5WazHfR8FsmVeWxw=="],
+
+ "@nestjs/common": ["@nestjs/[email protected]", "", { "dependencies": { "file-type": "21.3.4", "iterare": "1.2.1", "load-esm": "1.0.3", "tslib": "2.8.1", "uid": "2.0.2" }, "peerDependencies": { "class-transformer": ">=0.4.1", "class-validator": ">=0.13.2", "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, "optionalPeers": ["class-transformer", "class-validator"] }, "sha512-bRImsxibie+AM7xjdwcrm/gr5YeacI65kSBNzTufa1Ib5iwziaY/lqMtRh9THq6pbV4e1HP9aI2ZxGUumnmaoQ=="],
+
+ "@nestjs/config": ["@nestjs/[email protected]", "", { "dependencies": { "dotenv": "17.4.1", "dotenv-expand": "12.0.3", "lodash": "4.18.1" }, "peerDependencies": { "@nestjs/common": "^10.0.0 || ^11.0.0", "rxjs": "^7.1.0" } }, "sha512-CJPjNitr0bAufSEnRe2N+JbnVmMmDoo6hvKCPzXgZoGwJSmp/dZPk9f/RMbuD/+Q1ZJPjwsRpq0vxna++Knwow=="],
+
+ "@nestjs/core": ["@nestjs/[email protected]", "", { "dependencies": { "fast-safe-stringify": "2.1.1", "iterare": "1.2.1", "path-to-regexp": "8.4.2", "tslib": "2.8.1", "uid": "2.0.2" }, "peerDependencies": { "@nestjs/common": "^11.0.0", "@nestjs/microservices": "^11.0.0", "@nestjs/platform-express": "^11.0.0", "@nestjs/websockets": "^11.0.0", "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, "optionalPeers": ["@nestjs/microservices", "@nestjs/platform-express", "@nestjs/websockets"] }, "sha512-06m63xIRj8+l8uOeh/8LnYupGubkyu4f+bPKIadaSui6vK9KpXgoz7HveT1yOVLcEt0M0oCOEW5EuEXZkEmBBQ=="],
+
+ "@nestjs/platform-express": ["@nestjs/[email protected]", "", { "dependencies": { "cors": "2.8.6", "express": "5.2.1", "multer": "2.2.0", "path-to-regexp": "8.4.2", "tslib": "2.8.1" }, "peerDependencies": { "@nestjs/common": "^11.0.0", "@nestjs/core": "^11.0.0" } }, "sha512-hU+9Sz4m+onHrR5AmelI59QKmY/Re546bPnygnpqqeQdHDiJpBgjWbL4t6Jr73CBpS60cpyng7WzjgphNB9iwA=="],
+
+ "@nestjs/schematics": ["@nestjs/[email protected]", "", { "dependencies": { "@angular-devkit/core": "19.2.24", "@angular-devkit/schematics": "19.2.24", "comment-json": "5.0.0", "jsonc-parser": "3.3.1", "pluralize": "8.0.0" }, "peerDependencies": { "prettier": "^3.0.0", "typescript": ">=4.8.2" }, "optionalPeers": ["prettier"] }, "sha512-lVxGZ46tcdItFMoXr6vyKWlnOsm1SZm/GUqAEDvy2RL4Q4O+3bkziAhrO7Y8JLssFUUvNFEGqAizI52WAxhjDw=="],
- "@next/eslint-plugin-next": ["@next/[email protected]", "", { "dependencies": { "fast-glob": "3.3.1" } }, "sha512-uF2z/qAK2q7B5/6CpnFcBRX6jOq5iCO+Uqh1UkJhXljX1JwLarLYhhoJadO6dPb6moTprOKewMXheBcbIoSbug=="],
+ "@nestjs/testing": ["@nestjs/[email protected]", "", { "dependencies": { "tslib": "2.8.1" }, "peerDependencies": { "@nestjs/common": "^11.0.0", "@nestjs/core": "^11.0.0", "@nestjs/microservices": "^11.0.0", "@nestjs/platform-express": "^11.0.0" }, "optionalPeers": ["@nestjs/microservices", "@nestjs/platform-express"] }, "sha512-B+VgRxeLaH7jkOMgAyUP3N3rpFlisQ7JRxixRbgHvG6a0VgKbbkNSofKExexCgKmQQak80undb3+2kE1lUBmRQ=="],
- "@next/swc-darwin-arm64": ["@next/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-/JZsqKzKt01IFoiLLAzlNqys7qk2F3JkcUhj50zuRhKDQkZNOz9E5N6wAQWprXdsvjRP4lTFj+/+36NSv5AwhQ=="],
+ "@next/env": ["@next/[email protected]", "", {}, "sha512-d0Z5Bc13Fa4nR8pFAKx2jay2yhJM16vlfHbTzYnUQAxlNb6B6lmn4hjt69lYNt4kRtyYP6gEM49lPRHNbIyneg=="],
- "@next/swc-darwin-x64": ["@next/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-/hV8erWq4SNlVgglUiW5UmQ5Hwy5EW/AbbXlJCn6zkfKxTy/E/U3V8U1Ocm2YCTUoFgQdoMxRyRMOW5jYy4ygg=="],
+ "@next/swc-darwin-arm64": ["@next/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0W1R0teHWJrqKX0FH20IzzIWAOuGtBxPGuObrxy1lE8hQvCFj49KE8a3WUg0D7sq6rn6zkM4c7YGUnhudBS6oA=="],
- "@next/swc-linux-arm64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-GkjL/Q7MWOwqWR9zoxu1TIHzkOI2l2BHCf7FzeQG87zPgs+6WDh+oC9Sw9ARuuL/FUk6JNCgKRkA6rEQYadUaw=="],
+ "@next/swc-darwin-x64": ["@next/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Hy5Ls099+aFUmOLmIgPfLqNi6iCwhL3uQCssz5rWk+5Nkc6TUKCE83DY5BbNylfm3+mfwcSFnLRfrZDJhVxdtw=="],
- "@next/swc-linux-arm64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-1ffhC6KY5qWLg5miMlKJp3dZbXelEfjuXt1qcp5WzSCQy36CV3y+JT7OC1WSFKizGQCDOcQbfkH/IjZP3cdRNA=="],
+ "@next/swc-linux-arm64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-+YqU2h1cQkHsGfvjAsrSmst8UIFBibBGm5x3Xgel8NLMiDQtNOM4sM2GOEMvG5YiOBNeN/Ykk8cQC2S0Xrqljg=="],
- "@next/swc-linux-x64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-FmbDcZQ8yJRq93EJSL6xaE0KK/Rslraf8fj1uViGxg7K4CKBCRYSubILJPEhjSgZurpcPQq12QNOJQ0DRJl6Hg=="],
+ "@next/swc-linux-arm64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0qjhiYBaKAqF63LA1ZWAAnKTzFUguAaZiRa5etMLGGPj/B6uEVjtIZldIzFEp3wHlB0koK6aTzqPtSdplTCjoA=="],
- "@next/swc-linux-x64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-HzjIHVkmGAwRbh/vzvoBWWEbb8BBZPxBvVbDQDvzHSf3D8RP/4vjw7MNLDXFF9Q1WEzeQyEj2zdxBtVAHu5Oyw=="],
+ "@next/swc-linux-x64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-7A3q26W+h7gnA15uqBToNuDqBEFZZcqh0mW2mn4AJh/G5pdg2RVE3n4slzLEliASZFG3NmsbEzng/x2Sh09mBg=="],
- "@next/swc-win32-arm64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-UMiFNQf5H7+1ZsZPxEsA064WEuFbRNq/kEXyepbCnSErp4f5iut75dBA8UeerFIG3vDaQNOfCpevnERPp2V+nA=="],
+ "@next/swc-linux-x64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-qSjL/uppm+cbh21s72Ss8gkiOhQ4dExWHNGOWy6eZV7STj5WsKehgxT61beSsOj+YYQuTplL376lOCdMQU5T8w=="],
- "@next/swc-win32-x64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-DRrNJKW+/eimrZgdhVN1uvkN1OI4j6Lpefwr44jKQ0YQzztlmOBUUzHuV5GxOMPK3nmodAYElUVCY8ZXo/IWeA=="],
+ "@next/swc-win32-arm64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-X6hzsOUJac/e7AWSbn9gQ9nzHld1xWP5iyjHpYWvud8pufB679O1xg4JDyKr8Xd69Jvd+kM2Der6uftiZCmjYA=="],
+
+ "@next/swc-win32-x64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-F6fakeHuFTLOPt0bslQJdf+xtT+WIP9DVn/m4y1w1mRnVPyh3D/cNvzlRkxM444xfm+IvvYNSOrKiA2CDJ0Uxw=="],
+
+ "@noble/ciphers": ["@noble/[email protected]", "", {}, "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA=="],
+
+ "@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg=="],
"@nodelib/fs.scandir": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],
@@ -194,536 +487,1986 @@
"@nodelib/fs.walk": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="],
- "@repo/eslint-config": ["@repo/eslint-config@workspace:packages/eslint-config"],
+ "@opentelemetry/semantic-conventions": ["@opentelemetry/[email protected]", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
- "@repo/typescript-config": ["@repo/typescript-config@workspace:packages/typescript-config"],
+ "@paralleldrive/cuid2": ["@paralleldrive/[email protected]", "", { "dependencies": { "@noble/hashes": "^1.1.5" } }, "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw=="],
- "@repo/ui": ["@repo/ui@workspace:packages/ui"],
+ "@prisma/adapter-pg": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.9.1", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-Ho2RK1KanQxLNSC0sR5bpiiVep10sWPLXCcxK+KXfI/Q69TMRbiafSvLPv3V9snimX72rMCqGlyJ4sBO4lKTAw=="],
- "@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g=="],
+ "@prisma/client": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/client-runtime-utils": "7.9.1" }, "peerDependencies": { "prisma": "*", "typescript": ">=5.4.0" }, "optionalPeers": ["prisma", "typescript"] }, "sha512-+xgrh2EhJVF79wC0yX5G4PI1Rdcm7Qn/nekNQ+t/O153wtNggruHal+fXHSa0QE+Tp/Cw5wvxeCEhZZ59xGm8Q=="],
- "@turbo/darwin-64": ["@turbo/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-po+7rfJfUnFXjWlcoN2RwhErgzCdRtBc1T26vYPcywHlggmCQiQe1uWaE4j+BibI2uY9/2pDoFzMN0rmSaPFOw=="],
+ "@prisma/client-runtime-utils": ["@prisma/[email protected]", "", {}, "sha512-mVIBGYdO5CFmK0HvjxrtfIyQQcPdb88pSCeVQriVQPVZyDovIWblpHfOgcS8QO187j3QF0ePArH8qPhp0AU2vg=="],
- "@turbo/darwin-arm64": ["@turbo/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+zB2btDJ00lnPRuqOvpVvgl4x34k/djZQGZTTCfjn7JgNCl8QFY5Njo5+dqkY1g/+9gbbsnAvWm9CmJg9ebcXA=="],
+ "@prisma/config": ["@prisma/[email protected]", "", { "dependencies": { "c12": "3.3.4", "deepmerge-ts": "7.1.5", "effect": "3.20.0", "empathic": "2.0.0" } }, "sha512-4znKhxTmXmuPye9Z6pbIyYb5VZlkZ05qG1L6Dr4g+7oTwc6V50Bs9XirFBDdjWt+H/AabMn9aUnxBcvj8z05aA=="],
- "@turbo/linux-64": ["@turbo/[email protected]", "", { "os": [ "linux", "android", ], "cpu": "x64" }, "sha512-K1dxqiVisyN7cViVsfQLs6xscQbYuI8aO2nbUhFURDACgEDfZRdP/b4CCxeosBJpcMfhYyiibWqJorCnvz9kKg=="],
+ "@prisma/debug": ["@prisma/[email protected]", "", {}, "sha512-/cpVZ4itxtcgB8GHBvZtcmuEjq+lWsLrRJxFMbwZrT1RIdtuKmUm7PPGo/wzfbYpBrk+9WmmBE8CHJw2rybKDQ=="],
- "@turbo/linux-arm64": ["@turbo/[email protected]", "", { "os": [ "linux", "android", ], "cpu": "arm64" }, "sha512-Gi77ibVnrE1fEmvr+/wBD/yvRqhwp/RQuCp2+//lv1U1wNFFyVg0V7Wj8FG9FXPFAw5QHReo8rxc9+wBSDZjzA=="],
+ "@prisma/dev": ["@prisma/[email protected]", "", { "dependencies": { "@electric-sql/pglite": "0.4.3", "@electric-sql/pglite-socket": "0.1.3", "@electric-sql/pglite-tools": "0.3.3", "@prisma/get-platform": "7.2.0", "@prisma/query-plan-executor": "7.2.0", "@prisma/streams-local": "0.1.11", "find-my-way": "9.7.0", "foreground-child": "3.3.1", "get-port-please": "3.2.0", "pathe": "2.0.3", "proper-lockfile": "4.1.2", "remeda": "2.33.4", "std-env": "3.10.0", "valibot": "1.4.2", "zeptomatch": "2.1.0" } }, "sha512-UvdZzmpFwknnfreh6Jije84ekkYGPYEJhXG1tFzCsCfQyzJifrOo38eZc0qajzvaC6OLUOrN9ML5XfCnEZL9DA=="],
- "@turbo/windows-64": ["@turbo/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-znnLO1haJPYTHoKMKwlAvlkjRiYbbhBzME6wIGaMd+fwir23U6jVd1ecaTWWi1fbnRVqxMfgDBKseQ/hLKb83g=="],
+ "@prisma/driver-adapter-utils": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.9.1" } }, "sha512-vmHehG7nn/heW32DXXpp13DxxAxVVe6n250oEt3dOL2E/4bt3olktKZN0mzSuxMMronyMSkbeW2uCOn3F4g8RQ=="],
- "@turbo/windows-arm64": ["@turbo/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-VN30vh3b3Czh2WzYHNTfF1FE0YMZ5aHsLO8dBMGHJewA6792wX6iJR8ZxlzFW6WdOu0gEAKIvlYhfyT81Wkm4Q=="],
+ "@prisma/engines": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.9.1", "@prisma/engines-version": "7.9.0-1.e922089b7d7502aff4249d5da3420f6fa55fc6ad", "@prisma/fetch-engine": "7.9.1", "@prisma/get-platform": "7.9.1" } }, "sha512-UprXSMNXx2NF5ow4pqaQtE8OuBz6K78B0wc0tn2L28G5r933iWp1DR9Do2qWrsNvvFIP3x6mpEWnQtckMO0Uhg=="],
- "@types/estree": ["@types/[email protected]", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
+ "@prisma/engines-version": ["@prisma/[email protected]", "", {}, "sha512-2BsPPFksz3CQUXG6af3rVCtJKg6+JJGJTtfgu2fU8DdXhOfkBjulCq8mwybCd6ge0/jhZq2kOtLAbmUDMyI1nA=="],
- "@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
+ "@prisma/fetch-engine": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.9.1", "@prisma/engines-version": "7.9.0-1.e922089b7d7502aff4249d5da3420f6fa55fc6ad", "@prisma/get-platform": "7.9.1" } }, "sha512-9DwxrNTeT25Orbu9CWh0CZvVlyY1lmscpbaeLZcOnuR7zcuFrt91YSmmOfIm7zJ08YOZ6mVzURKwLoMwEBcK8w=="],
- "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],
+ "@prisma/get-platform": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.2.0" } }, "sha512-k1V0l0Td1732EHpAfi2eySTezyllok9dXb6UQanajkJQzPUGi3vO2z7jdkz67SypFTdmbnyGYxvEvYZdZsMAVA=="],
- "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA=="],
+ "@prisma/query-plan-executor": ["@prisma/[email protected]", "", {}, "sha512-EOZmNzcV8uJ0mae3DhTsiHgoNCuu1J9mULQpGCh62zN3PxPTd+qI9tJvk5jOst8WHKQNwJWR3b39t0XvfBB0WQ=="],
- "@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw=="],
+ "@prisma/streams-local": ["@prisma/[email protected]", "", { "dependencies": { "ajv": "^8.12.0", "better-result": "^2.7.0", "env-paths": "^3.0.0", "proper-lockfile": "^4.1.2" } }, "sha512-0TcebL559MByKqTJ+SsrFIEg228iw8UCVRFckzgfRSiJqczhs+MuAgWOF9lnOIV/IVqvu+KMnFTH0eDeTQMpUg=="],
- "@typescript-eslint/eslint-plugin": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.65.0", "@typescript-eslint/type-utils": "8.65.0", "@typescript-eslint/utils": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.65.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-IEgob78X12rHpUmtcwFsXhZdVGJtwTVP8FiCLZkR6GlYVrl2PcuB+KhCE5BlVC/eQpQnu8WXRtkHZuPar+gCRA=="],
+ "@prisma/studio-core": ["@prisma/[email protected]", "", { "dependencies": { "@radix-ui/react-toggle": "1.1.10", "@visx/curve": "4.0.1-alpha.0", "@visx/event": "4.0.1-alpha.0", "@visx/grid": "4.0.1-alpha.0", "@visx/group": "4.0.1-alpha.0", "@visx/responsive": "4.0.1-alpha.0", "@visx/scale": "4.0.1-alpha.0", "@visx/shape": "4.0.1-alpha.0", "d3-array": "3.2.4", "d3-shape": "3.2.0", "elkjs": "0.11.1" }, "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" } }, "sha512-V2fX/nKEymNTrHXwfP26PGjoLStO35Ogu+ex7CFJbLrMYEcZxxZpiSNOs7px23Hk5mzLWvM5RsqG6Ka+rha+wg=="],
- "@typescript-eslint/parser": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.65.0", "@typescript-eslint/types": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0", "debug": "^4.4.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-CZ4nMxWwgu1HEEFNkeaCptra9QCtkmKdgf3sWh1rl1trIhmxLilgTV4cwcbQ4wemnT4sWQN8CaKOmdYx+g2gMA=="],
+ "@radix-ui/number": ["@radix-ui/[email protected]", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="],
- "@typescript-eslint/project-service": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.65.0", "@typescript-eslint/types": "^8.65.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-SxnPhbTsGahizDgbu7oqFH/xVtzIqMd/s+WtnSxNxJZJpLbdT5IPdzg8EZxO3+PoKahXmwJLeNQOpKJb3/bi7Q=="],
+ "@radix-ui/primitive": ["@radix-ui/[email protected]", "", {}, "sha512-rqWnm76nYT8HoNNqEjpgJ7Pw/DrBj5iBTrmEPo6HTX5+VJyBNOqTdv4g89G63HuR5g0AaENoAcH7Is5fF2kZ8Q=="],
- "@typescript-eslint/scope-manager": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0" } }, "sha512-Esbl8OSYiVxBokYgWPf7VVWg/BE798wXhimnn9ML9Pt5qoDf8bfQlgjlKXR/k98+AcNzlLKYrpCcrcuZ9DZLgg=="],
+ "@radix-ui/react-accessible-icon": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-WTQwcAvQf5sOcuUyi90lKPbhwcvQ+j55cjrSmeaN+L2vKU3DooOvlKw2MDeiJ5IkV5N905KW0/fGojKOBhD11A=="],
- "@typescript-eslint/tsconfig-utils": ["@typescript-eslint/[email protected]", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-j6GzGqCiRdA7Qhur2VVmKZAkBLfnHFQfx4TaJGL9RMveZqCo48jSHHO0DTgizEnGhtWnqmbtCUSrqSkdiY/0Hg=="],
+ "@radix-ui/react-accordion": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collapsible": "1.1.20", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-jDhG9FvAEnlhnjrsINbNXcUa4G+L1KqSkJSunkbKEzFRcAb52jvM0PjPxPRvhe1HNc5F5yc0yzzWeeqlH4yBIg=="],
- "@typescript-eslint/type-utils": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0", "@typescript-eslint/utils": "8.65.0", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-YjaZ7PRI5qY7ax2L3PbvX0rRyGtipAReCWs0mhhDBHjH/vl0g0BonaGXrKdKpMbIIsMIwDgbk/xzkBTyAltS5g=="],
+ "@radix-ui/react-alert-dialog": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dialog": "1.1.23", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-VAYOiQRqj3GPpYJE0I9J+X8Ip05cyVlNdKOFeiGS2Ou1HHGfpl0BxOyZm6nmVDyU+W+NF3/XLzmjHmVGydhwgA=="],
- "@typescript-eslint/types": ["@typescript-eslint/[email protected]", "", {}, "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg=="],
+ "@radix-ui/react-arrow": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-v4zggRcjadnI+ClKDuijlQEW4tw3NoaeHc/PwpKnLoLLKNUG4InLegkstooLcRIUWCs+8L22dGURCVuFfOKfnA=="],
- "@typescript-eslint/typescript-estree": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/project-service": "8.65.0", "@typescript-eslint/tsconfig-utils": "8.65.0", "@typescript-eslint/types": "8.65.0", "@typescript-eslint/visitor-keys": "8.65.0", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-JboAE2swaYt4tb1fHhHTABE2K+OLy09XfcTbhnk4Pw96f9dd2e9iYsJ28gBggHlo5z5x1rkyWvcPoTuNTd4oGg=="],
+ "@radix-ui/react-aspect-ratio": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-fy+dyVR+90nelK8rqIznFlxzx7uPcGbhxH8Nfr2bHb4UfSe+e3hklOC0luK0hDwVwnRX7xTRySpsrQVeW+/oNQ=="],
- "@typescript-eslint/utils": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.65.0", "@typescript-eslint/types": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-gXiwIHsYreboxeJucHKPvgwl7dXt50mF8s1/c00cP/WoVTyWKFdtfhRWwZiXYFU5H2O8vVoSLNrexFZjYS/SGA=="],
+ "@radix-ui/react-avatar": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-4ULOTJ/mqy2hT9GlWa/MFHxHSvH3nJzHnZM1waNsc5Bonv7i70aNenghXmD97S6OJ81ekXONGGt4nT1r0PfEdA=="],
- "@typescript-eslint/visitor-keys": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/types": "8.65.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-8C71BQkGjiMmXtop7pHVJu1l2NNShFdkCyD6a2ezzs5vU/L3LRtb69EtcteFwz0mYMPzIgOw0n6OV4VBUWZd7A=="],
+ "@radix-ui/react-checkbox": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Gnptr9pDDQxD3hgq2dtPbtrp/c2qH1mBwIzw3X/ivrMb2e1t0jMTi606fVEqFPaQR1ggXIVQWKj3P2WW9v7zGQ=="],
- "acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="],
+ "@radix-ui/react-collapsible": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mcGesGplBnzN2sbvJETzpCNfSMyPnb29q1GRLU+Ib7bJrpIG2ywmRoh2V5VbA2uNvKikKUlVbAPks7JDjz4A8Q=="],
- "acorn-jsx": ["[email protected]", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="],
+ "@radix-ui/react-collection": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA=="],
- "ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
+ "@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
- "ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
+ "@radix-ui/react-context": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RHCUGwKHDr0hDGg4X7ma4JG4/+12qxw8rkh5QKdDldlCvtja6nUx1Ef/8HVrJze81lEsgLQlqjzjGNHantgnQA=="],
- "argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
+ "@radix-ui/react-context-menu": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-CtXP35dxaB5T3zXSd+E3uHe/QpXcpYnZmxp6OaIbfthtfW4wyb77M23BG+bwIJDtsMwEP/YssdsmNyZu7jhWew=="],
- "array-buffer-byte-length": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "is-array-buffer": "^3.0.5" } }, "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw=="],
+ "@radix-ui/react-dialog": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Ksw4WeROkO4rC9k/onilX/Ao2Cr1ku1unMNH+XSCcP4jSXYu7HDsg9n4ojMjVb22XpYjAQ9qfrFlVbru1vXDUA=="],
- "array-includes": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.4", "define-properties": "^1.2.1", "es-abstract": "^1.24.0", "es-object-atoms": "^1.1.1", "get-intrinsic": "^1.3.0", "is-string": "^1.1.1", "math-intrinsics": "^1.1.0" } }, "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ=="],
+ "@radix-ui/react-direction": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-5pzg4FGQNpExhnhT2zlrP1wZFaYCd1K0nYWoFAdcYoYK868IEigqMX3B3f8yIoRlAhAeDWciLI6ZdCKHF9P4Vg=="],
- "array.prototype.findlast": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", "es-abstract": "^1.23.2", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "es-shim-unscopables": "^1.0.2" } }, "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ=="],
+ "@radix-ui/react-dismissable-layer": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-effect-event": "0.0.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w=="],
- "array.prototype.flat": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.5", "es-shim-unscopables": "^1.0.2" } }, "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg=="],
+ "@radix-ui/react-dropdown-menu": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-geq8l2rJkxvkXsT9RMgtUE3P8pITFpTsvYpbySi1IH4fZEABD/Gp85myayFgxk0ktljGMJnCbeFkyTusvSvv7g=="],
- "array.prototype.flatmap": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.5", "es-shim-unscopables": "^1.0.2" } }, "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg=="],
+ "@radix-ui/react-focus-guards": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ=="],
- "array.prototype.tosorted": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", "es-abstract": "^1.23.3", "es-errors": "^1.3.0", "es-shim-unscopables": "^1.0.2" } }, "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA=="],
+ "@radix-ui/react-focus-scope": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-wmRZ2WWLvmt6KHy2rNPOdPUjwq5xOHY02+m+udwJTn0aNIox/rkskAvJTyTLGhPK6KgrUjlJUJpgmx/+wFiFIQ=="],
- "arraybuffer.prototype.slice": ["[email protected]", "", { "dependencies": { "array-buffer-byte-length": "^1.0.1", "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.5", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "is-array-buffer": "^3.0.4" } }, "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ=="],
+ "@radix-ui/react-form": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-label": "2.1.15", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Q4TLEn2A7TAypxwmd6R9EwrlXDvkfYSDMrq9/887AXAGh+G1rH+kYJKSTv+Si9Y0JPKTwKYv6PviAJosysNimA=="],
- "async-function": ["[email protected]", "", {}, "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA=="],
+ "@radix-ui/react-hover-card": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-H8qONfZd3ltrU3+jHCIgITbWo6e1iTKvP9DHdrvYbX48ooRM5FjEDTn16AMwdfuOGkWdZEhpl3PLL/Wk/AnHDQ=="],
- "available-typed-arrays": ["[email protected]", "", { "dependencies": { "possible-typed-array-names": "^1.0.0" } }, "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ=="],
+ "@radix-ui/react-id": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="],
- "balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
+ "@radix-ui/react-label": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-o/rdYEwZTTo5tjknnPeyQFU45kUC4i/XyeDPP+HGyi6XqpOP6Zf5Ya5vh/Yfe9Id5JiuWnnAx2XqIeD3UYZt0g=="],
- "baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-zAgkquC2WYF0PIc6XbNYkA2uuxxFavzgmX61R+dHDUa558V8Ejf8ozTZFR6QzM24RWu4kBcRkhJ5kpz77j9fnQ=="],
+ "@radix-ui/react-menu": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-callback-ref": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-uW7RVuU6Lp/ZtfeY4b3kL32zccgEWvPv1+cf17ubYzHa9cL8AHokmk36cG/XEiH/smbQvumnieXX9j/e9RqJWA=="],
- "brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
+ "@radix-ui/react-menubar": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-eeVs0vf7cuqXaM0qLQCPcufImiJNVBXdJDLu7ZGYl2732UH23Qat/foNGrr6vYV3/DdTsBqASoggUFgH14OcZA=="],
- "braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
+ "@radix-ui/react-navigation-menu": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ou7iLEJ+yrhQndkkA4U21XIdS/CS45F4iXIkTZcb6/Ne9EMsOuDudVmCwmDnfFZZ+y1FZqXRNSIgBy+YMvZVZg=="],
- "call-bind": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "get-intrinsic": "^1.3.0", "set-function-length": "^1.2.2" } }, "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ=="],
+ "@radix-ui/react-one-time-password-field": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Tj9P6ntAJEw52oq/F0AGknXR4XncxEt7XU47O3xJQOiWfLzEy3d9gtgKfvjSzGxzHkfL+VzvxGu2KTFsloJqXw=="],
- "call-bind-apply-helpers": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
+ "@radix-ui/react-password-toggle-field": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-is-hydrated": "0.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-4gvFnmDXu3dgj21CqsufzIameRvlRd4SBqaWhcrlrNhRo0Y5i/49AmRJYe1fdAM3G2VNBbmin4b0D6cdQocwgw=="],
- "call-bound": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
+ "@radix-ui/react-popover": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mw58MrBlyHWFisTOYignD0vf/3gdcgAR+9of1s9G/38CbFiUwH1nCDkc0AUM9IrXFgN5Ue8n45j9WCgyM1sbiQ=="],
- "callsites": ["[email protected]", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="],
+ "@radix-ui/react-popper": ["@radix-ui/[email protected]", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-rect": "1.1.4", "@radix-ui/react-use-size": "1.1.4", "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UsJrrd7w4wuKKTdvd/DNERVlwSlUcyXzjhyDwBk+3aPOsCjOY6ZSbxuw8E6lZTjjfP8Cpd0J8VVkrYUWyGYXyg=="],
- "caniuse-lite": ["[email protected]", "", {}, "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw=="],
+ "@radix-ui/react-portal": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ=="],
- "chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
+ "@radix-ui/react-presence": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw=="],
- "client-only": ["[email protected]", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="],
+ "@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
- "color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
+ "@radix-ui/react-progress": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-5XnomAsoZZCY+KNTxbIghpGqPruZvKFNlvcAljVAOdDRDsH4/OZQxhtwo5wdtoDM5R6MhJBb2sPnDuRFep3lzg=="],
- "color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
+ "@radix-ui/react-radio-group": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-cgYFEkntCxppHZgtSZ+7vh0wbZQ+IC7PPMw8DSnRG27B6kDd32/Zw0OJt7dGDigCoprMuWHjg2PvUn3PYvPFoQ=="],
- "concat-map": ["[email protected]", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
+ "@radix-ui/react-roving-focus": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-V9jI6hDjT7l3jsCQD9bLNvDLM3tH/gdbOTp7Tefp3hbbgCGQoK7tUvrWiRlcoBHIZ809ElXwNQwVo0B98LuTXQ=="],
- "cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
+ "@radix-ui/react-scroll-area": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Zn5Cd171wxsO3Dfg8HaW6RifTb9CYTKQJHs/G4+LN1GfmJpaQMZQyQxMprVPHpaz7QY4l9BxK2JwQuzHsXC8nA=="],
- "csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+ "@radix-ui/react-select": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-WFGImkmbzcfxeIwq/+4HvRN0pizBwbwQUED4I13ezQsDdfl38ZntN6TmR8XaSzPBqoCToe8rF75j6NPNDSzhbg=="],
- "data-view-buffer": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-data-view": "^1.0.2" } }, "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ=="],
+ "@radix-ui/react-separator": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-jOLO4lssEzWpoDu7G+Ze4VjwMRUBt291pnZD0gmalREZipnTX3wadQo7Fy48GCTfe14/YRN6rw/rOJqrE85Wxw=="],
- "data-view-byte-length": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-data-view": "^1.0.2" } }, "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ=="],
+ "@radix-ui/react-slider": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mTSLf1GC/C0moWjTbvCM6Qn/gBjvlFt1azuWF2v7MN5C3Zq2U2J2lN3ZEYkpujuOU5Ro7A28wkviSxaKnG0BYg=="],
- "data-view-byte-offset": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "is-data-view": "^1.0.1" } }, "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ=="],
+ "@radix-ui/react-slot": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q=="],
- "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
+ "@radix-ui/react-switch": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-48tB/4dn2UVLBCYhTu9AuR63IHl73l/qLbLgxd86noTUor4/K4LFDAcYjK+isP5313qxaFpjPVogE7+Y0/V3Kw=="],
- "deep-is": ["[email protected]", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
+ "@radix-ui/react-tabs": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UKxJlZid7FVtsk/WTxj4i4uSEgj2Au+KBbS7SQyTlzMhhn+86Cz3tISZdTa87bfEfcuvZezf2ZsxD4xuEKtkog=="],
- "define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
+ "@radix-ui/react-toast": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ofhyAsYaocRGOs/n0XWdUOSVzEAG6BfrMVM8z0c0kLEWY38w/0WuMFPTJP/HVaZPYkMvHZoKIIhNcjbTCBILPg=="],
- "define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
+ "@radix-ui/react-toggle": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-7lonPlKfSacd20GlOBx2ltuVKz9oqWYZz+oMQyOltw6t1y2nyftj2ZmwwUHYn49kqfDWcp8dNZm5NgV+5Z+mug=="],
- "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
+ "@radix-ui/react-toggle-group": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-toggle": "1.1.18", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-OtnwuSVjd1Ofi+AdnvhsjQdyuhCDwYs1w9RyB5BN/OavXOVQo42SYqQjwUnbPnaiPFBpQ9aX70dWeee+v2oBLA=="],
- "docs": ["docs@workspace:apps/docs"],
+ "@radix-ui/react-toolbar": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-separator": "1.1.15", "@radix-ui/react-toggle-group": "1.1.19" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Ph0IvtYw4VB12ZnZg+YtrGs8yJQsnizwo/zu0R4Y/nWugtJzA7Pg1eWeuDR9+LSqn+xjamss+UOSOJJJ4gx8jw=="],
- "doctrine": ["[email protected]", "", { "dependencies": { "esutils": "^2.0.2" } }, "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw=="],
+ "@radix-ui/react-tooltip": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-6EamKFRRnlpdadndbZ6LMwycfwkwPte1B42hs6QA0gYhjaOKqW4PZ4pjaW9UrlDX5eVt/OjncE7BFTPL5nmZhg=="],
- "dotenv": ["[email protected]", "", {}, "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ=="],
+ "@radix-ui/react-use-callback-ref": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-R6OUY2e2fA6Yn6s+VSx5KBV6Nx8LQEhu+cz7LCej18rQ1HLyg9PSC9jP/ZNx0o6FAIK9c0F1kHylzSxKsdlkrQ=="],
- "dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
+ "@radix-ui/react-use-controllable-state": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-uEQJGT97ZA/TgP/Hydw47lHu+/vQj6z/0jA+WeTbK1o9Rx45GImjpD0tc3W5ad3D6XTSR6e1yEO0FvGq6WQfVQ=="],
- "es-abstract": ["[email protected]", "", { "dependencies": { "array-buffer-byte-length": "^1.0.2", "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "data-view-buffer": "^1.0.2", "data-view-byte-length": "^1.0.2", "data-view-byte-offset": "^1.0.1", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "es-set-tostringtag": "^2.1.0", "es-to-primitive": "^1.3.0", "function.prototype.name": "^1.1.8", "get-intrinsic": "^1.3.0", "get-proto": "^1.0.1", "get-symbol-description": "^1.1.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "internal-slot": "^1.1.0", "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", "is-regex": "^1.2.1", "is-set": "^2.0.3", "is-shared-array-buffer": "^1.0.4", "is-string": "^1.1.1", "is-typed-array": "^1.1.15", "is-weakref": "^1.1.1", "math-intrinsics": "^1.1.0", "object-inspect": "^1.13.4", "object-keys": "^1.1.1", "object.assign": "^4.1.7", "own-keys": "^1.0.1", "regexp.prototype.flags": "^1.5.4", "safe-array-concat": "^1.1.3", "safe-push-apply": "^1.0.0", "safe-regex-test": "^1.1.0", "set-proto": "^1.0.0", "stop-iteration-iterator": "^1.1.0", "string.prototype.trim": "^1.2.10", "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", "typed-array-buffer": "^1.0.3", "typed-array-byte-length": "^1.0.3", "typed-array-byte-offset": "^1.0.4", "typed-array-length": "^1.0.7", "unbox-primitive": "^1.1.0", "which-typed-array": "^1.1.19" } }, "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg=="],
+ "@radix-ui/react-use-effect-event": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg=="],
- "es-abstract-get": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "es-object-atoms": "^1.1.2", "is-callable": "^1.2.7", "object-inspect": "^1.13.4" } }, "sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg=="],
+ "@radix-ui/react-use-escape-keydown": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ge3ipobwSXTj4JyVtswQ7qZj0ZHdtbGuOno/LrgAAeSxtsJ6Vs4Gz5IkPH2bmqpjcLUFoqGhA/mueuIf63UXlA=="],
- "es-define-property": ["[email protected]", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
+ "@radix-ui/react-use-is-hydrated": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw=="],
- "es-errors": ["[email protected]", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
+ "@radix-ui/react-use-layout-effect": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="],
- "es-iterator-helpers": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "define-properties": "^1.2.1", "es-abstract": "^1.24.2", "es-errors": "^1.3.0", "es-set-tostringtag": "^2.1.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.3.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "internal-slot": "^1.1.0", "iterator.prototype": "^1.1.5", "math-intrinsics": "^1.1.0" } }, "sha512-c/A0P0oxkACDc+cKWw8evLXK83oBKgn0qPOqCYT4x9uolpCIJAcYvJC9QYKNDRPsTeGyCrQ326jrvgZWdCdK5Q=="],
+ "@radix-ui/react-use-previous": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg=="],
- "es-object-atoms": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="],
+ "@radix-ui/react-use-rect": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ=="],
- "es-set-tostringtag": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="],
+ "@radix-ui/react-use-size": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-D3anSY15EJoxrihpsXI6SMrmmonnQtR2ni7arO+Lfdg3O95b9hNXxONk8jA5C8ANdF/h5HMAxejgs8PWJ6rlhw=="],
- "es-shim-unscopables": ["[email protected]", "", { "dependencies": { "hasown": "^2.0.2" } }, "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw=="],
+ "@radix-ui/react-visually-hidden": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-NFS86RYYZb4/exihaESBGOpMJFz8MGLAfu3mOBSGByVnVPC9JPASfYubxd/8KbkQK0sYAv8lVQDEQukDX/qXvQ=="],
- "es-to-primitive": ["[email protected]", "", { "dependencies": { "es-abstract-get": "^1.0.0", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "is-callable": "^1.2.7", "is-date-object": "^1.1.0", "is-symbol": "^1.1.1" } }, "sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw=="],
+ "@radix-ui/rect": ["@radix-ui/[email protected]", "", {}, "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw=="],
- "escape-string-regexp": ["[email protected]", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
+ "@redis/client": ["@redis/[email protected]", "", { "dependencies": { "cluster-key-slot": "1.1.2" }, "peerDependencies": { "@node-rs/xxhash": "^1.1.0", "@opentelemetry/api": ">=1 <2" }, "optionalPeers": ["@node-rs/xxhash", "@opentelemetry/api"] }, "sha512-7aPGWeqA3uFm43o19umzdl16CEjK/JQGtSXVPevplTaOU3VJA/rseBC1QvYUz9lLDIMBimc4SW/zrW4S89BaCA=="],
- "eslint": ["[email protected]", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.21.2", "@eslint/config-helpers": "^0.4.2", "@eslint/core": "^0.17.0", "@eslint/eslintrc": "^3.3.6", "@eslint/js": "9.39.5", "@eslint/plugin-kit": "^0.4.1", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.14.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^8.4.0", "eslint-visitor-keys": "^4.2.1", "espree": "^10.4.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw=="],
+ "@reduxjs/toolkit": ["@reduxjs/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw=="],
- "eslint-config-prettier": ["[email protected]", "", { "peerDependencies": { "eslint": ">=7.0.0" }, "bin": { "eslint-config-prettier": "bin/cli.js" } }, "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w=="],
+ "@sec-ant/readable-stream": ["@sec-ant/[email protected]", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="],
- "eslint-plugin-only-warn": ["[email protected]", "", {}, "sha512-j37hwfaQDEOfkZ1Dpvu/HnWLavlzQxQxfbrU/9Jb4R9qzrE1eTYuRJyrxq7LzLRI8miG5FOV6veoUVhx7AI84w=="],
+ "@shadcn/react": ["@shadcn/[email protected]", "", { "peerDependencies": { "@types/react": ">=19", "react": ">=19" }, "optionalPeers": ["@types/react", "react"] }, "sha512-5krgi3dRMKb5jH6a+qPzVJUy/54s0kKE4Rw4LjDfLqOdVQTWKUgxWf1kW8r912I0jX/Lzxqc+pgjkjWxUIK5BQ=="],
- "eslint-plugin-react": ["[email protected]", "", { "dependencies": { "array-includes": "^3.1.8", "array.prototype.findlast": "^1.2.5", "array.prototype.flatmap": "^1.3.3", "array.prototype.tosorted": "^1.1.4", "doctrine": "^2.1.0", "es-iterator-helpers": "^1.2.1", "estraverse": "^5.3.0", "hasown": "^2.0.2", "jsx-ast-utils": "^2.4.1 || ^3.0.0", "minimatch": "^3.1.2", "object.entries": "^1.1.9", "object.fromentries": "^2.0.8", "object.values": "^1.2.1", "prop-types": "^15.8.1", "resolve": "^2.0.0-next.5", "semver": "^6.3.1", "string.prototype.matchall": "^4.0.12", "string.prototype.repeat": "^1.0.0" }, "peerDependencies": { "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" } }, "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA=="],
+ "@sindresorhus/merge-streams": ["@sindresorhus/[email protected]", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
- "eslint-plugin-react-hooks": ["[email protected]", "", { "peerDependencies": { "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" } }, "sha512-+f15FfK64YQwZdJNELETdn5ibXEUQmW1DZL6KXhNnc2heoy/sg9VJJeT7n8TlMWouzWqSWavFkIhHyIbIAEapg=="],
+ "@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
- "eslint-plugin-turbo": ["[email protected]", "", { "dependencies": { "dotenv": "16.0.3" }, "peerDependencies": { "eslint": ">6.6.0", "turbo": ">2.0.0" } }, "sha512-D6/FZUlP5IkZl/Wahoyi9q/UYFnyuh0cyqf3x5aHJNTmlu+bC6+h03cNPzPoQS7708ts54KYreUZW+FdRG5BWg=="],
+ "@standard-schema/utils": ["@standard-schema/[email protected]", "", {}, "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="],
- "eslint-scope": ["[email protected]", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg=="],
+ "@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g=="],
- "eslint-visitor-keys": ["[email protected]", "", {}, "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ=="],
+ "@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="],
- "espree": ["[email protected]", "", { "dependencies": { "acorn": "^8.15.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^4.2.1" } }, "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ=="],
+ "@tailwindcss/oxide": ["@tailwindcss/[email protected]", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.3", "@tailwindcss/oxide-darwin-arm64": "4.3.3", "@tailwindcss/oxide-darwin-x64": "4.3.3", "@tailwindcss/oxide-freebsd-x64": "4.3.3", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", "@tailwindcss/oxide-linux-x64-musl": "4.3.3", "@tailwindcss/oxide-wasm32-wasi": "4.3.3", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" } }, "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA=="],
- "esquery": ["[email protected]", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="],
+ "@tailwindcss/oxide-android-arm64": ["@tailwindcss/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw=="],
- "esrecurse": ["[email protected]", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],
+ "@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw=="],
- "estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
+ "@tailwindcss/oxide-darwin-x64": ["@tailwindcss/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw=="],
- "esutils": ["[email protected]", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
+ "@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw=="],
- "fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
+ "@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ=="],
- "fast-glob": ["[email protected]", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.4" } }, "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg=="],
+ "@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w=="],
- "fast-json-stable-stringify": ["[email protected]", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="],
+ "@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA=="],
- "fast-levenshtein": ["[email protected]", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
+ "@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w=="],
- "fastq": ["[email protected]", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="],
+ "@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img=="],
- "fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
+ "@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.11.1", "@emnapi/runtime": "^1.11.1", "@emnapi/wasi-threads": "^1.2.2", "@napi-rs/wasm-runtime": "^1.1.4", "@tybys/wasm-util": "^0.10.2", "tslib": "^2.8.1" }, "cpu": "none" }, "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ=="],
- "file-entry-cache": ["[email protected]", "", { "dependencies": { "flat-cache": "^4.0.0" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="],
+ "@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ=="],
- "fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
+ "@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw=="],
- "find-up": ["[email protected]", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
+ "@tailwindcss/postcss": ["@tailwindcss/[email protected]", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "postcss": "^8.5.16", "tailwindcss": "4.3.3" } }, "sha512-JTSZZGQi1AyKirbLN3azmjVzef92tcX7h+iSqPdaeStyFpGpDlKvvpxeOE8njhbUanbRwr3z8DyzhICWnMtQeg=="],
- "flat-cache": ["[email protected]", "", { "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.4" } }, "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw=="],
+ "@tanstack/query-core": ["@tanstack/[email protected]", "", {}, "sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw=="],
- "flatted": ["[email protected]", "", {}, "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q=="],
+ "@tanstack/query-devtools": ["@tanstack/[email protected]", "", {}, "sha512-z5IPHnDX3aUWeTWlRKLyooBQekaCAw4xRpZqPQ390RiWTDBcTynjpPT221BArw0u2+pnQMdGvPQI9YNNubBcmA=="],
- "for-each": ["[email protected]", "", { "dependencies": { "is-callable": "^1.2.7" } }, "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg=="],
+ "@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.101.4" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-yRg2pfOCxIs4ZJW3XYYHU/WgtD04FHSnfHlpRT7h7pR77hwkdRG4wxbKe4aq6P0RvXUTBSQpQeadS1SUYUe+KA=="],
- "function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
+ "@tanstack/react-query-devtools": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-devtools": "5.101.4" }, "peerDependencies": { "@tanstack/react-query": "^5.101.4", "react": "^18 || ^19" } }, "sha512-VeK2gtmfj7kvRBjtxS7TKxt/6qKhn8VzabY4UiYMr7NV9CddjSRYRgeYyld+NpjAkgMV9dd+2Qdr8ah5I03NeA=="],
- "function.prototype.name": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "functions-have-names": "^1.2.3", "has-property-descriptors": "^1.0.2", "hasown": "^2.0.4", "is-callable": "^1.2.7", "is-document.all": "^1.0.0" } }, "sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew=="],
+ "@thallesp/nestjs-better-auth": ["@thallesp/[email protected]", "", { "peerDependencies": { "@nestjs/common": "^11.1.6", "@nestjs/core": "^11.1.6", "@nestjs/graphql": "^13.1.0", "@nestjs/websockets": "^11.1.6", "better-auth": ">=1.5.0 <2.0.0", "express": "^5.1.0", "graphql": "^16.11.0", "qs": "^6.14.0", "typescript": "^5.9.2 || ^6.0.0" }, "optionalPeers": ["@nestjs/graphql", "@nestjs/websockets", "express", "graphql", "qs"] }, "sha512-Grq74scQ4AdEjrAr9mE8780u9N4fn+X/qz7DTHa/K37g+RPw+R3Yde4leRz/UIqsLx0o8p1B5wRGPnM65Q+ZsQ=="],
- "functions-have-names": ["[email protected]", "", {}, "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ=="],
+ "@tokenizer/inflate": ["@tokenizer/[email protected]", "", { "dependencies": { "debug": "^4.4.3", "token-types": "^6.1.1" } }, "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA=="],
- "generator-function": ["[email protected]", "", {}, "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g=="],
+ "@tokenizer/token": ["@tokenizer/[email protected]", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="],
- "get-intrinsic": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
+ "@trpc/client": ["@trpc/[email protected]", "", { "peerDependencies": { "@trpc/server": "11.18.0", "typescript": ">=5.7.2" }, "bin": { "intent": "bin/intent.js" } }, "sha512-wOqeg3Fvl25V1ZisQhUD3K8G60ZJDlSGJNSyeXrLH24xAo5w6GSR2Kzb1cSNY9Y+IQ2YZvYGZstBU+V/ulo/ow=="],
- "get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
+ "@trpc/server": ["@trpc/[email protected]", "", { "peerDependencies": { "typescript": ">=5.7.2" }, "bin": { "intent": "bin/intent.js" } }, "sha512-JAvXOuNTxgXjIDfQaOvDq1j66LMNfDJUH1IU7Slfn8EvRv2EkH6ehu3A7zpYhjO0syHHiYg77v2lG2JFJgvw7Q=="],
- "get-symbol-description": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6" } }, "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg=="],
+ "@trpc/tanstack-react-query": ["@trpc/[email protected]", "", { "peerDependencies": { "@tanstack/react-query": "^5.80.3", "@trpc/client": "11.18.0", "@trpc/server": "11.18.0", "react": ">=18.2.0", "typescript": ">=5.7.2" }, "bin": { "intent": "bin/intent.js" } }, "sha512-dm5xIlN0SEzJAbQ34EHdb1Kgd/zWZ63ZMviQEw3WCWCIPz8MjLKAhquncPcn+YxFUJa+Qi4qatdGFymmM4HmAQ=="],
- "glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="],
+ "@ts-morph/common": ["@ts-morph/[email protected]", "", { "dependencies": { "fast-glob": "^3.3.3", "minimatch": "^10.0.1", "path-browserify": "^1.0.1" } }, "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="],
+
+ "@turbo/darwin-64": ["@turbo/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-po+7rfJfUnFXjWlcoN2RwhErgzCdRtBc1T26vYPcywHlggmCQiQe1uWaE4j+BibI2uY9/2pDoFzMN0rmSaPFOw=="],
- "globals": ["[email protected]", "", {}, "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ=="],
+ "@turbo/darwin-arm64": ["@turbo/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+zB2btDJ00lnPRuqOvpVvgl4x34k/djZQGZTTCfjn7JgNCl8QFY5Njo5+dqkY1g/+9gbbsnAvWm9CmJg9ebcXA=="],
- "globalthis": ["[email protected]", "", { "dependencies": { "define-properties": "^1.2.1", "gopd": "^1.0.1" } }, "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ=="],
+ "@turbo/linux-64": ["@turbo/[email protected]", "", { "os": [ "linux", "android", ], "cpu": "x64" }, "sha512-K1dxqiVisyN7cViVsfQLs6xscQbYuI8aO2nbUhFURDACgEDfZRdP/b4CCxeosBJpcMfhYyiibWqJorCnvz9kKg=="],
- "gopd": ["[email protected]", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
+ "@turbo/linux-arm64": ["@turbo/[email protected]", "", { "os": [ "linux", "android", ], "cpu": "arm64" }, "sha512-Gi77ibVnrE1fEmvr+/wBD/yvRqhwp/RQuCp2+//lv1U1wNFFyVg0V7Wj8FG9FXPFAw5QHReo8rxc9+wBSDZjzA=="],
- "has-bigints": ["[email protected]", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],
+ "@turbo/windows-64": ["@turbo/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-znnLO1haJPYTHoKMKwlAvlkjRiYbbhBzME6wIGaMd+fwir23U6jVd1ecaTWWi1fbnRVqxMfgDBKseQ/hLKb83g=="],
- "has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
+ "@turbo/windows-arm64": ["@turbo/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-VN30vh3b3Czh2WzYHNTfF1FE0YMZ5aHsLO8dBMGHJewA6792wX6iJR8ZxlzFW6WdOu0gEAKIvlYhfyT81Wkm4Q=="],
- "has-property-descriptors": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],
+ "@types/body-parser": ["@types/[email protected]", "", { "dependencies": { "@types/connect": "*", "@types/node": "*" } }, "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g=="],
- "has-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.0" } }, "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ=="],
+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
- "has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
+ "@types/connect": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="],
- "has-tostringtag": ["[email protected]", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="],
+ "@types/cookiejar": ["@types/[email protected]", "", {}, "sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q=="],
- "hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
+ "@types/d3-array": ["@types/[email protected]", "", {}, "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ=="],
- "ignore": ["[email protected]", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
+ "@types/d3-color": ["@types/[email protected]", "", {}, "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA=="],
- "import-fresh": ["[email protected]", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="],
+ "@types/d3-delaunay": ["@types/[email protected]", "", {}, "sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ=="],
- "imurmurhash": ["[email protected]", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="],
+ "@types/d3-ease": ["@types/[email protected]", "", {}, "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA=="],
- "internal-slot": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "hasown": "^2.0.2", "side-channel": "^1.1.0" } }, "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw=="],
+ "@types/d3-format": ["@types/[email protected]", "", {}, "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg=="],
- "is-array-buffer": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "get-intrinsic": "^1.2.6" } }, "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A=="],
+ "@types/d3-geo": ["@types/[email protected]", "", { "dependencies": { "@types/geojson": "*" } }, "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ=="],
- "is-async-function": ["[email protected]", "", { "dependencies": { "async-function": "^1.0.0", "call-bound": "^1.0.3", "get-proto": "^1.0.1", "has-tostringtag": "^1.0.2", "safe-regex-test": "^1.1.0" } }, "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ=="],
+ "@types/d3-interpolate": ["@types/[email protected]", "", { "dependencies": { "@types/d3-color": "*" } }, "sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw=="],
- "is-bigint": ["[email protected]", "", { "dependencies": { "has-bigints": "^1.0.2" } }, "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ=="],
+ "@types/d3-path": ["@types/[email protected]", "", {}, "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg=="],
- "is-boolean-object": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" } }, "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A=="],
+ "@types/d3-scale": ["@types/[email protected]", "", { "dependencies": { "@types/d3-time": "*" } }, "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA=="],
- "is-callable": ["[email protected]", "", {}, "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA=="],
+ "@types/d3-shape": ["@types/[email protected]", "", { "dependencies": { "@types/d3-path": "*" } }, "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg=="],
- "is-core-module": ["[email protected]", "", { "dependencies": { "hasown": "^2.0.3" } }, "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA=="],
+ "@types/d3-time": ["@types/[email protected]", "", {}, "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg=="],
- "is-data-view": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "get-intrinsic": "^1.2.6", "is-typed-array": "^1.1.13" } }, "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw=="],
+ "@types/d3-time-format": ["@types/[email protected]", "", {}, "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA=="],
- "is-date-object": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "has-tostringtag": "^1.0.2" } }, "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg=="],
+ "@types/d3-timer": ["@types/[email protected]", "", {}, "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw=="],
- "is-document.all": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.4" } }, "sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g=="],
+ "@types/eslint": ["@types/[email protected]", "", { "dependencies": { "@types/estree": "*", "@types/json-schema": "*" } }, "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag=="],
- "is-extglob": ["[email protected]", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
+ "@types/eslint-scope": ["@types/[email protected]", "", { "dependencies": { "@types/eslint": "*", "@types/estree": "*" } }, "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg=="],
- "is-finalizationregistry": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3" } }, "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg=="],
+ "@types/estree": ["@types/[email protected]", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
- "is-generator-function": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.4", "generator-function": "^2.0.0", "get-proto": "^1.0.1", "has-tostringtag": "^1.0.2", "safe-regex-test": "^1.1.0" } }, "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA=="],
+ "@types/express": ["@types/[email protected]", "", { "dependencies": { "@types/body-parser": "*", "@types/express-serve-static-core": "^5.0.0", "@types/serve-static": "^2" } }, "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA=="],
- "is-glob": ["[email protected]", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
+ "@types/express-serve-static-core": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "@types/qs": "*", "@types/range-parser": "*", "@types/send": "*" } }, "sha512-d3KvEXBSo/lOAMc2u6fkyDHBvetBHeqD7wm/AcXfLpSOQwlmG9D/aQ0SFswVjv05p7ullQS7Mjohj6/VdbZuTg=="],
- "is-map": ["[email protected]", "", {}, "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw=="],
+ "@types/geojson": ["@types/[email protected]", "", {}, "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg=="],
- "is-negative-zero": ["[email protected]", "", {}, "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw=="],
+ "@types/http-errors": ["@types/[email protected]", "", {}, "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg=="],
- "is-number": ["[email protected]", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
+ "@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
- "is-number-object": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" } }, "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw=="],
+ "@types/lodash": ["@types/[email protected]", "", {}, "sha512-gIW7lQLZbue7lRSWEFql49QJJWThrTFFeIMJdp3eH4tKoxm1OvEPg02rm4wCCSHS0cL3/Fizimb35b7k8atwsQ=="],
- "is-regex": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g=="],
+ "@types/methods": ["@types/[email protected]", "", {}, "sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ=="],
- "is-set": ["[email protected]", "", {}, "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg=="],
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q=="],
- "is-shared-array-buffer": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3" } }, "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A=="],
+ "@types/pg": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow=="],
- "is-string": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" } }, "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA=="],
+ "@types/qs": ["@types/[email protected]", "", {}, "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw=="],
- "is-symbol": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "has-symbols": "^1.1.0", "safe-regex-test": "^1.1.0" } }, "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w=="],
+ "@types/range-parser": ["@types/[email protected]", "", {}, "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ=="],
- "is-typed-array": ["[email protected]", "", { "dependencies": { "which-typed-array": "^1.1.16" } }, "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ=="],
+ "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w=="],
- "is-weakmap": ["[email protected]", "", {}, "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w=="],
+ "@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw=="],
- "is-weakref": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3" } }, "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew=="],
+ "@types/send": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ=="],
- "is-weakset": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "get-intrinsic": "^1.2.6" } }, "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ=="],
+ "@types/serve-static": ["@types/[email protected]", "", { "dependencies": { "@types/http-errors": "*", "@types/node": "*" } }, "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ=="],
- "isarray": ["[email protected]", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="],
+ "@types/superagent": ["@types/[email protected]", "", { "dependencies": { "@types/cookiejar": "^2.1.5", "@types/methods": "^1.1.4", "@types/node": "*", "form-data": "^4.0.0" } }, "sha512-KA7srSW/HENDtOw9DOqaFLgWuMqN9WgjEw62lh9dpvRaZDkhdOkazASd7X7i2eMUYLHa1U37ZttnePsH5zTDHw=="],
- "isexe": ["[email protected]", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
+ "@types/supertest": ["@types/[email protected]", "", { "dependencies": { "@types/methods": "^1.1.4", "@types/superagent": "^8.1.0" } }, "sha512-4CbBvoYVLHL7+yhbYrZET0vsvuyXTC05aRe7dNQkwMzm56auceoy6Yu3K50uZmwfHna1os3CMSgM/3QVkUtPTw=="],
- "iterator.prototype": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.4", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.6", "get-proto": "^1.0.0", "has-symbols": "^1.1.0", "set-function-name": "^2.0.2" } }, "sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g=="],
+ "@types/use-sync-external-store": ["@types/[email protected]", "", {}, "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="],
- "js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
+ "@types/validate-npm-package-name": ["@types/[email protected]", "", {}, "sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw=="],
- "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q=="],
+ "@types/validator": ["@types/[email protected]", "", {}, "sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA=="],
- "json-buffer": ["[email protected]", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
+ "@visx/curve": ["@visx/[email protected]", "", { "dependencies": { "@visx/vendor": "4.0.0-alpha.0" } }, "sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg=="],
- "json-schema-traverse": ["[email protected]", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
+ "@visx/event": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/point": "4.0.1-alpha.0" } }, "sha512-EQqCMSv/s8NbFjo+hz3FKsvvYfP+2QslsFJ/24/O5l/W+7UC6J6aAvO0ujVwrTwdYbuQ+vhxKi1xdPdKR/qj1g=="],
- "json-stable-stringify-without-jsonify": ["[email protected]", "", {}, "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw=="],
+ "@visx/grid": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/curve": "4.0.1-alpha.0", "@visx/group": "4.0.1-alpha.0", "@visx/point": "4.0.1-alpha.0", "@visx/scale": "4.0.1-alpha.0", "@visx/shape": "4.0.1-alpha.0", "classnames": "^2.3.1" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-rycutGmTHO+znNdPumheWMglm7YfpffvRwUkVy5zy4WoORIuKTMkDxwnOzHG2xMxU3EE/YCd37xFV5AxA30yeg=="],
- "jsx-ast-utils": ["[email protected]", "", { "dependencies": { "array-includes": "^3.1.6", "array.prototype.flat": "^1.3.1", "object.assign": "^4.1.4", "object.values": "^1.1.6" } }, "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ=="],
+ "@visx/group": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "classnames": "^2.3.1" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-V19l7iQ7jccBv8kao/EByuI6o4xtxzzLV9nqVI1hRvmdzTVsuLpqlwzYCZUXJaTVvUWf8s4D2SQFjGkj/Nw+0w=="],
- "keyv": ["[email protected]", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
+ "@visx/point": ["@visx/[email protected]", "", {}, "sha512-ijTfr/Nx09f03vIj9nyTr3z4Xth4Y75427UaogJh6dnIRLMEFHQOwNu791sbfiNj0a+ZXuaE32h0vKrFe4/8Qg=="],
- "levn": ["[email protected]", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],
+ "@visx/responsive": ["@visx/[email protected]", "", { "dependencies": { "@types/lodash": "^4.17.13", "@types/react": "*", "lodash": "^4.17.21" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-o+1zGywQZY0+yOx3Iw87wc4bbPJRr/HnIukTwfOz4UVyj9pB1OQNVHB7OORO1+LBHJceWpB31co/ZV9KHncKrA=="],
- "locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],
+ "@visx/scale": ["@visx/[email protected]", "", { "dependencies": { "@visx/vendor": "4.0.0-alpha.0" } }, "sha512-nzjeE87vFSAXGWFiiNfBpNLAf0Q8Qmf6syvKLjqNi4kGZkdhbUll3E/59YsgWXmjM8+llPLWzGsP+JPvo5eq1A=="],
- "lodash.merge": ["[email protected]", "", {}, "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="],
+ "@visx/shape": ["@visx/[email protected]", "", { "dependencies": { "@types/lodash": "^4.17.13", "@types/react": "*", "@visx/curve": "4.0.1-alpha.0", "@visx/group": "4.0.1-alpha.0", "@visx/scale": "4.0.1-alpha.0", "@visx/vendor": "4.0.0-alpha.0", "classnames": "^2.3.1", "lodash": "^4.17.21" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-62QeiVNmPlterQGwhkEDcbq7M0MqY0lBsK5QKXtM9ZoPZWkuGV3aykA3+Xu20B2FAvyJq4LqJzBc7Sxr+EAdbA=="],
- "loose-envify": ["[email protected]", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="],
+ "@visx/vendor": ["@visx/[email protected]", "", { "dependencies": { "@types/d3-array": "3.0.3", "@types/d3-color": "3.1.0", "@types/d3-delaunay": "6.0.1", "@types/d3-format": "3.0.1", "@types/d3-geo": "3.1.0", "@types/d3-interpolate": "3.0.1", "@types/d3-path": "3.1.1", "@types/d3-scale": "4.0.2", "@types/d3-shape": "3.1.7", "@types/d3-time": "3.0.0", "@types/d3-time-format": "2.1.0", "d3-array": "3.2.1", "d3-color": "3.1.0", "d3-delaunay": "6.0.2", "d3-format": "3.1.0", "d3-geo": "3.1.0", "d3-interpolate": "3.0.1", "d3-path": "3.1.0", "d3-scale": "4.0.2", "d3-shape": "3.2.0", "d3-time": "3.1.0", "d3-time-format": "4.1.0", "internmap": "2.0.3" } }, "sha512-6I+MuqXBcv9jnlcVowHoHKSdk9gXTWkHLKyqBwRWg7LY6A3Ei8SHfubpqGV5rBUSppxMq2RszPJUS6w+H0YgmQ=="],
- "math-intrinsics": ["[email protected]", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
+ "@webassemblyjs/ast": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/helper-numbers": "1.13.2", "@webassemblyjs/helper-wasm-bytecode": "1.13.2" } }, "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ=="],
- "merge2": ["[email protected]", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],
+ "@webassemblyjs/floating-point-hex-parser": ["@webassemblyjs/[email protected]", "", {}, "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA=="],
- "micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
+ "@webassemblyjs/helper-api-error": ["@webassemblyjs/[email protected]", "", {}, "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ=="],
- "minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
+ "@webassemblyjs/helper-buffer": ["@webassemblyjs/[email protected]", "", {}, "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA=="],
- "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
+ "@webassemblyjs/helper-numbers": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/floating-point-hex-parser": "1.13.2", "@webassemblyjs/helper-api-error": "1.13.2", "@xtuc/long": "4.2.2" } }, "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA=="],
- "nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="],
+ "@webassemblyjs/helper-wasm-bytecode": ["@webassemblyjs/[email protected]", "", {}, "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA=="],
- "natural-compare": ["[email protected]", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],
+ "@webassemblyjs/helper-wasm-section": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", "@webassemblyjs/helper-wasm-bytecode": "1.13.2", "@webassemblyjs/wasm-gen": "1.14.1" } }, "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw=="],
- "next": ["[email protected]", "", { "dependencies": { "@next/env": "16.2.0", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.2.0", "@next/swc-darwin-x64": "16.2.0", "@next/swc-linux-arm64-gnu": "16.2.0", "@next/swc-linux-arm64-musl": "16.2.0", "@next/swc-linux-x64-gnu": "16.2.0", "@next/swc-linux-x64-musl": "16.2.0", "@next/swc-win32-arm64-msvc": "16.2.0", "@next/swc-win32-x64-msvc": "16.2.0", "sharp": "^0.34.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-NLBVrJy1pbV1Yn00L5sU4vFyAHt5XuSjzrNyFnxo6Com0M0KrL6hHM5B99dbqXb2bE9pm4Ow3Zl1xp6HVY9edQ=="],
+ "@webassemblyjs/ieee754": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@xtuc/ieee754": "^1.2.0" } }, "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw=="],
- "node-exports-info": ["[email protected]", "", { "dependencies": { "array.prototype.flatmap": "^1.3.3", "es-errors": "^1.3.0", "object.entries": "^1.1.9", "semver": "^6.3.1" } }, "sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag=="],
+ "@webassemblyjs/leb128": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@xtuc/long": "4.2.2" } }, "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw=="],
- "object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
+ "@webassemblyjs/utf8": ["@webassemblyjs/[email protected]", "", {}, "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ=="],
- "object-inspect": ["[email protected]", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
+ "@webassemblyjs/wasm-edit": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", "@webassemblyjs/helper-wasm-bytecode": "1.13.2", "@webassemblyjs/helper-wasm-section": "1.14.1", "@webassemblyjs/wasm-gen": "1.14.1", "@webassemblyjs/wasm-opt": "1.14.1", "@webassemblyjs/wasm-parser": "1.14.1", "@webassemblyjs/wast-printer": "1.14.1" } }, "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ=="],
- "object-keys": ["[email protected]", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="],
+ "@webassemblyjs/wasm-gen": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-wasm-bytecode": "1.13.2", "@webassemblyjs/ieee754": "1.13.2", "@webassemblyjs/leb128": "1.13.2", "@webassemblyjs/utf8": "1.13.2" } }, "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg=="],
- "object.assign": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0", "has-symbols": "^1.1.0", "object-keys": "^1.1.1" } }, "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw=="],
+ "@webassemblyjs/wasm-opt": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", "@webassemblyjs/wasm-gen": "1.14.1", "@webassemblyjs/wasm-parser": "1.14.1" } }, "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw=="],
- "object.entries": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.4", "define-properties": "^1.2.1", "es-object-atoms": "^1.1.1" } }, "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw=="],
+ "@webassemblyjs/wasm-parser": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-api-error": "1.13.2", "@webassemblyjs/helper-wasm-bytecode": "1.13.2", "@webassemblyjs/ieee754": "1.13.2", "@webassemblyjs/leb128": "1.13.2", "@webassemblyjs/utf8": "1.13.2" } }, "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ=="],
- "object.fromentries": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", "es-abstract": "^1.23.2", "es-object-atoms": "^1.0.0" } }, "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ=="],
+ "@webassemblyjs/wast-printer": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/ast": "1.14.1", "@xtuc/long": "4.2.2" } }, "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw=="],
- "object.values": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0" } }, "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA=="],
+ "@xtuc/ieee754": ["@xtuc/[email protected]", "", {}, "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA=="],
- "optionator": ["[email protected]", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],
+ "@xtuc/long": ["@xtuc/[email protected]", "", {}, "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ=="],
- "own-keys": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.4", "get-intrinsic": "^1.3.0", "object-keys": "^1.1.1", "safe-push-apply": "^1.0.0" } }, "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg=="],
+ "accepts": ["[email protected]", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
- "p-limit": ["[email protected]", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="],
+ "acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="],
- "p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="],
+ "acorn-import-phases": ["[email protected]", "", { "peerDependencies": { "acorn": "^8.14.0" } }, "sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ=="],
- "parent-module": ["[email protected]", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="],
+ "ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
- "path-exists": ["[email protected]", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
+ "ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
- "path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
+ "ajv-keywords": ["[email protected]", "", { "peerDependencies": { "ajv": "^6.9.1" } }, "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ=="],
- "path-parse": ["[email protected]", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="],
+ "ansi-colors": ["[email protected]", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="],
- "picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
+ "ansi-regex": ["[email protected]", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
- "picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
+ "ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
- "possible-typed-array-names": ["[email protected]", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="],
+ "ansis": ["[email protected]", "", {}, "sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig=="],
- "postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="],
+ "api": ["api@workspace:apps/api"],
- "prelude-ls": ["[email protected]", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
+ "app": ["app@workspace:apps/app"],
- "prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g=="],
+ "append-field": ["[email protected]", "", {}, "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="],
- "prop-types": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="],
+ "argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
- "punycode": ["[email protected]", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
+ "aria-hidden": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
- "queue-microtask": ["[email protected]", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
+ "array-timsort": ["[email protected]", "", {}, "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ=="],
- "react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],
+ "asap": ["[email protected]", "", {}, "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA=="],
- "react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.8" } }, "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ=="],
+ "ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="],
- "react-is": ["[email protected]", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
+ "asynckit": ["[email protected]", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="],
- "reflect.getprototypeof": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="],
+ "atomically": ["[email protected]", "", {}, "sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w=="],
- "regexp.prototype.flags": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-errors": "^1.3.0", "get-proto": "^1.0.1", "gopd": "^1.2.0", "set-function-name": "^2.0.2" } }, "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA=="],
+ "aws-ssl-profiles": ["[email protected]", "", {}, "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g=="],
- "resolve": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "is-core-module": "^2.16.2", "node-exports-info": "^1.6.0", "object-keys": "^1.1.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-tqt+NBWwyaMgw3zDsnygx4CByWjQEJHOPMdslYhppaQSJUtL/D4JO9CcBBlhPoI8lz9oJIDXkwXfhF4aWqP8xQ=="],
+ "balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
- "resolve-from": ["[email protected]", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
+ "base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
- "reusify": ["[email protected]", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="],
+ "baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-zAgkquC2WYF0PIc6XbNYkA2uuxxFavzgmX61R+dHDUa558V8Ejf8ozTZFR6QzM24RWu4kBcRkhJ5kpz77j9fnQ=="],
- "run-parallel": ["[email protected]", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="],
+ "better-auth": ["[email protected]", "", { "dependencies": { "@better-auth/core": "1.6.25", "@better-auth/drizzle-adapter": "1.6.25", "@better-auth/kysely-adapter": "1.6.25", "@better-auth/memory-adapter": "1.6.25", "@better-auth/mongo-adapter": "1.6.25", "@better-auth/prisma-adapter": "1.6.25", "@better-auth/telemetry": "1.6.25", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@noble/ciphers": "^2.1.1", "@noble/hashes": "^2.0.1", "better-call": "1.3.7", "defu": "^6.1.4", "jose": "^6.1.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.1.1", "zod": "^4.3.6" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": "^0.45.2", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-fvoq+oCO+FF5fpP3XfU7znRyGFpHB77UG2EyxsKNy+Cak7Q5pELu+auvvDveQbWQxcoKugZ7jYQQPFQLpUTGOw=="],
- "safe-array-concat": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "get-intrinsic": "^1.3.0", "has-symbols": "^1.1.0", "isarray": "^2.0.5" } }, "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg=="],
+ "better-call": ["[email protected]", "", { "dependencies": { "@better-auth/utils": "^0.4.0", "@better-fetch/fetch": "^1.1.21", "rou3": "^0.7.12", "set-cookie-parser": "^3.0.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-Al51/hjp2SSp6CRTa3F2ptcx4yQVS1xWKoY6jcVXqNYOap6mHFP2jUBn5EwIL4iIed1/Sq4hlQ+Umm6EflZG+w=="],
- "safe-push-apply": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "isarray": "^2.0.5" } }, "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA=="],
+ "better-result": ["[email protected]", "", {}, "sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw=="],
- "safe-regex-test": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "is-regex": "^1.2.1" } }, "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw=="],
+ "better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA=="],
- "scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
+ "bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
- "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+ "bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
- "set-function-length": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="],
+ "body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="],
- "set-function-name": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "functions-have-names": "^1.2.3", "has-property-descriptors": "^1.0.2" } }, "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ=="],
+ "brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
- "set-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0" } }, "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw=="],
+ "braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
- "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.0.0", "detect-libc": "^2.1.2", "semver": "^7.7.3" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.34.5", "@img/sharp-darwin-x64": "0.34.5", "@img/sharp-libvips-darwin-arm64": "1.2.4", "@img/sharp-libvips-darwin-x64": "1.2.4", "@img/sharp-libvips-linux-arm": "1.2.4", "@img/sharp-libvips-linux-arm64": "1.2.4", "@img/sharp-libvips-linux-ppc64": "1.2.4", "@img/sharp-libvips-linux-riscv64": "1.2.4", "@img/sharp-libvips-linux-s390x": "1.2.4", "@img/sharp-libvips-linux-x64": "1.2.4", "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", "@img/sharp-libvips-linuxmusl-x64": "1.2.4", "@img/sharp-linux-arm": "0.34.5", "@img/sharp-linux-arm64": "0.34.5", "@img/sharp-linux-ppc64": "0.34.5", "@img/sharp-linux-riscv64": "0.34.5", "@img/sharp-linux-s390x": "0.34.5", "@img/sharp-linux-x64": "0.34.5", "@img/sharp-linuxmusl-arm64": "0.34.5", "@img/sharp-linuxmusl-x64": "0.34.5", "@img/sharp-wasm32": "0.34.5", "@img/sharp-win32-arm64": "0.34.5", "@img/sharp-win32-ia32": "0.34.5", "@img/sharp-win32-x64": "0.34.5" } }, "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg=="],
+ "browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.10.44", "caniuse-lite": "^1.0.30001806", "electron-to-chromium": "^1.5.393", "node-releases": "^2.0.51", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw=="],
- "shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
+ "buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
- "shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
+ "buffer-from": ["[email protected]", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
- "side-channel": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="],
+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
- "side-channel-list": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
+ "bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
- "side-channel-map": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
+ "busboy": ["[email protected]", "", { "dependencies": { "streamsearch": "^1.1.0" } }, "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA=="],
- "side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
+ "bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
- "source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
+ "c12": ["[email protected]", "", { "dependencies": { "chokidar": "^5.0.0", "confbox": "^0.2.4", "defu": "^6.1.6", "dotenv": "^17.3.1", "exsolve": "^1.0.8", "giget": "^3.2.0", "jiti": "^2.6.1", "ohash": "^2.0.11", "pathe": "^2.0.3", "perfect-debounce": "^2.1.0", "pkg-types": "^2.3.0", "rc9": "^3.0.1" }, "peerDependencies": { "magicast": "*" }, "optionalPeers": ["magicast"] }, "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA=="],
+
+ "cache-manager": ["[email protected]", "", { "dependencies": { "@cacheable/utils": "^2.5.0", "keyv": "^5.6.0" } }, "sha512-d4vceEyYe95gPxEyQchlEOH9vJlkNRW8G6gzFzzMTxJK9PahYMhC9chrEqgZN0HulROjgw3IzmWVNk7Q7ytiGw=="],
- "stop-iteration-iterator": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "internal-slot": "^1.1.0" } }, "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ=="],
+ "call-bind-apply-helpers": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
- "string.prototype.matchall": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-abstract": "^1.23.6", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.6", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "internal-slot": "^1.1.0", "regexp.prototype.flags": "^1.5.3", "set-function-name": "^2.0.2", "side-channel": "^1.1.0" } }, "sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA=="],
+ "call-bound": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
- "string.prototype.repeat": ["[email protected]", "", { "dependencies": { "define-properties": "^1.1.3", "es-abstract": "^1.17.5" } }, "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w=="],
+ "callsites": ["[email protected]", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="],
- "string.prototype.trim": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "define-data-property": "^1.1.4", "define-properties": "^1.2.1", "es-abstract": "^1.24.2", "es-object-atoms": "^1.1.2", "has-property-descriptors": "^1.0.2", "safe-regex-test": "^1.1.0" } }, "sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w=="],
+ "caniuse-lite": ["[email protected]", "", {}, "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw=="],
- "string.prototype.trimend": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "define-properties": "^1.2.1", "es-object-atoms": "^1.1.2" } }, "sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw=="],
+ "chalk": ["[email protected]", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="],
- "string.prototype.trimstart": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0" } }, "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg=="],
+ "chardet": ["[email protected]", "", {}, "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA=="],
- "strip-json-comments": ["[email protected]", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],
+ "chevrotain": ["[email protected]", "", { "dependencies": { "@chevrotain/cst-dts-gen": "10.5.0", "@chevrotain/gast": "10.5.0", "@chevrotain/types": "10.5.0", "@chevrotain/utils": "10.5.0", "lodash": "4.17.21", "regexp-to-ast": "0.5.0" } }, "sha512-Pkv5rBY3+CsHOYfV5g/Vs5JY9WTHHDEKOlohI2XeygaZhUeqhAlldZ8Hz9cRmxu709bvS08YzxHdTPHhffc13A=="],
- "styled-jsx": ["[email protected]", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="],
+ "chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="],
- "supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+ "chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
- "supports-preserve-symlinks-flag": ["[email protected]", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],
+ "chrome-trace-event": ["[email protected]", "", {}, "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ=="],
- "tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
+ "class-transformer": ["[email protected]", "", {}, "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw=="],
- "to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
+ "class-validator": ["[email protected]", "", { "dependencies": { "@types/validator": "^13.15.3", "libphonenumber-js": "^1.11.1", "validator": "^13.15.22" } }, "sha512-LqoS80HBBSCVhz/3KloUly0ovokxpdOLR++Al3J3+dHXWt9sTKlKd4eYtoxhxyUjoe5+UcIM+5k9MIxyBWnRTw=="],
- "ts-api-utils": ["[email protected]", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="],
+ "class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
- "tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+ "classnames": ["[email protected]", "", {}, "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow=="],
- "turbo": ["[email protected]", "", { "optionalDependencies": { "@turbo/darwin-64": "2.10.8", "@turbo/darwin-arm64": "2.10.8", "@turbo/linux-64": "2.10.8", "@turbo/linux-arm64": "2.10.8", "@turbo/windows-64": "2.10.8", "@turbo/windows-arm64": "2.10.8" }, "bin": { "turbo": "bin/turbo" } }, "sha512-9+8YX5QOkGXzZxcIykTHgaooRHGMWO+jfdyRK0o+rN0U7hBIig2MrJ8r/aNzIPDPhdA73SGb0O+tIztaModTMg=="],
+ "cli-cursor": ["[email protected]", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="],
- "type-check": ["[email protected]", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="],
+ "cli-spinners": ["[email protected]", "", {}, "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg=="],
- "typed-array-buffer": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-typed-array": "^1.1.14" } }, "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw=="],
+ "cli-table3": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0" }, "optionalDependencies": { "@colors/colors": "1.5.0" } }, "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ=="],
- "typed-array-byte-length": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "for-each": "^0.3.3", "gopd": "^1.2.0", "has-proto": "^1.2.0", "is-typed-array": "^1.1.14" } }, "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg=="],
+ "cli-width": ["[email protected]", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
- "typed-array-byte-offset": ["[email protected]", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "for-each": "^0.3.3", "gopd": "^1.2.0", "has-proto": "^1.2.0", "is-typed-array": "^1.1.15", "reflect.getprototypeof": "^1.0.9" } }, "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ=="],
+ "client-only": ["[email protected]", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="],
- "typed-array-length": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.9", "for-each": "^0.3.5", "gopd": "^1.2.0", "is-typed-array": "^1.1.15", "possible-typed-array-names": "^1.1.0", "reflect.getprototypeof": "^1.0.10" } }, "sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g=="],
+ "cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
- "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A=="],
+ "clone": ["[email protected]", "", {}, "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg=="],
- "typescript-eslint": ["[email protected]", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.65.0", "@typescript-eslint/parser": "8.65.0", "@typescript-eslint/typescript-estree": "8.65.0", "@typescript-eslint/utils": "8.65.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-/ggrHAwyjENDusvyxbuqxAC2dTnZg/Z8F+fgQtYIz+L6n/9HfSlEZcFGV/NsMNa6CkGk0xUjUAFwC0vHOflvIA=="],
+ "clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
- "unbox-primitive": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "has-bigints": "^1.0.2", "has-symbols": "^1.1.0", "which-boxed-primitive": "^1.1.1" } }, "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw=="],
+ "cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],
- "undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
+ "cmdk": ["[email protected]", "", { "dependencies": { "@radix-ui/react-compose-refs": "^1.1.1", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-id": "^1.1.0", "@radix-ui/react-primitive": "^2.0.2" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg=="],
- "uri-js": ["[email protected]", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
+ "code-block-writer": ["[email protected]", "", {}, "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg=="],
+
+ "color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
+
+ "color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
+
+ "combined-stream": ["[email protected]", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="],
+
+ "commander": ["[email protected]", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
+
+ "comment-json": ["[email protected]", "", { "dependencies": { "array-timsort": "^1.0.3", "esprima": "^4.0.1" } }, "sha512-uiqLcOiVDJtBP8WGkZHEP+FZIhTzP1dxvn59EfoYUi9gqupjrBWVQkO2atDrbnKPwLeotFYDsuNb26uBMqB+hw=="],
+
+ "component-emitter": ["[email protected]", "", {}, "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ=="],
+
+ "concat-map": ["[email protected]", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
+
+ "concat-stream": ["[email protected]", "", { "dependencies": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.0.2", "typedarray": "^0.0.6" } }, "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A=="],
+
+ "concurrently": ["[email protected]", "", { "dependencies": { "chalk": "4.1.2", "rxjs": "7.8.2", "shell-quote": "1.9.0", "supports-color": "8.1.1", "tree-kill": "1.2.2", "yargs": "17.7.2" }, "bin": { "conc": "dist/bin/concurrently.js", "concurrently": "dist/bin/concurrently.js" } }, "sha512-TZ0CEhyzvFjgtAvHTusDMgj7wNdihCh7LLLrzdUOXIhdlnL2JBBGA9eJxR24rtqgmdjh3OA3hrN1rCHj6HM8qA=="],
+
+ "conf": ["[email protected]", "", { "dependencies": { "ajv": "^8.6.3", "ajv-formats": "^2.1.1", "atomically": "^1.7.0", "debounce-fn": "^4.0.0", "dot-prop": "^6.0.1", "env-paths": "^2.2.1", "json-schema-typed": "^7.0.3", "onetime": "^5.1.2", "pkg-up": "^3.1.0", "semver": "^7.3.5" } }, "sha512-8fLl9F04EJqjSqH+QjITQfJF8BrOVaYr1jewVgSRAEWePfxT0sku4w2hrGQ60BC/TNLGQ2pgxNlTbWQmMPFvXg=="],
+
+ "confbox": ["[email protected]", "", {}, "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ=="],
+
+ "content-disposition": ["[email protected]", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
+
+ "content-type": ["[email protected]", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
+
+ "context.dev": ["[email protected]", "", {}, "sha512-FuonQNWVxHNixuTPQmcWc1D9qPnqfD/MurXiOo12jEGK8zeZ4TvYRCZP67XRkUZwjah0niklnrBJj+QCDwohSw=="],
+
+ "convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
+
+ "cookie": ["[email protected]", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
+
+ "cookie-signature": ["[email protected]", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
+
+ "cookiejar": ["[email protected]", "", {}, "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw=="],
+
+ "cors": ["[email protected]", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
+
+ "cosmiconfig": ["[email protected]", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" }, "optionalPeers": ["typescript"] }, "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg=="],
+
+ "cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
+
+ "cssesc": ["[email protected]", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
+
+ "csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+
+ "d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
+
+ "d3-color": ["[email protected]", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
+
+ "d3-delaunay": ["[email protected]", "", { "dependencies": { "delaunator": "5" } }, "sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ=="],
+
+ "d3-ease": ["[email protected]", "", {}, "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w=="],
+
+ "d3-format": ["[email protected]", "", {}, "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA=="],
+
+ "d3-geo": ["[email protected]", "", { "dependencies": { "d3-array": "2.5.0 - 3" } }, "sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA=="],
+
+ "d3-interpolate": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="],
+
+ "d3-path": ["[email protected]", "", {}, "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ=="],
+
+ "d3-scale": ["[email protected]", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ=="],
+
+ "d3-shape": ["[email protected]", "", { "dependencies": { "d3-path": "^3.1.0" } }, "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA=="],
+
+ "d3-time": ["[email protected]", "", { "dependencies": { "d3-array": "2 - 3" } }, "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q=="],
+
+ "d3-time-format": ["[email protected]", "", { "dependencies": { "d3-time": "1 - 3" } }, "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg=="],
+
+ "d3-timer": ["[email protected]", "", {}, "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA=="],
+
+ "date-fns": ["[email protected]", "", {}, "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w=="],
+
+ "debounce-fn": ["[email protected]", "", { "dependencies": { "mimic-fn": "^3.0.0" } }, "sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ=="],
+
+ "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
+
+ "decimal.js-light": ["[email protected]", "", {}, "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg=="],
+
+ "decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
+
+ "dedent": ["[email protected]", "", { "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, "optionalPeers": ["babel-plugin-macros"] }, "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA=="],
+
+ "deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
+
+ "deepmerge": ["[email protected]", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="],
+
+ "deepmerge-ts": ["[email protected]", "", {}, "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw=="],
+
+ "default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
+
+ "default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
+
+ "defaults": ["[email protected]", "", { "dependencies": { "clone": "^1.0.2" } }, "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A=="],
+
+ "define-lazy-prop": ["[email protected]", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="],
+
+ "defu": ["[email protected]", "", {}, "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="],
+
+ "delaunator": ["[email protected]", "", { "dependencies": { "robust-predicates": "^3.0.2" } }, "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ=="],
+
+ "delayed-stream": ["[email protected]", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="],
+
+ "denque": ["[email protected]", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="],
+
+ "depd": ["[email protected]", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
+
+ "destr": ["[email protected]", "", {}, "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA=="],
+
+ "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
+
+ "detect-node-es": ["[email protected]", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="],
+
+ "dezalgo": ["[email protected]", "", { "dependencies": { "asap": "^2.0.0", "wrappy": "1" } }, "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig=="],
+
+ "diff": ["[email protected]", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="],
+
+ "dot-prop": ["[email protected]", "", { "dependencies": { "is-obj": "^2.0.0" } }, "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA=="],
+
+ "dotenv": ["[email protected]", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="],
+
+ "dotenv-expand": ["[email protected]", "", { "dependencies": { "dotenv": "^16.4.5" } }, "sha512-uc47g4b+4k/M/SeaW1y4OApx+mtLWl92l5LMPP0GNXctZqELk+YGgOPIIC5elYmUH4OuoK3JLhuRUYegeySiFA=="],
+
+ "drizzle-orm": ["[email protected]", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "sql.js", "sqlite3"] }, "sha512-7A4ZxhHk9gdlXmTdPj/lREtP+3u8KvZ4yEN6MYVxBzZGex5Wtdc+CWSbu7btgF6TB0N+MNPrvW7RKBbxJchs/Q=="],
+
+ "dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
+
+ "ee-first": ["[email protected]", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
+
+ "effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw=="],
+
+ "electron-to-chromium": ["[email protected]", "", {}, "sha512-lEcqhErbHjXRvd41rnWLpzbyU/IXfIYo7QwaFWmxGeLiLyY2TBCdHnWY88vB+p3ubnihRypDm66panXl7TylLA=="],
+
+ "elkjs": ["[email protected]", "", {}, "sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg=="],
+
+ "embla-carousel": ["[email protected]", "", {}, "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA=="],
+
+ "embla-carousel-react": ["[email protected]", "", { "dependencies": { "embla-carousel": "8.6.0", "embla-carousel-reactive-utils": "8.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.1 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-0/PjqU7geVmo6F734pmPqpyHqiM99olvyecY7zdweCw+6tKEXnrE90pBiBbMMU8s5tICemzpQ3hi5EpxzGW+JA=="],
+
+ "embla-carousel-reactive-utils": ["[email protected]", "", { "peerDependencies": { "embla-carousel": "8.6.0" } }, "sha512-fMVUDUEx0/uIEDM0Mz3dHznDhfX+znCCDCeIophYb1QGVM7YThSWX+wz11zlYwWFOr74b4QLGg0hrGPJeG2s4A=="],
+
+ "emoji-regex": ["[email protected]", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
+
+ "empathic": ["[email protected]", "", {}, "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA=="],
+
+ "encodeurl": ["[email protected]", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
+
+ "end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
+
+ "enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="],
+
+ "enquirer": ["[email protected]", "", { "dependencies": { "ansi-colors": "^4.1.1", "strip-ansi": "^6.0.1" } }, "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ=="],
+
+ "env-paths": ["[email protected]", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
+
+ "error-ex": ["[email protected]", "", { "dependencies": { "is-arrayish": "^0.2.1" } }, "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ=="],
+
+ "es-define-property": ["[email protected]", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
+
+ "es-errors": ["[email protected]", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
+
+ "es-module-lexer": ["[email protected]", "", {}, "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA=="],
+
+ "es-object-atoms": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="],
+
+ "es-set-tostringtag": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="],
+
+ "es-toolkit": ["[email protected]", "", {}, "sha512-OyZKhUVvEep9ITEiwHn8GKnMRQIVqoSIX7WnRbkWgJkllCujilqP2rD0u979tkl8wqyc8ICwlc1UBVv/Sl1G6w=="],
+
+ "escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
+
+ "escape-html": ["[email protected]", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
+
+ "eslint-scope": ["[email protected]", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw=="],
+
+ "esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],
+
+ "esrecurse": ["[email protected]", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],
+
+ "estraverse": ["[email protected]", "", {}, "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw=="],
+
+ "etag": ["[email protected]", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
+
+ "eventemitter3": ["[email protected]", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="],
+
+ "events": ["[email protected]", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="],
+
+ "eventsource": ["[email protected]", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
+
+ "eventsource-parser": ["[email protected]", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
+
+ "execa": ["[email protected]", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "cross-spawn": "^7.0.6", "figures": "^6.1.0", "get-stream": "^9.0.0", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.2.0", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "yoctocolors": "^2.1.1" } }, "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA=="],
+
+ "expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
+
+ "express": ["[email protected]", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
+
+ "express-rate-limit": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-0D493aP61w0TJ2A0wy27riRsO7FMQ7FK+KUHOKCSfPvYo0R55aiC6emCVgFUeShH0fq0ICPVzNcgoS+BsbXQCA=="],
+
+ "exsolve": ["[email protected]", "", {}, "sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g=="],
+
+ "fast-check": ["[email protected]", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
+
+ "fast-decode-uri-component": ["[email protected]", "", {}, "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg=="],
+
+ "fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
+
+ "fast-glob": ["[email protected]", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="],
+
+ "fast-json-stable-stringify": ["[email protected]", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="],
+
+ "fast-querystring": ["[email protected]", "", { "dependencies": { "fast-decode-uri-component": "^1.0.1" } }, "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg=="],
+
+ "fast-safe-stringify": ["[email protected]", "", {}, "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA=="],
+
+ "fast-uri": ["[email protected]", "", {}, "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw=="],
+
+ "fastq": ["[email protected]", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="],
+
+ "fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
+
+ "figures": ["[email protected]", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="],
+
+ "file-type": ["[email protected]", "", { "dependencies": { "@tokenizer/inflate": "^0.4.1", "strtok3": "^10.3.4", "token-types": "^6.1.1", "uint8array-extras": "^1.4.0" } }, "sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g=="],
+
+ "file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
+
+ "fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
+
+ "finalhandler": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
+
+ "find-my-way": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ=="],
+
+ "find-up": ["[email protected]", "", { "dependencies": { "locate-path": "^3.0.0" } }, "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg=="],
+
+ "foreground-child": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="],
+
+ "fork-ts-checker-webpack-plugin": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.16.7", "chalk": "^4.1.2", "chokidar": "^4.0.1", "cosmiconfig": "^8.2.0", "deepmerge": "^4.2.2", "fs-extra": "^10.0.0", "memfs": "^3.4.1", "minimatch": "^3.0.4", "node-abort-controller": "^3.0.1", "schema-utils": "^3.1.1", "semver": "^7.3.5", "tapable": "^2.2.1" }, "peerDependencies": { "typescript": ">3.6.0", "webpack": "^5.11.0" } }, "sha512-mpafl89VFPJmhnJ1ssH+8wmM2b50n+Rew5x42NeI2U78aRWgtkEtGmctp7iT16UjquJTjorEmIfESj3DxdW84Q=="],
+
+ "form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.4", "mime-types": "^2.1.35" } }, "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ=="],
+
+ "formidable": ["[email protected]", "", { "dependencies": { "@paralleldrive/cuid2": "^2.2.2", "dezalgo": "^1.0.4", "once": "^1.4.0" } }, "sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug=="],
+
+ "forwarded": ["[email protected]", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
+
+ "fresh": ["[email protected]", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
+
+ "fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
+
+ "fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA=="],
+
+ "fs-monkey": ["[email protected]", "", {}, "sha512-QMUezzXWII9EV5aTFXW1UBVUO77wYPpjqIF8/AviUCThNeSYZykpoTixUeaNNBwmCev0AMDWMAni+f8Hxb1IFw=="],
+
+ "function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
+
+ "fuzzysort": ["[email protected]", "", {}, "sha512-sR9BNCjBg6LNgwvxlBd0sBABvQitkLzoVY9MYYROQVX/FvfJ4Mai9LsGhDgd8qYdds0bY77VzYd5iuB+v5rwQQ=="],
+
+ "generate-function": ["[email protected]", "", { "dependencies": { "is-property": "^1.0.2" } }, "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ=="],
+
+ "gensync": ["[email protected]", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
+
+ "get-caller-file": ["[email protected]", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
+
+ "get-east-asian-width": ["[email protected]", "", {}, "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="],
+
+ "get-intrinsic": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
+
+ "get-nonce": ["[email protected]", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="],
+
+ "get-own-enumerable-keys": ["[email protected]", "", {}, "sha512-PKsK2FSrQCyxcGHsGrLDcK0lx+0Ke+6e8KFFozA9/fIQLhQzPaRvJFdcz7+Axg3jUH/Mq+NI4xa5u/UT2tQskA=="],
+
+ "get-port-please": ["[email protected]", "", {}, "sha512-I9QVvBw5U/hw3RmWpYKRumUeaDgxTPd401x364rLmWBJcOQ753eov1eTgzDqRG9bqFIfDc7gfzcQEWrUri3o1A=="],
+
+ "get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
+
+ "get-stream": ["[email protected]", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="],
+
+ "giget": ["[email protected]", "", { "bin": { "giget": "dist/cli.mjs" } }, "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg=="],
+
+ "github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
+
+ "glob": ["[email protected]", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw=="],
+
+ "glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
+
+ "glob-to-regexp": ["[email protected]", "", {}, "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw=="],
+
+ "gopd": ["[email protected]", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
+
+ "graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
+
+ "grammex": ["[email protected]", "", {}, "sha512-LnPnhOBLEJEVKS8WFDVaA397L9Kq55Q9oSITJiVLHVdhAclfUkWzQv74KhvZHKL2Q09Pb1XdsrOsZ4LfTFFTEg=="],
+
+ "graphmatch": ["[email protected]", "", {}, "sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg=="],
+
+ "has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
+
+ "has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
+
+ "has-tostringtag": ["[email protected]", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="],
+
+ "hashery": ["[email protected]", "", { "dependencies": { "hookified": "^1.15.0" } }, "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ=="],
+
+ "hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
+
+ "helmet": ["[email protected]", "", {}, "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w=="],
+
+ "hono": ["[email protected]", "", {}, "sha512-+SwvkaiJtxsiPjhy9LivY/1m7UsNqCJetM1BrZl9A5DkQhlbHQDU730mMiDPWjnoCYOM8Chf3WrCJw27kNTPFQ=="],
+
+ "hookified": ["[email protected]", "", {}, "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg=="],
+
+ "http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
+
+ "human-signals": ["[email protected]", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="],
+
+ "iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="],
+
+ "ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
+
+ "ignore": ["[email protected]", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
+
+ "immer": ["[email protected]", "", {}, "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw=="],
+
+ "import-fresh": ["[email protected]", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="],
+
+ "inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
+
+ "ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
+
+ "input-otp": ["[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-l3jWwYNvrEa6NTCt7BECfCm48GvwuZzkoeG3gBL2w4CHeOXW3eKFmf9UNYkNfYc3mxMrthMnxjIE07MT0zLBQA=="],
+
+ "internmap": ["[email protected]", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
+
+ "ip-address": ["[email protected]", "", {}, "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ=="],
+
+ "ipaddr.js": ["[email protected]", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
+
+ "is-arrayish": ["[email protected]", "", {}, "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg=="],
+
+ "is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="],
+
+ "is-extglob": ["[email protected]", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
+
+ "is-fullwidth-code-point": ["[email protected]", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
+
+ "is-glob": ["[email protected]", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
+
+ "is-in-ssh": ["[email protected]", "", {}, "sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw=="],
+
+ "is-inside-container": ["[email protected]", "", { "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" } }, "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA=="],
+
+ "is-interactive": ["[email protected]", "", {}, "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ=="],
+
+ "is-number": ["[email protected]", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
+
+ "is-obj": ["[email protected]", "", {}, "sha512-IlsXEHOjtKhpN8r/tRFj2nDyTmHvcfNeu/nrRIcXE17ROeatXchkojffa1SpdqW4cr/Fj6QkEf/Gn4zf6KKvEQ=="],
+
+ "is-plain-obj": ["[email protected]", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
+
+ "is-promise": ["[email protected]", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
+
+ "is-property": ["[email protected]", "", {}, "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g=="],
+
+ "is-regexp": ["[email protected]", "", {}, "sha512-rbku49cWloU5bSMI+zaRaXdQHXnthP6DZ/vLnfdSKyL4zUzuWnomtOEiZZOd+ioQ+avFo/qau3KPTc7Fjy1uPA=="],
+
+ "is-stream": ["[email protected]", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="],
+
+ "is-unicode-supported": ["[email protected]", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="],
+
+ "is-wsl": ["[email protected]", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw=="],
+
+ "isexe": ["[email protected]", "", {}, "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w=="],
+
+ "iterare": ["[email protected]", "", {}, "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q=="],
+
+ "jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg=="],
+
+ "jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
+
+ "jose": ["[email protected]", "", {}, "sha512-2E5L2yRp03FnwreJLJX8/r7mHiZICCf8kG7fAsTWkSQTDAcc46NIZoQLKy+EJ8sPoJlxyS4OQR5H70LjIZZlIQ=="],
+
+ "js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
+
+ "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q=="],
+
+ "jsesc": ["[email protected]", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
+
+ "json-parse-even-better-errors": ["[email protected]", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="],
+
+ "json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
+
+ "json-schema-typed": ["[email protected]", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
+
+ "json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
+
+ "jsonc-parser": ["[email protected]", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="],
+
+ "jsonfile": ["[email protected]", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="],
+
+ "keyv": ["[email protected]", "", { "dependencies": { "@keyv/serialize": "^1.1.1" } }, "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw=="],
+
+ "kleur": ["[email protected]", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],
+
+ "kysely": ["[email protected]", "", {}, "sha512-y5mVgQNkMbs1eK9Xyc0pmNdabN2wHhRYY/5r4W5HrUT1rYCEPeVNSj1RUJeSDKT3U0p+mXCvLgkrFuIafYI6BA=="],
+
+ "libphonenumber-js": ["[email protected]", "", {}, "sha512-xJxrdqvbl2rtn2MaUJrUejz8J7/uZNC0V77oks2LxYrO/+ZtVpRmz+fEQMuu6VusnEB1fmpByiLS1WXecOnAnw=="],
+
+ "lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
+
+ "lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
+
+ "lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="],
+
+ "lightningcss-darwin-x64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="],
+
+ "lightningcss-freebsd-x64": ["[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="],
+
+ "lightningcss-linux-arm-gnueabihf": ["[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="],
+
+ "lightningcss-linux-arm64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="],
+
+ "lightningcss-linux-arm64-musl": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="],
+
+ "lightningcss-linux-x64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="],
+
+ "lightningcss-linux-x64-musl": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="],
+
+ "lightningcss-win32-arm64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="],
+
+ "lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
+
+ "lilconfig": ["[email protected]", "", {}, "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ=="],
+
+ "lines-and-columns": ["[email protected]", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="],
+
+ "load-esm": ["[email protected]", "", {}, "sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA=="],
+
+ "loader-runner": ["[email protected]", "", {}, "sha512-DFEqQ3ihfS9blba08cLfYf1NRAIEm+dDjic073DRDc3/JspI/8wYmtDsHwd3+4hwvdxSK7PGaElfTmm0awWJ4w=="],
+
+ "locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A=="],
+
+ "lodash": ["[email protected]", "", {}, "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="],
+
+ "log-symbols": ["[email protected]", "", { "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" } }, "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw=="],
+
+ "long": ["[email protected]", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
+
+ "loose-envify": ["[email protected]", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="],
+
+ "lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
+
+ "lru.min": ["[email protected]", "", {}, "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA=="],
+
+ "lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-fARAFJULsGuDDydjp6+6blekG/sBIM29TerzLjc9bQUKAcEfrSc4ZQKb25KRz4OMKd87cZTb5dgq0w/T6KufVg=="],
+
+ "magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
+
+ "math-intrinsics": ["[email protected]", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
+
+ "media-typer": ["[email protected]", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="],
+
+ "memfs": ["[email protected]", "", { "dependencies": { "fs-monkey": "^1.0.4" } }, "sha512-EGowvkkgbMcIChjMTMkESFDbZeSh8xZ7kNSF0hAiAN4Jh6jgHCRS0Ga/+C8y6Au+oqpezRHCfPsmJ2+DwAgiwQ=="],
+
+ "merge-descriptors": ["[email protected]", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
+
+ "merge-stream": ["[email protected]", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],
+
+ "merge2": ["[email protected]", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],
+
+ "methods": ["[email protected]", "", {}, "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w=="],
+
+ "micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
+
+ "mime": ["[email protected]", "", { "bin": { "mime": "cli.js" } }, "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg=="],
+
+ "mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
+
+ "mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
+
+ "mimic-fn": ["[email protected]", "", {}, "sha512-Ysbi9uYW9hFyfrThdDEQuykN4Ey6BuwPD2kpI5ES/nFTDn/98yxYNLZJcgUAKPT/mcrLLKaGzJR9YVxJrIdASQ=="],
+
+ "mimic-function": ["[email protected]", "", {}, "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA=="],
+
+ "mimic-response": ["[email protected]", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="],
+
+ "minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
+
+ "minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
+
+ "minipass": ["[email protected]", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="],
+
+ "mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
+
+ "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
+
+ "multer": ["[email protected]", "", { "dependencies": { "append-field": "^1.0.0", "busboy": "^1.6.0", "concat-stream": "^2.0.0", "type-is": "^1.6.18" } }, "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ=="],
+
+ "mute-stream": ["[email protected]", "", {}, "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA=="],
+
+ "mysql2": ["[email protected]", "", { "dependencies": { "aws-ssl-profiles": "^1.1.1", "denque": "^2.1.0", "generate-function": "^2.3.1", "iconv-lite": "^0.7.0", "long": "^5.2.1", "lru.min": "^1.0.0", "named-placeholders": "^1.1.3", "seq-queue": "^0.0.5", "sqlstring": "^2.3.2" } }, "sha512-FBrGau0IXmuqg4haEZRBfHNWB5mUARw6hNwPDXXGg0XzVJ50mr/9hb267lvpVMnhZ1FON3qNd4Xfcez1rbFwSg=="],
+
+ "named-placeholders": ["[email protected]", "", { "dependencies": { "lru.min": "^1.1.0" } }, "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w=="],
+
+ "nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="],
+
+ "nanostores": ["[email protected]", "", {}, "sha512-Wxv8Roefr2nqtiRG0bnaFlpYqpIVtOEeJZHaH+4nGgOK1/7n6OHOuHCb/bhqrNQgZM8fyd0s1PqhdrJc9Ib44g=="],
+
+ "napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
+
+ "negotiator": ["[email protected]", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
+
+ "neo-async": ["[email protected]", "", {}, "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw=="],
+
+ "nestjs-trpc": ["[email protected]", "", { "dependencies": { "lodash": "^4.17.21", "tslib": "^2.5.0" }, "peerDependencies": { "@nestjs/common": "^9.3.8 || ^10.0.0 || ^11.0.0", "@nestjs/core": "^9.3.8 || ^10.0.0 || ^11.0.0", "@trpc/server": "^11.0.0", "reflect-metadata": "^0.1.13 || ^0.2.0", "rxjs": "7.8.1", "zod": "^3.14.0 || ^4.0.0" }, "bin": { "nestjs-trpc": "bin/nestjs-trpc.js" } }, "sha512-kip+4dI6vnoe/wDDtCz9ITu9WJ80dHSnSQHJR5B0WNf5FIqB9Haz69msXwV/QI8GpHsBaU5Vs9nJC1dGJkroQw=="],
+
+ "next": ["[email protected]", "", { "dependencies": { "@next/env": "16.2.12", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.2.12", "@next/swc-darwin-x64": "16.2.12", "@next/swc-linux-arm64-gnu": "16.2.12", "@next/swc-linux-arm64-musl": "16.2.12", "@next/swc-linux-x64-gnu": "16.2.12", "@next/swc-linux-x64-musl": "16.2.12", "@next/swc-win32-arm64-msvc": "16.2.12", "@next/swc-win32-x64-msvc": "16.2.12", "sharp": "^0.34.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-iD59eYQWmbFcEbX7v/acG5DRym9iw1DdaPoD0WTA920naWsE25wShzJW4+UvAs8MK9EC2kBfIH6vtto1H1PHGw=="],
+
+ "next-themes": ["[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
+
+ "node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g=="],
+
+ "node-abort-controller": ["[email protected]", "", {}, "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ=="],
+
+ "node-emoji": ["[email protected]", "", { "dependencies": { "lodash": "^4.17.21" } }, "sha512-wo2DpQkQp7Sjm2A0cq+sN7EHKO6Sl0ctXeBdFZrL9T9+UywORbufTcTZxom8YqpLQt/FqNMUkOpkZrJVYSKD3A=="],
+
+ "node-releases": ["[email protected]", "", {}, "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ=="],
+
+ "npm-run-path": ["[email protected]", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
+
+ "nuqs": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "1.1.0" }, "peerDependencies": { "@remix-run/react": ">=2", "@tanstack/react-router": "^1", "next": ">=14.2.0", "react": ">=18.2.0 || ^19.0.0-0", "react-router": "^5 || ^6 || ^7 || ^8", "react-router-dom": "^5 || ^6 || ^7" }, "optionalPeers": ["@remix-run/react", "@tanstack/react-router", "next", "react-router", "react-router-dom"] }, "sha512-lsz3NyCOKmuNAyW052i9RWqcTntoYb2Qm6FxSWnkTDwOJnGS6fzpXDAp0VcwTevw3xgnWebYpDr9rm6+o4DHbw=="],
+
+ "object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
+
+ "object-inspect": ["[email protected]", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
+
+ "object-treeify": ["[email protected]", "", {}, "sha512-EFVjAYfzWqWsBMRHPMAXLCDIJnpMhdWAqR7xG6M6a2cs6PMFpl/+Z20w9zDW4vkxOFfddegBKq9Rehd0bxWE7A=="],
+
+ "ohash": ["[email protected]", "", {}, "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ=="],
+
+ "on-finished": ["[email protected]", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
+
+ "once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
+
+ "onetime": ["[email protected]", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],
+
+ "open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
+
+ "ora": ["[email protected]", "", { "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^5.0.0", "cli-spinners": "^2.9.2", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.0.0", "log-symbols": "^6.0.0", "stdin-discarder": "^0.2.2", "string-width": "^7.2.0", "strip-ansi": "^7.1.0" } }, "sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw=="],
+
+ "p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+
+ "p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^2.0.0" } }, "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ=="],
+
+ "p-try": ["[email protected]", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="],
+
+ "parent-module": ["[email protected]", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="],
+
+ "parse-json": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg=="],
+
+ "parse-ms": ["[email protected]", "", {}, "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw=="],
+
+ "parseurl": ["[email protected]", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
+
+ "path-browserify": ["[email protected]", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
+
+ "path-exists": ["[email protected]", "", {}, "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ=="],
+
+ "path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
+
+ "path-scurry": ["[email protected]", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg=="],
+
+ "path-to-regexp": ["[email protected]", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
+
+ "path-type": ["[email protected]", "", {}, "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw=="],
+
+ "pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
+
+ "perfect-debounce": ["[email protected]", "", {}, "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g=="],
+
+ "pg": ["[email protected]", "", { "dependencies": { "pg-connection-string": "^2.14.0", "pg-pool": "^3.14.0", "pg-protocol": "^1.15.0", "pg-types": "2.2.0", "pgpass": "1.0.5" }, "optionalDependencies": { "pg-cloudflare": "^1.4.0" }, "peerDependencies": { "pg-native": ">=3.0.1" }, "optionalPeers": ["pg-native"] }, "sha512-8wih1vVIBMxoUM2oB4soJsD9tDnDpLv4OXBJ+EJzFsvycD+lfyIreC2gGHq78f8jbLLt+bvlPTFdFZfJkOuzAA=="],
+
+ "pg-cloudflare": ["[email protected]", "", {}, "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A=="],
+
+ "pg-connection-string": ["[email protected]", "", {}, "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg=="],
+
+ "pg-int8": ["[email protected]", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="],
+
+ "pg-pool": ["[email protected]", "", { "peerDependencies": { "pg": ">=8.0" } }, "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw=="],
+
+ "pg-protocol": ["[email protected]", "", {}, "sha512-cq9sECI5s0+uPUXjbz8ioyPJni6RzsRib0US67i5IoTZKw8fNeYlVE7u8F4dG7vEJJtc5wdD1K189lCCUwqWTQ=="],
+
+ "pg-types": ["[email protected]", "", { "dependencies": { "pg-int8": "1.0.1", "postgres-array": "~2.0.0", "postgres-bytea": "~1.0.0", "postgres-date": "~1.0.4", "postgres-interval": "^1.1.0" } }, "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA=="],
+
+ "pgpass": ["[email protected]", "", { "dependencies": { "split2": "^4.1.0" } }, "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug=="],
+
+ "picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
+
+ "picomatch": ["[email protected]", "", {}, "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A=="],
+
+ "pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
+
+ "pkg-types": ["[email protected]", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],
+
+ "pkg-up": ["[email protected]", "", { "dependencies": { "find-up": "^3.0.0" } }, "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA=="],
+
+ "pluralize": ["[email protected]", "", {}, "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA=="],
+
+ "postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw=="],
+
+ "postcss-selector-parser": ["[email protected]", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg=="],
+
+ "postgres": ["[email protected]", "", {}, "sha512-Jtc2612XINuBjIl/QTWsV5UvE8UHuNblcO3vVADSrKsrc6RqGX6lOW1cEo3CM2v0XG4Nat8nI+YM7/f26VxXLw=="],
+
+ "postgres-array": ["[email protected]", "", {}, "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ=="],
+
+ "postgres-bytea": ["[email protected]", "", {}, "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ=="],
+
+ "postgres-date": ["[email protected]", "", {}, "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q=="],
+
+ "postgres-interval": ["[email protected]", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="],
+
+ "powershell-utils": ["[email protected]", "", {}, "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A=="],
+
+ "prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
+
+ "prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g=="],
+
+ "pretty-ms": ["[email protected]", "", { "dependencies": { "parse-ms": "^4.0.0" } }, "sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ=="],
+
+ "prisma": ["[email protected]", "", { "dependencies": { "@prisma/config": "7.9.1", "@prisma/dev": "0.24.17", "@prisma/engines": "7.9.1", "@prisma/studio-core": "0.33.0", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-aPqePoZIqwlAchbgbFDO/wHqGB+7H1nj9gaM+OsL9h77S5S3TnLd9BgD3LnoeDikULo7cl2HSUrEyQ55Z7DYbg=="],
+
+ "prompts": ["[email protected]", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="],
+
+ "prop-types": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="],
+
+ "proper-lockfile": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "retry": "^0.12.0", "signal-exit": "^3.0.2" } }, "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA=="],
+
+ "proxy-addr": ["[email protected]", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
+
+ "pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
+
+ "punycode": ["[email protected]", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
+
+ "pure-rand": ["[email protected]", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
+
+ "qs": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A=="],
+
+ "queue-microtask": ["[email protected]", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
+
+ "radix-ui": ["[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-accessible-icon": "1.1.15", "@radix-ui/react-accordion": "1.2.20", "@radix-ui/react-alert-dialog": "1.1.23", "@radix-ui/react-arrow": "1.1.15", "@radix-ui/react-aspect-ratio": "1.1.15", "@radix-ui/react-avatar": "1.2.6", "@radix-ui/react-checkbox": "1.3.11", "@radix-ui/react-collapsible": "1.1.20", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-context-menu": "2.3.7", "@radix-ui/react-dialog": "1.1.23", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-dropdown-menu": "2.1.24", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-form": "0.1.16", "@radix-ui/react-hover-card": "1.1.23", "@radix-ui/react-label": "2.1.15", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-menubar": "1.1.24", "@radix-ui/react-navigation-menu": "1.2.22", "@radix-ui/react-one-time-password-field": "0.1.16", "@radix-ui/react-password-toggle-field": "0.1.11", "@radix-ui/react-popover": "1.1.23", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-progress": "1.1.16", "@radix-ui/react-radio-group": "1.4.7", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-scroll-area": "1.2.18", "@radix-ui/react-select": "2.3.7", "@radix-ui/react-separator": "1.1.15", "@radix-ui/react-slider": "1.4.7", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-switch": "1.3.7", "@radix-ui/react-tabs": "1.1.21", "@radix-ui/react-toast": "1.2.23", "@radix-ui/react-toggle": "1.1.18", "@radix-ui/react-toggle-group": "1.1.19", "@radix-ui/react-toolbar": "1.1.19", "@radix-ui/react-tooltip": "1.2.16", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-escape-keydown": "1.1.5", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-size": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-QBdhh1arIEUvPC0dQ5+nwWAxt7+N+oP/9jPwjJkGFoSk/sqxg32gJtSXGtFh8frAIcS6oC9cx2Q+7KYCQLOAeA=="],
+
+ "range-parser": ["[email protected]", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="],
+
+ "raw-body": ["[email protected]", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
+
+ "rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
+
+ "rc9": ["[email protected]", "", { "dependencies": { "defu": "^6.1.6", "destr": "^2.0.5" } }, "sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ=="],
+
+ "react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],
+
+ "react-day-picker": ["[email protected]", "", { "dependencies": { "@date-fns/tz": "^1.4.1", "date-fns": "^4.1.0" }, "peerDependencies": { "@types/react": ">=16.8.0", "react": ">=16.8.0" }, "optionalPeers": ["@types/react"] }, "sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w=="],
+
+ "react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
+
+ "react-hook-form": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17 || ^18 || ^19" } }, "sha512-AXt8cMCmx5a7u4uvpb2uRFVrWQhllI4pV+LSykxIac/hjt44TnQkmX9BKuQi2i+LDC62esmiLpilkav+kjVf/A=="],
+
+ "react-is": ["[email protected]", "", {}, "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ=="],
+
+ "react-redux": ["[email protected]", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.6", "use-sync-external-store": "^1.4.0" }, "peerDependencies": { "@types/react": "^18.2.25 || ^19", "react": "^18.0 || ^19", "redux": "^5.0.0" }, "optionalPeers": ["@types/react", "redux"] }, "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g=="],
+
+ "react-remove-scroll": ["[email protected]", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="],
+
+ "react-remove-scroll-bar": ["[email protected]", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="],
+
+ "react-resizable-panels": ["[email protected]", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" } }, "sha512-NwY5LCo4WrxVvDh0xoMML6EMLPONP/8ckKcIdpnojxexoatZdjLiRqLJQjQK5CPkd4SYiB/2M5BVrjZBQtOO7Q=="],
+
+ "react-style-singleton": ["[email protected]", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],
+
+ "readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
+
+ "readdirp": ["[email protected]", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="],
+
+ "recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-T98lym7kH+pnZmRaD8yDRdaNqyUbwnbEBx0MuchrzMFOEMray4AO3ZJoTUZ5r78Ao78X/OhzW0DL8GB85w/I2w=="],
+
+ "recharts": ["[email protected]", "", { "dependencies": { "@reduxjs/toolkit": "^1.9.0 || 2.x.x", "clsx": "^2.1.1", "decimal.js-light": "^2.5.1", "es-toolkit": "^1.39.3", "eventemitter3": "^5.0.1", "immer": "^10.1.1", "react-redux": "8.x.x || 9.x.x", "reselect": "5.1.1", "tiny-invariant": "^1.3.3", "use-sync-external-store": "^1.2.2", "victory-vendor": "^37.0.2" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Z/m38DX3L73ExO4Tpc9/iZWHmHnlzWG4njQbxsF5aSjwqmHNDDIm0rdEBArkwsBvR8U6EirlEHiQNYWCVh9sGQ=="],
+
+ "redux": ["[email protected]", "", {}, "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w=="],
+
+ "redux-thunk": ["[email protected]", "", { "peerDependencies": { "redux": "^5.0.0" } }, "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw=="],
+
+ "reflect-metadata": ["[email protected]", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="],
+
+ "regexp-to-ast": ["[email protected]", "", {}, "sha512-tlbJqcMHnPKI9zSrystikWKwHkBqu2a/Sgw01h3zFjvYrMxEDYHzzoMZnUrbIfpTFEsoRnnviOXNCzFiSc54Qw=="],
+
+ "remeda": ["[email protected]", "", {}, "sha512-ygHswjlc/opg2VrtiYvUOPLjxjtdKvjGz1/plDhkG66hjNjFr1xmfrs2ClNFo/E6TyUFiwYNh53bKV26oBoMGQ=="],
+
+ "require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
+
+ "require-from-string": ["[email protected]", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
+
+ "reselect": ["[email protected]", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],
+
+ "resolve-from": ["[email protected]", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
+
+ "restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],
+
+ "ret": ["[email protected]", "", {}, "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw=="],
+
+ "retry": ["[email protected]", "", {}, "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow=="],
+
+ "reusify": ["[email protected]", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="],
+
+ "robust-predicates": ["[email protected]", "", {}, "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA=="],
+
+ "rou3": ["[email protected]", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="],
+
+ "router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
+
+ "run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
+
+ "run-parallel": ["[email protected]", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="],
+
+ "rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
+
+ "safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
+
+ "safe-regex2": ["[email protected]", "", { "dependencies": { "ret": "~0.5.0" }, "bin": { "safe-regex2": "bin/safe-regex2.js" } }, "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA=="],
+
+ "safer-buffer": ["[email protected]", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
+
+ "scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
+
+ "schema-utils": ["[email protected]", "", { "dependencies": { "@types/json-schema": "^7.0.8", "ajv": "^6.12.5", "ajv-keywords": "^3.5.2" } }, "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg=="],
+
+ "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+
+ "send": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
+
+ "seq-queue": ["[email protected]", "", {}, "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q=="],
+
+ "serve-static": ["[email protected]", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
+
+ "set-cookie-parser": ["[email protected]", "", {}, "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw=="],
+
+ "setprototypeof": ["[email protected]", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
+
+ "shadcn": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/parser": "^7.28.0", "@babel/plugin-transform-typescript": "^7.28.0", "@babel/preset-typescript": "^7.27.1", "@dotenvx/dotenvx": "^1.48.4", "@modelcontextprotocol/sdk": "^1.26.0", "@types/validate-npm-package-name": "^4.0.2", "browserslist": "^4.26.2", "commander": "^14.0.0", "cosmiconfig": "^9.0.0", "dedent": "^1.6.0", "deepmerge": "^4.3.1", "diff": "^8.0.2", "execa": "^9.6.0", "fast-glob": "^3.3.3", "fs-extra": "^11.3.1", "fuzzysort": "^3.1.0", "kleur": "^4.1.5", "open": "^11.0.0", "ora": "^8.2.0", "postcss": "^8.5.6", "postcss-selector-parser": "^7.1.0", "prompts": "^2.4.2", "recast": "^0.23.11", "stringify-object": "^5.0.0", "tailwind-merge": "^3.0.1", "ts-morph": "^26.0.0", "tsconfig-paths": "^4.2.0", "undici": "^7.27.2", "validate-npm-package-name": "^7.0.1", "zod": "^3.24.1", "zod-to-json-schema": "^3.24.6" }, "bin": { "shadcn": "dist/index.js" } }, "sha512-XLFzfNNIUPlUlyheFEzj0H4Vnhi9nI0nl3Nfgg8HYXW1FkUVhVT1X+mgmOUW8aWL5SeG0A+yJIV5fm3Hr9MVkQ=="],
+
+ "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.0.0", "detect-libc": "^2.1.2", "semver": "^7.7.3" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.34.5", "@img/sharp-darwin-x64": "0.34.5", "@img/sharp-libvips-darwin-arm64": "1.2.4", "@img/sharp-libvips-darwin-x64": "1.2.4", "@img/sharp-libvips-linux-arm": "1.2.4", "@img/sharp-libvips-linux-arm64": "1.2.4", "@img/sharp-libvips-linux-ppc64": "1.2.4", "@img/sharp-libvips-linux-riscv64": "1.2.4", "@img/sharp-libvips-linux-s390x": "1.2.4", "@img/sharp-libvips-linux-x64": "1.2.4", "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", "@img/sharp-libvips-linuxmusl-x64": "1.2.4", "@img/sharp-linux-arm": "0.34.5", "@img/sharp-linux-arm64": "0.34.5", "@img/sharp-linux-ppc64": "0.34.5", "@img/sharp-linux-riscv64": "0.34.5", "@img/sharp-linux-s390x": "0.34.5", "@img/sharp-linux-x64": "0.34.5", "@img/sharp-linuxmusl-arm64": "0.34.5", "@img/sharp-linuxmusl-x64": "0.34.5", "@img/sharp-wasm32": "0.34.5", "@img/sharp-win32-arm64": "0.34.5", "@img/sharp-win32-ia32": "0.34.5", "@img/sharp-win32-x64": "0.34.5" } }, "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg=="],
+
+ "shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
+
+ "shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
+
+ "shell-quote": ["[email protected]", "", {}, "sha512-Iov+JwFv/2HcTpcwNMKd8+IWNb8tboQJNQTkAY/LLVK7gGH9jy+LGkVqPxfekHl+yMmiqXszdGWXgkfml7hjqA=="],
+
+ "side-channel": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="],
+
+ "side-channel-list": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
+
+ "side-channel-map": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
+
+ "side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
+
+ "signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
+
+ "simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
+
+ "simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
+
+ "sisteransi": ["[email protected]", "", {}, "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="],
+
+ "sonner": ["[email protected]", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w=="],
+
+ "source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
+
+ "source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
+
+ "source-map-support": ["[email protected]", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w=="],
+
+ "split2": ["[email protected]", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="],
+
+ "sqlstring": ["[email protected]", "", {}, "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="],
+
+ "statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
+
+ "std-env": ["[email protected]", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
+
+ "stdin-discarder": ["[email protected]", "", {}, "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ=="],
+
+ "streamsearch": ["[email protected]", "", {}, "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg=="],
+
+ "string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
+
+ "string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
+
+ "stringify-object": ["[email protected]", "", { "dependencies": { "get-own-enumerable-keys": "^1.0.0", "is-obj": "^3.0.0", "is-regexp": "^3.1.0" } }, "sha512-zaJYxz2FtcMb4f+g60KsRNFOpVMUyuJgA51Zi5Z1DOTC3S59+OQiVOzE9GZt0x72uBGWKsQIuBKeF9iusmKFsg=="],
+
+ "strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],
+
+ "strip-bom": ["[email protected]", "", {}, "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA=="],
+
+ "strip-final-newline": ["[email protected]", "", {}, "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw=="],
+
+ "strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
+
+ "strtok3": ["[email protected]", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA=="],
+
+ "styled-jsx": ["[email protected]", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="],
+
+ "superagent": ["[email protected]", "", { "dependencies": { "component-emitter": "^1.3.1", "cookiejar": "^2.1.4", "debug": "^4.3.7", "fast-safe-stringify": "^2.1.1", "form-data": "^4.0.5", "formidable": "^3.5.4", "methods": "^1.1.2", "mime": "2.6.0", "qs": "^6.14.1" } }, "sha512-B+4Ik7ROgVKrQsXTV0Jwp2u+PXYLSlqtDAhYnkkD+zn3yg8s/zjA2MeGayPoY/KICrbitwneDHrjSotxKL+0XQ=="],
+
+ "supertest": ["[email protected]", "", { "dependencies": { "cookie-signature": "^1.2.2", "methods": "^1.1.2", "superagent": "^10.3.0" } }, "sha512-oK8WG9diS3DlhdUkcFn4tkNIiIbBx9lI2ClF8K+b2/m8Eyv47LSawxUzZQSNKUrVb2KsqeTDCcjAAVPYaSLVTA=="],
+
+ "supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],
+
+ "symbol-observable": ["[email protected]", "", {}, "sha512-b19dMThMV4HVFynSAM1++gBHAbk2Tc/osgLIBZMKsyqh34jb2e8Os7T6ZW/Bt3pJFdBTd2JwAnAAEQV7rSNvcQ=="],
+
+ "systeminformation": ["[email protected]", "", { "os": "!aix", "bin": { "systeminformation": "lib/cli.js" } }, "sha512-DEN6ICHk3Tk0Uf/hrAHh7xlt7iL5CJFBtPZinA0H62DrGG/KPKqq/Nzj6lCXPS4Ay/sf/14zNnk9LpqKzBIc+w=="],
+
+ "tailwind-merge": ["[email protected]", "", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="],
+
+ "tailwindcss": ["[email protected]", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="],
+
+ "tapable": ["[email protected]", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],
+
+ "tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw=="],
+
+ "tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
+
+ "terser": ["[email protected]", "", { "dependencies": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, "bin": { "terser": "bin/terser" } }, "sha512-SNiDnXyHSrxVcIOtVbULzcTmniUiwcV7Nwdyj1twVubeTmbjoa8p69KKDpfkdoOavuM4/GRm1+ykI8qqnavHoA=="],
+
+ "terser-webpack-plugin": ["[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.25", "jest-worker": "^27.4.5", "schema-utils": "^4.3.0", "terser": "^5.31.1" }, "peerDependencies": { "webpack": "^5.1.0" } }, "sha512-201R5j+sJpK8nFWwKVyNfZot8FaJbLZDq5evriVzbV1wDtSXDjRUDRfJzHpAaxFDMEhsZL1QkeqM61wgsS3KaQ=="],
+
+ "tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
+
+ "to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
+
+ "toidentifier": ["[email protected]", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
+
+ "token-types": ["[email protected]", "", { "dependencies": { "@borewit/text-codec": "^0.2.1", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww=="],
+
+ "tree-kill": ["[email protected]", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],
+
+ "ts-morph": ["[email protected]", "", { "dependencies": { "@ts-morph/common": "~0.27.0", "code-block-writer": "^13.0.3" } }, "sha512-ztMO++owQnz8c/gIENcM9XfCEzgoGphTv+nKpYNM1bgsdOVC/jRZuEBf6N+mLLDNg68Kl+GgUZfOySaRiG1/Ug=="],
+
+ "tsconfig-paths": ["[email protected]", "", { "dependencies": { "json5": "^2.2.2", "minimist": "^1.2.6", "strip-bom": "^3.0.0" } }, "sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg=="],
+
+ "tsconfig-paths-webpack-plugin": ["[email protected]", "", { "dependencies": { "chalk": "^4.1.0", "enhanced-resolve": "^5.7.0", "tapable": "^2.2.1", "tsconfig-paths": "^4.1.2" } }, "sha512-zbem3rfRS8BgeNK50Zz5SIQgXzLafiHjOwUAvk/38/o1jHn/V5QAgVUcz884or7WYcPaH3N2CIfUc2u0ul7UcA=="],
+
+ "tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
+
+ "turbo": ["[email protected]", "", { "optionalDependencies": { "@turbo/darwin-64": "2.10.8", "@turbo/darwin-arm64": "2.10.8", "@turbo/linux-64": "2.10.8", "@turbo/linux-arm64": "2.10.8", "@turbo/windows-64": "2.10.8", "@turbo/windows-arm64": "2.10.8" }, "bin": { "turbo": "bin/turbo" } }, "sha512-9+8YX5QOkGXzZxcIykTHgaooRHGMWO+jfdyRK0o+rN0U7hBIig2MrJ8r/aNzIPDPhdA73SGb0O+tIztaModTMg=="],
+
+ "tw-animate-css": ["[email protected]", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
+
+ "type-is": ["[email protected]", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],
+
+ "typedarray": ["[email protected]", "", {}, "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="],
+
+ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A=="],
+
+ "uid": ["[email protected]", "", { "dependencies": { "@lukeed/csprng": "^1.0.0" } }, "sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g=="],
+
+ "uint8array-extras": ["[email protected]", "", {}, "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A=="],
+
+ "undici": ["[email protected]", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
+
+ "unicorn-magic": ["[email protected]", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],
+
+ "universalify": ["[email protected]", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
+
+ "unpipe": ["[email protected]", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
+
+ "update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
+
+ "uri-js": ["[email protected]", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
+
+ "use-callback-ref": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="],
+
+ "use-sidecar": ["[email protected]", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="],
+
+ "use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
+
+ "util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
+
+ "valibot": ["[email protected]", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg=="],
+
+ "validate-npm-package-name": ["[email protected]", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="],
+
+ "validator": ["[email protected]", "", {}, "sha512-TQ5pAGhd5whStmqWvYF4OjQROlmv9SMFVt37qoCBdqRffuuklWYQlCNnEs2ZaIBD1kZRNnikiZOS1eqgkar0iw=="],
+
+ "vary": ["[email protected]", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
+
+ "vaul": ["[email protected]", "", { "dependencies": { "@radix-ui/react-dialog": "^1.1.1" }, "peerDependencies": { "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA=="],
+
+ "victory-vendor": ["[email protected]", "", { "dependencies": { "@types/d3-array": "^3.0.3", "@types/d3-ease": "^3.0.0", "@types/d3-interpolate": "^3.0.1", "@types/d3-scale": "^4.0.2", "@types/d3-shape": "^3.1.0", "@types/d3-time": "^3.0.0", "@types/d3-timer": "^3.0.0", "d3-array": "^3.1.6", "d3-ease": "^3.0.1", "d3-interpolate": "^3.0.1", "d3-scale": "^4.0.2", "d3-shape": "^3.1.0", "d3-time": "^3.0.0", "d3-timer": "^3.0.1" } }, "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ=="],
+
+ "watchpack": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.1.2" } }, "sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg=="],
+
+ "wcwidth": ["[email protected]", "", { "dependencies": { "defaults": "^1.0.3" } }, "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg=="],
+
+ "webpack": ["[email protected]", "", { "dependencies": { "@types/eslint-scope": "^3.7.7", "@types/estree": "^1.0.8", "@types/json-schema": "^7.0.15", "@webassemblyjs/ast": "^1.14.1", "@webassemblyjs/wasm-edit": "^1.14.1", "@webassemblyjs/wasm-parser": "^1.14.1", "acorn": "^8.16.0", "acorn-import-phases": "^1.0.3", "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", "enhanced-resolve": "^5.20.0", "es-module-lexer": "^2.0.0", "eslint-scope": "5.1.1", "events": "^3.2.0", "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.2.11", "loader-runner": "^4.3.1", "mime-db": "^1.54.0", "neo-async": "^2.6.2", "schema-utils": "^4.3.3", "tapable": "^2.3.0", "terser-webpack-plugin": "^5.3.17", "watchpack": "^2.5.1", "webpack-sources": "^3.3.4" }, "bin": { "webpack": "bin/webpack.js" } }, "sha512-wGN3qcrBQIFmQ/c0AiOAQBvrZ5lmY8vbbMv4Mxfgzqd/B6+9pXtLo73WuS1dSGXM5QYY3hZnIbvx+K1xxe6FyA=="],
+
+ "webpack-node-externals": ["[email protected]", "", {}, "sha512-LnL6Z3GGDPht/AigwRh2dvL9PQPFQ8skEpVrWZXLWBYmqcaojHNN0onvHzie6rq7EWKrrBfPYqNEzTJgiwEQDQ=="],
+
+ "webpack-sources": ["[email protected]", "", {}, "sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw=="],
+
+ "which": ["[email protected]", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg=="],
+
+ "wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
+
+ "wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
+
+ "wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],
+
+ "xtend": ["[email protected]", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
+
+ "y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
+
+ "yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
+
+ "yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
+
+ "yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
+
+ "yocto-spinner": ["[email protected]", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-sqBChb33loEnkoXte1bLg45bEBsOP9N1kzQh5JZNKj/0rik4zAPTNSAVPj3uQAdc6slYJ0Ksc403G2XgxsJQFQ=="],
+
+ "yoctocolors": ["[email protected]", "", {}, "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg=="],
+
+ "yoctocolors-cjs": ["[email protected]", "", {}, "sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw=="],
+
+ "zeptomatch": ["[email protected]", "", { "dependencies": { "grammex": "^3.1.11", "graphmatch": "^1.1.0" } }, "sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA=="],
+
+ "zod": ["[email protected]", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
+
+ "zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
+
+ "@angular-devkit/core/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
+
+ "@angular-devkit/core/rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg=="],
+
+ "@angular-devkit/core/source-map": ["[email protected]", "", {}, "sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA=="],
+
+ "@angular-devkit/schematics/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0" } }, "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA=="],
+
+ "@angular-devkit/schematics/ora": ["[email protected]", "", { "dependencies": { "bl": "^4.1.0", "chalk": "^4.1.0", "cli-cursor": "^3.1.0", "cli-spinners": "^2.5.0", "is-interactive": "^1.0.0", "is-unicode-supported": "^0.1.0", "log-symbols": "^4.1.0", "strip-ansi": "^6.0.0", "wcwidth": "^1.0.1" } }, "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ=="],
+
+ "@angular-devkit/schematics/rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg=="],
+
+ "@angular-devkit/schematics-cli/@inquirer/prompts": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/checkbox": "^4.1.2", "@inquirer/confirm": "^5.1.6", "@inquirer/editor": "^4.2.7", "@inquirer/expand": "^4.0.9", "@inquirer/input": "^4.1.6", "@inquirer/number": "^3.0.9", "@inquirer/password": "^4.0.9", "@inquirer/rawlist": "^4.0.9", "@inquirer/search": "^3.0.9", "@inquirer/select": "^4.0.9" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-G1ytyOoHh5BphmEBxSwALin3n1KGNYB6yImbICcRQdzXfOGbuJ9Jske/Of5Sebk339NSGGNfUshnzK8YWkTPsQ=="],
+
+ "@babel/core/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@babel/helper-compilation-targets/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@babel/helper-create-class-features-plugin/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@better-auth/cli/@prisma/client": ["@prisma/[email protected]", "", { "peerDependencies": { "prisma": "*" }, "optionalPeers": ["prisma"] }, "sha512-M0SVXfyHnQREBKxCgyo7sffrKttwE6R8PMq330MIUF0pTwjUhLbW84pFDlf06B27XyCR++VtjugEnIHdr07SVA=="],
+
+ "@better-auth/cli/better-auth": ["[email protected]", "", { "dependencies": { "@better-auth/core": "1.4.22", "@better-auth/telemetry": "1.4.22", "@better-auth/utils": "0.3.0", "@better-fetch/fetch": "1.1.21", "@noble/ciphers": "^2.0.0", "@noble/hashes": "^2.0.0", "better-call": "1.1.8", "defu": "^6.1.4", "jose": "^6.1.0", "kysely": "^0.28.5", "nanostores": "^1.0.1", "zod": "^4.3.5" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": ">=0.41.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-CXQ7ZLDkf/I9iaVTNuejJ7FlWal50hRPIv1n0lqMipvthEoMx+2RQyNXUvzGRjltSe5d9rcZPI3IxdtS1A5+YA=="],
+
+ "@better-auth/core/@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="],
+
+ "@better-auth/core/better-call": ["[email protected]", "", { "dependencies": { "@better-auth/utils": "^0.3.0", "@better-fetch/fetch": "^1.1.4", "rou3": "^0.7.10", "set-cookie-parser": "^2.7.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-XMQ2rs6FNXasGNfMjzbyroSwKwYbZ/T3IxruSS6U2MJRsSYh3wYtG3o6H00ZlKZ/C/UPOAD97tqgQJNsxyeTXw=="],
+
+ "@better-auth/core/kysely": ["[email protected]", "", {}, "sha512-nbD8lB9EB3wNdMhOCdx5Li8DxnLbvKByylRLcJ1h+4SkrowVeECAyZlyiKMThF7xFdRz0jSQ2MoJr+wXux2y0Q=="],
+
+ "@better-auth/drizzle-adapter/@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@cloudflare/workers-types": ">=4", "@opentelemetry/api": "^1.9.0", "better-call": "1.3.7", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types", "@opentelemetry/api"] }, "sha512-lMTlhtwyK4NpY9kPF+2rQCRKYpg136d3gM2xl8esxT1PjJx5Nh5YwZvxcYCIjDuO759sx6TCloJTuwcZGG6ZBw=="],
+
+ "@better-auth/drizzle-adapter/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "@better-auth/kysely-adapter/@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@cloudflare/workers-types": ">=4", "@opentelemetry/api": "^1.9.0", "better-call": "1.3.7", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types", "@opentelemetry/api"] }, "sha512-lMTlhtwyK4NpY9kPF+2rQCRKYpg136d3gM2xl8esxT1PjJx5Nh5YwZvxcYCIjDuO759sx6TCloJTuwcZGG6ZBw=="],
+
+ "@better-auth/kysely-adapter/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "@better-auth/memory-adapter/@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@cloudflare/workers-types": ">=4", "@opentelemetry/api": "^1.9.0", "better-call": "1.3.7", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types", "@opentelemetry/api"] }, "sha512-lMTlhtwyK4NpY9kPF+2rQCRKYpg136d3gM2xl8esxT1PjJx5Nh5YwZvxcYCIjDuO759sx6TCloJTuwcZGG6ZBw=="],
+
+ "@better-auth/memory-adapter/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "@better-auth/mongo-adapter/@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@cloudflare/workers-types": ">=4", "@opentelemetry/api": "^1.9.0", "better-call": "1.3.7", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types", "@opentelemetry/api"] }, "sha512-lMTlhtwyK4NpY9kPF+2rQCRKYpg136d3gM2xl8esxT1PjJx5Nh5YwZvxcYCIjDuO759sx6TCloJTuwcZGG6ZBw=="],
+
+ "@better-auth/mongo-adapter/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "@better-auth/prisma-adapter/@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@cloudflare/workers-types": ">=4", "@opentelemetry/api": "^1.9.0", "better-call": "1.3.7", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types", "@opentelemetry/api"] }, "sha512-lMTlhtwyK4NpY9kPF+2rQCRKYpg136d3gM2xl8esxT1PjJx5Nh5YwZvxcYCIjDuO759sx6TCloJTuwcZGG6ZBw=="],
+
+ "@better-auth/prisma-adapter/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "@better-auth/telemetry/@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="],
+
+ "@chevrotain/cst-dts-gen/lodash": ["[email protected]", "", {}, "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="],
+
+ "@chevrotain/gast/lodash": ["[email protected]", "", {}, "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="],
+
+ "@crm/ui/react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
+
+ "@dotenvx/dotenvx/commander": ["[email protected]", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],
+
+ "@dotenvx/dotenvx/execa": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="],
+
+ "@dotenvx/dotenvx/open": ["[email protected]", "", { "dependencies": { "define-lazy-prop": "^2.0.0", "is-docker": "^2.1.1", "is-wsl": "^2.2.0" } }, "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ=="],
+
+ "@dotenvx/dotenvx/yocto-spinner": ["[email protected]", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="],
+
+ "@inquirer/core/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
+
+ "@nestjs/cli/commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],
+
+ "@nestjs/cli/ora": ["[email protected]", "", { "dependencies": { "bl": "^4.1.0", "chalk": "^4.1.0", "cli-cursor": "^3.1.0", "cli-spinners": "^2.5.0", "is-interactive": "^1.0.0", "is-unicode-supported": "^0.1.0", "log-symbols": "^4.1.0", "strip-ansi": "^6.0.0", "wcwidth": "^1.0.1" } }, "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ=="],
+
+ "@nestjs/cli/typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "@nestjs/config/dotenv": ["[email protected]", "", {}, "sha512-k8DaKGP6r1G30Lx8V4+pCsLzKr8vLmV2paqEj1Y55GdAgJuIqpRp5FfajGF8KtwMxCz9qJc6wUIJnm053d/WCw=="],
+
+ "@nestjs/schematics/@angular-devkit/core": ["@angular-devkit/[email protected]", "", { "dependencies": { "ajv": "8.18.0", "ajv-formats": "3.0.1", "jsonc-parser": "3.3.1", "picomatch": "4.0.4", "rxjs": "7.8.1", "source-map": "0.7.4" }, "peerDependencies": { "chokidar": "^4.0.0" }, "optionalPeers": ["chokidar"] }, "sha512-Kd49warf6U/EyWe5BszF/eebN3zQ3bk7tgfEljAw8q/rX95UUtriJubWvp6pgzHfzBA4jwq8f+QiNZB8eBEXPA=="],
+
+ "@nestjs/schematics/@angular-devkit/schematics": ["@angular-devkit/[email protected]", "", { "dependencies": { "@angular-devkit/core": "19.2.24", "jsonc-parser": "3.3.1", "magic-string": "0.30.17", "ora": "5.4.1", "rxjs": "7.8.1" } }, "sha512-lnw+ZM1Io+cJAkReC0NPDjqObL8NtKzKIkdgEEKC8CUmkhurYhedbicN8Y8NYHgG1uLd2GozW3+/QqPRZaN+Lw=="],
+
+ "@paralleldrive/cuid2/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],
+
+ "@prisma/engines/@prisma/get-platform": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.9.1" } }, "sha512-PK8R60YZRQvYxBrGG9i7l2/rFyzy+2MuI1dKtmtrCqPH8YpiJx/MfiC7LRzX5786rZDEv7BngcjfIJW4/9ADuw=="],
+
+ "@prisma/fetch-engine/@prisma/get-platform": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.9.1" } }, "sha512-PK8R60YZRQvYxBrGG9i7l2/rFyzy+2MuI1dKtmtrCqPH8YpiJx/MfiC7LRzX5786rZDEv7BngcjfIJW4/9ADuw=="],
+
+ "@prisma/get-platform/@prisma/debug": ["@prisma/[email protected]", "", {}, "sha512-YSGTiSlBAVJPzX4ONZmMotL+ozJwQjRmZweQNIq/ER0tQJKJynNkRB3kyvt37eOfsbMCXk3gnLF6J9OJ4QWftw=="],
+
+ "@prisma/streams-local/env-paths": ["[email protected]", "", {}, "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A=="],
+
+ "@prisma/studio-core/@radix-ui/react-toggle": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ=="],
+
+ "@radix-ui/react-accordion/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-accordion/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-alert-dialog/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-alert-dialog/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-arrow/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-aspect-ratio/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-avatar/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-checkbox/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-checkbox/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-collapsible/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-collapsible/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-collection/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-collection/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-context-menu/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-dialog/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-dialog/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-dismissable-layer/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-dismissable-layer/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-dropdown-menu/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-dropdown-menu/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-focus-scope/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-focus-scope/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-form/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-form/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-hover-card/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-hover-card/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-label/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-menu/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-menu/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-menubar/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-menubar/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-navigation-menu/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-navigation-menu/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-one-time-password-field/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-one-time-password-field/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-password-toggle-field/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-password-toggle-field/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-popover/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-popover/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-popper/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-popper/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-portal/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
+
+ "@radix-ui/react-progress/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-radio-group/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-radio-group/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-roving-focus/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-roving-focus/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-scroll-area/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-scroll-area/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-select/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-select/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-separator/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-slider/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-slider/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-switch/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-switch/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-tabs/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-toast/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-toast/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-toggle/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-toggle-group/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-toolbar/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-tooltip/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "@radix-ui/react-tooltip/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@radix-ui/react-visually-hidden/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "@reduxjs/toolkit/immer": ["[email protected]", "", {}, "sha512-VrNANlmnWQnh5COXIIOQXM9oOJw7naGKlBT74ZOOR6lpVXc3gFEu9FJLDFcpCJ2j+NWr8TIwtWD//T6ZX6TKiQ=="],
+
+ "@reduxjs/toolkit/reselect": ["[email protected]", "", {}, "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" }, "bundled": true }, "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "@ts-morph/common/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
+
+ "@visx/vendor/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ=="],
+
+ "ajv-keywords/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
+
+ "api/typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "app/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA=="],
+
+ "app/react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
+
+ "app/typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "better-auth/@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@cloudflare/workers-types": ">=4", "@opentelemetry/api": "^1.9.0", "better-call": "1.3.7", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types", "@opentelemetry/api"] }, "sha512-lMTlhtwyK4NpY9kPF+2rQCRKYpg136d3gM2xl8esxT1PjJx5Nh5YwZvxcYCIjDuO759sx6TCloJTuwcZGG6ZBw=="],
+
+ "better-auth/@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.25", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1" } }, "sha512-2ZfC9lp7tU6Jw/q2Lz/bKfQqGMdMwc/IQDTYdBhvtGi24qInYVnhp2ZCW57hHM9j+fq1ULOtxgg6M3T1LEaihw=="],
+
+ "better-auth/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "better-call/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "body-parser/content-type": ["[email protected]", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
+
+ "c12/chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="],
+
+ "chevrotain/lodash": ["[email protected]", "", {}, "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="],
+
+ "cli-table3/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
+ "cliui/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
+ "cliui/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "concurrently/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
+
+ "conf/ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="],
+
+ "conf/json-schema-typed": ["[email protected]", "", {}, "sha512-7DE8mpG+/fVw+dTpjbxnx47TaMnDfOI1jwft9g1VybltZCduyRQPJPvc+zzKY9WPHxhPWczyFuYa6I8Mw4iU5A=="],
+
+ "cross-spawn/which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
+
+ "dot-prop/is-obj": ["[email protected]", "", {}, "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w=="],
+
+ "dotenv-expand/dotenv": ["[email protected]", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],
+
+ "enquirer/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "esrecurse/estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
+
+ "fork-ts-checker-webpack-plugin/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
+
+ "fork-ts-checker-webpack-plugin/cosmiconfig": ["[email protected]", "", { "dependencies": { "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0", "path-type": "^4.0.0" }, "peerDependencies": { "typescript": ">=4.9.5" }, "optionalPeers": ["typescript"] }, "sha512-kcZ6+W5QzcJ3P1Mt+83OUv/oHFqZHIx8DuxG6eZ5RGMERoLqp4BuGjhHLYGK+Kf5XVkQvqBSmAy/nGWN3qDgEA=="],
+
+ "fork-ts-checker-webpack-plugin/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
+
+ "form-data/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
+
+ "glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
+
+ "log-symbols/is-unicode-supported": ["[email protected]", "", {}, "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ=="],
+
+ "micromatch/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
+
+ "multer/type-is": ["[email protected]", "", { "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" } }, "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g=="],
+
+ "nestjs-trpc/rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg=="],
+
+ "next/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="],
+
+ "npm-run-path/path-key": ["[email protected]", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],
+
+ "onetime/mimic-fn": ["[email protected]", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="],
+
+ "path-scurry/lru-cache": ["[email protected]", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="],
+
+ "pg-types/postgres-array": ["[email protected]", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
+
+ "prompts/kleur": ["[email protected]", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="],
+
+ "prop-types/react-is": ["[email protected]", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
+
+ "proper-lockfile/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "radix-ui/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
+
+ "radix-ui/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+
+ "restore-cursor/onetime": ["[email protected]", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="],
+
+ "schema-utils/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
+
+ "shadcn/commander": ["[email protected]", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="],
+
+ "shadcn/open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.4.0", "define-lazy-prop": "^3.0.0", "is-in-ssh": "^1.0.0", "is-inside-container": "^1.0.0", "powershell-utils": "^0.1.0", "wsl-utils": "^0.3.0" } }, "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw=="],
+
+ "shadcn/zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
+
+ "terser/commander": ["[email protected]", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="],
+
+ "terser-webpack-plugin/schema-utils": ["[email protected]", "", { "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", "ajv-formats": "^2.1.1", "ajv-keywords": "^5.1.0" } }, "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA=="],
+
+ "tsconfig-paths-webpack-plugin/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
+
+ "type-is/content-type": ["[email protected]", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
+
+ "webpack/schema-utils": ["[email protected]", "", { "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", "ajv-formats": "^2.1.1", "ajv-keywords": "^5.1.0" } }, "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA=="],
+
+ "wrap-ansi/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
+ "wrap-ansi/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "yargs/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
+ "@angular-devkit/schematics/ora/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
+
+ "@angular-devkit/schematics/ora/cli-cursor": ["[email protected]", "", { "dependencies": { "restore-cursor": "^3.1.0" } }, "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw=="],
+
+ "@angular-devkit/schematics/ora/is-interactive": ["[email protected]", "", {}, "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w=="],
+
+ "@angular-devkit/schematics/ora/is-unicode-supported": ["[email protected]", "", {}, "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw=="],
+
+ "@angular-devkit/schematics/ora/log-symbols": ["[email protected]", "", { "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" } }, "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg=="],
+
+ "@angular-devkit/schematics/ora/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "@better-auth/cli/better-auth/@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="],
+
+ "@better-auth/cli/better-auth/better-call": ["[email protected]", "", { "dependencies": { "@better-auth/utils": "^0.3.0", "@better-fetch/fetch": "^1.1.4", "rou3": "^0.7.10", "set-cookie-parser": "^2.7.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-XMQ2rs6FNXasGNfMjzbyroSwKwYbZ/T3IxruSS6U2MJRsSYh3wYtG3o6H00ZlKZ/C/UPOAD97tqgQJNsxyeTXw=="],
+
+ "@better-auth/cli/better-auth/kysely": ["[email protected]", "", {}, "sha512-nbD8lB9EB3wNdMhOCdx5Li8DxnLbvKByylRLcJ1h+4SkrowVeECAyZlyiKMThF7xFdRz0jSQ2MoJr+wXux2y0Q=="],
+
+ "@better-auth/core/better-call/@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g=="],
+
+ "@better-auth/core/better-call/set-cookie-parser": ["[email protected]", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="],
+
+ "@dotenvx/dotenvx/execa/get-stream": ["[email protected]", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="],
+
+ "@dotenvx/dotenvx/execa/human-signals": ["[email protected]", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="],
+
+ "@dotenvx/dotenvx/execa/is-stream": ["[email protected]", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
+
+ "@dotenvx/dotenvx/execa/npm-run-path": ["[email protected]", "", { "dependencies": { "path-key": "^3.0.0" } }, "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw=="],
+
+ "@dotenvx/dotenvx/execa/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "@dotenvx/dotenvx/execa/strip-final-newline": ["[email protected]", "", {}, "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="],
+
+ "@dotenvx/dotenvx/open/define-lazy-prop": ["[email protected]", "", {}, "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="],
+
+ "@dotenvx/dotenvx/open/is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="],
+
+ "@dotenvx/dotenvx/open/is-wsl": ["[email protected]", "", { "dependencies": { "is-docker": "^2.0.0" } }, "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww=="],
+
+ "@inquirer/core/wrap-ansi/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
+ "@inquirer/core/wrap-ansi/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "@nestjs/cli/ora/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
+
+ "@nestjs/cli/ora/cli-cursor": ["[email protected]", "", { "dependencies": { "restore-cursor": "^3.1.0" } }, "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw=="],
+
+ "@nestjs/cli/ora/is-interactive": ["[email protected]", "", {}, "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w=="],
+
+ "@nestjs/cli/ora/is-unicode-supported": ["[email protected]", "", {}, "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw=="],
+
+ "@nestjs/cli/ora/log-symbols": ["[email protected]", "", { "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" } }, "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg=="],
+
+ "@nestjs/cli/ora/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "@nestjs/schematics/@angular-devkit/core/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
+
+ "@nestjs/schematics/@angular-devkit/core/rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg=="],
+
+ "@nestjs/schematics/@angular-devkit/core/source-map": ["[email protected]", "", {}, "sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA=="],
+
+ "@nestjs/schematics/@angular-devkit/schematics/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0" } }, "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA=="],
+
+ "@nestjs/schematics/@angular-devkit/schematics/ora": ["[email protected]", "", { "dependencies": { "bl": "^4.1.0", "chalk": "^4.1.0", "cli-cursor": "^3.1.0", "cli-spinners": "^2.5.0", "is-interactive": "^1.0.0", "is-unicode-supported": "^0.1.0", "log-symbols": "^4.1.0", "strip-ansi": "^6.0.0", "wcwidth": "^1.0.1" } }, "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ=="],
+
+ "@nestjs/schematics/@angular-devkit/schematics/rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg=="],
+
+ "@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/primitive": ["@radix-ui/[email protected]", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
+
+ "@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-use-controllable-state": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="],
+
+ "@ts-morph/common/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="],
+
+ "ajv-keywords/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
+
+ "app/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
+
+ "c12/chokidar/readdirp": ["[email protected]", "", {}, "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ=="],
+
+ "cli-table3/string-width/emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "cli-table3/string-width/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "cliui/string-width/emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "cliui/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "concurrently/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+
+ "cross-spawn/which/isexe": ["[email protected]", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
+
+ "enquirer/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "fork-ts-checker-webpack-plugin/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+
+ "form-data/mime-types/mime-db": ["[email protected]", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
+
+ "glob/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="],
+
+ "multer/type-is/media-typer": ["[email protected]", "", {}, "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ=="],
+
+ "multer/type-is/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
+
+ "schema-utils/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
+
+ "shadcn/open/wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg=="],
+
+ "terser-webpack-plugin/schema-utils/ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="],
+
+ "terser-webpack-plugin/schema-utils/ajv-keywords": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="],
+
+ "tsconfig-paths-webpack-plugin/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+
+ "webpack/schema-utils/ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="],
+
+ "webpack/schema-utils/ajv-keywords": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="],
+
+ "wrap-ansi/string-width/emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "wrap-ansi/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "yargs/string-width/emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "yargs/string-width/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "@angular-devkit/schematics/ora/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+
+ "@angular-devkit/schematics/ora/cli-cursor/restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA=="],
+
+ "@angular-devkit/schematics/ora/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "@better-auth/cli/better-auth/better-call/@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g=="],
+
+ "@better-auth/cli/better-auth/better-call/set-cookie-parser": ["[email protected]", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="],
+
+ "@inquirer/core/wrap-ansi/string-width/emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "@inquirer/core/wrap-ansi/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "@nestjs/cli/ora/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+
+ "@nestjs/cli/ora/cli-cursor/restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA=="],
+
+ "@nestjs/cli/ora/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
- "web": ["web@workspace:apps/web"],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
- "which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/cli-cursor": ["[email protected]", "", { "dependencies": { "restore-cursor": "^3.1.0" } }, "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw=="],
- "which-boxed-primitive": ["[email protected]", "", { "dependencies": { "is-bigint": "^1.1.0", "is-boolean-object": "^1.2.1", "is-number-object": "^1.1.1", "is-string": "^1.1.1", "is-symbol": "^1.1.1" } }, "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/is-interactive": ["[email protected]", "", {}, "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w=="],
- "which-builtin-type": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "function.prototype.name": "^1.1.6", "has-tostringtag": "^1.0.2", "is-async-function": "^2.0.0", "is-date-object": "^1.1.0", "is-finalizationregistry": "^1.1.0", "is-generator-function": "^1.0.10", "is-regex": "^1.2.1", "is-weakref": "^1.0.2", "isarray": "^2.0.5", "which-boxed-primitive": "^1.1.0", "which-collection": "^1.0.2", "which-typed-array": "^1.1.16" } }, "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/is-unicode-supported": ["[email protected]", "", {}, "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw=="],
- "which-collection": ["[email protected]", "", { "dependencies": { "is-map": "^2.0.3", "is-set": "^2.0.3", "is-weakmap": "^2.0.2", "is-weakset": "^2.0.3" } }, "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/log-symbols": ["[email protected]", "", { "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" } }, "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg=="],
- "which-typed-array": ["[email protected]", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.9", "call-bound": "^1.0.4", "for-each": "^0.3.5", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" } }, "sha512-fvO4ExWMFsqyhG3AiPAObMuY1lxaqgYcxbc49CNdWDDECOJNgQyvsOWVwbZc+qf3rzRtxojBK+CMEv0Ld5CYpw=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
- "word-wrap": ["[email protected]", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
+ "@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="],
- "yocto-queue": ["[email protected]", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
+ "@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],
- "@eslint-community/eslint-utils/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
+ "@ts-morph/common/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
- "@eslint/eslintrc/globals": ["[email protected]", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],
+ "cli-table3/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
- "@typescript-eslint/eslint-plugin/ignore": ["[email protected]", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="],
+ "glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
- "@typescript-eslint/typescript-estree/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
+ "multer/type-is/mime-types/mime-db": ["[email protected]", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
- "@typescript-eslint/typescript-estree/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+ "yargs/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
- "@typescript-eslint/visitor-keys/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],
+ "@angular-devkit/schematics/ora/cli-cursor/restore-cursor/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
- "fast-glob/glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
+ "@nestjs/cli/ora/cli-cursor/restore-cursor/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
- "sharp/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
- "tinyglobby/picomatch": ["[email protected]", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/cli-cursor/restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA=="],
- "@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
- "@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
+ "@nestjs/schematics/@angular-devkit/schematics/ora/cli-cursor/restore-cursor/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
}
}
diff --git a/docs/api.md b/docs/api.md
new file mode 100644
index 00000000..51a2f0c2
--- /dev/null
+++ b/docs/api.md
@@ -0,0 +1,95 @@
+
+# API Rules - Always review when working on our API
+
+## Logging: use the Nest logger, attach fields, never `console.log`
+
+Logging lives in `apps/api/src/logging`. `ContextLogger` extends Nest's
+`ConsoleLogger` and is installed in `main.ts`, so `new Logger(Thing.name)`
+anywhere in the app picks it up. **Format and level are not configurable** —
+they follow `NODE_ENV`: JSON at `log` and above in production, colourised with
+`debug`/`verbose` locally.
+
+- **Attach data as one object, not extra arguments.** Nest prints one line per
+ argument, so `logger.log("Saved", { userId })` emits two lines. Write
+ `logger.log({ message: "Saved", userId })` instead — the fields are hoisted to
+ the top level in JSON and rendered after the text in development.
+- **Errors pass the stack as the second argument**:
+ `logger.error({ message: "…" }, error instanceof Error ? error.stack : String(error))`.
+ Handing Nest the error object instead prints it as a second message and drops
+ the trace.
+- **Every request carries a `requestId`**, generated (or taken from an inbound
+ `x-request-id`) by `RequestLoggerMiddleware`, returned on the response header,
+ included in error bodies, and stored in `AsyncLocalStorage` so every log line
+ during that request is correlated. `UserContextInterceptor` adds `userId` once
+ the auth guard has resolved the session.
+- **Better Auth routes are logged through its `middleware` option**
+ (`BetterAuthModule.forRoot({ auth, middleware: logAuthRoute })`). It mounts its
+ handler straight onto the HTTP adapter during module configuration, before
+ Nest applies anything from `MiddlewareConsumer`, so `/api/auth/*` would
+ otherwise never reach the middleware. `LoggingModule` must stay **first** in
+ `AppModule`'s imports for the same reason.
+- **Never log headers, query strings, or request bodies.** They routinely carry
+ session cookies and personal data. Log the specific fields a handler knows are
+ safe.
+- **Prisma statement logging is opt-in** via `PRISMA_LOG_QUERIES=true`, and is
+ emitted at `debug`. It is off by default because it buries every other line
+ under a wall of `SELECT`s. Bound parameters are dropped even when it is on.
+ Prisma warnings and errors always flow through the app logger via
+ `PrismaLogBridge`; outside the API (seeds, scripts, the Next.js app) they fall
+ back to the console sink in `packages/db/src/client.ts`.
+
+## There are no organizations
+
+This is an internal tool behind Google sign-in, and it is **single tenant**.
+There is no `Organization` model, no `x-organization-slug` header, no org
+context interceptor, and no org-scoped cache keys. "Signed in" is the entire
+authorisation model.
+
+If you are porting something from the Comp AI MVP, delete the org plumbing
+rather than stubbing it — an `organizationId` that is always the same value is
+a column, an index and a `where` clause that buy nothing, and a permissions
+check that always returns `true` reads like a real one at review time.
+
+## tRPC is the data surface; REST is for auth and health
+
+Everything the app reads or writes goes through `nestjs-trpc` routers under
+`/api/trpc`, wired in `apps/api/src/trpc`. The remaining REST controllers are
+`/api/auth/*` (Better Auth) and `/health`.
+
+- **One router per module**, named `*.router.ts` so the codegen glob finds it,
+ carrying `@Router({ alias: "…" })` and `@UseMiddlewares(AuthMiddleware)`.
+ A router with no `AuthMiddleware` is public — there is no other guard.
+- **Routers are thin.** They validate input with zod and call a service; the
+ Prisma work lives in `*.service.ts`, which is also where a REST controller or
+ a background job would call in.
+- **Services throw Nest's `HttpException` family** (`NotFoundException`,
+ `BadRequestException`, …). `DomainErrorMiddleware` maps those onto tRPC error
+ codes, so a service does not need to know it is being called over tRPC.
+- **Filtering, sorting and pagination happen in Prisma.** List procedures take
+ the shared `listInput` (`apps/api/src/trpc/list-input.ts`) and return
+ `{ rows, total, facetCounts }`. Never return a whole table and filter in the
+ browser, and never interpolate `sort` into a Prisma field name — resolve it
+ through `resolveOrderBy` against the columns that module allows.
+- **The router type is generated**, not hand-written:
+ `bun run --filter=api trpc:generate` writes `src/generated/server.ts`, which
+ the app imports as `type { AppRouter } from "api/app-router"`. `bun run dev`
+ keeps it in watch mode. If the app cannot see a new procedure, the generator
+ has not run.
+
+## Freshness: invalidate the query, don't disable the cache
+
+There is no HTTP response cache in front of tRPC. Freshness is TanStack Query's
+job: a mutation invalidates the query keys it affected, and the list refetches.
+
+- **Invalidate on the client, in the mutation's `onSuccess`**, using the
+ `queryKey` from `trpc.<router>.<procedure>.queryKey()` — invalidate the
+ narrowest key that covers what changed.
+- **`cache-manager` is still there** (`apps/api/src/cache`, Redis when
+ `REDIS_URL` is set) but it is used deliberately, per value, by services that
+ want it — `AuthService.getProfile` is the model: read through, write on miss,
+ and an explicit `invalidateProfile` on change. It is not a global interceptor,
+ so nothing is cached unless a service asks for it.
+- **Background writes the browser cannot see** — enrichment finishing, most
+ obviously — are not invalidations at all, because no client action caused
+ them. Poll for those: `refetchInterval` while the record's status is
+ `PENDING`/`RUNNING`, and stop once it settles.
diff --git a/docs/crm-plan.md b/docs/crm-plan.md
new file mode 100644
index 00000000..0b579a48
--- /dev/null
+++ b/docs/crm-plan.md
@@ -0,0 +1,1368 @@
+# Plan — Agentic CRM (HubSpot replacement)
+
+A lightweight, opinionated CRM for our sales team. Companies are the top-level
+object; Contacts and Deals hang off them; everything that happens is an
+**Activity** on a timeline. Company knowledge is filled in by an agent using
+[Context.dev](https://docs.context.dev) rather than typed by a human.
+
+This is the build plan: decisions, data model, contracts, conventions and
+phased delivery. Read it with [`AGENTS.md`](../AGENTS.md),
+[`design.md`](./design.md) and [`api.md`](./api.md).
+
+---
+
+## 1. The decisions that stop this becoming a nightmare
+
+Five choices carry the whole design. Everything else follows from them.
+
+1. **Core fields are real columns. Custom fields are one JSONB column.** Not
+ EAV. A table showing eight custom columns must not become eight joins. §5.
+2. **One property registry drives columns, filters, forms and the detail
+ sheet.** System fields and custom fields are described by the *same*
+ metadata, so adding a column to the CRM is a data change, not four code
+ changes. §5.
+3. **Permissions are enforced in the tRPC middleware and again in the service.**
+ The UI hides buttons; it never guards anything. Row-level ownership is a
+ service concern because no statement grammar can express it. §6.
+4. **Sheets, not inner pages.** A row click opens a sheet keyed by a URL param.
+ Back button closes it, links are shareable, and we never build a
+ `/companies/[id]/contacts/[id]/edit` route tree. §10.
+5. **Everything that lists data is the same `DataTable`.** Ported verbatim from
+ `mvp`, driven by nuqs, paginated server-side. §10.
+
+### Choice table
+
+| Decision | Choice | Why |
+| --- | --- | --- |
+| Tenancy | Single tenant, no organizations | Repo is already built this way (`20260731160000_remove_organizations`); internal tool, Google-only sign-in. |
+| Hosting | Both apps on Vercel | §2 — with the serverless consequences handled explicitly, not discovered later. |
+| Data fetching | tRPC end to end, prefetched in RSC | Type-safe Prisma→cell; first paint is already filtered. |
+| Table state | nuqs, server-side page/sort/filter | Shareable URLs; 100k rows stay fast. |
+| Data table | mvp's `DataTable` into `packages/ui` | `design.md` makes `/packages/ui` the source of truth; `simple-table` and `card-table` already live there. |
+| Custom fields | JSONB + `PropertyDefinition` registry | §5. |
+| Associations | Many-to-many, three typed join tables, labels + primary flags | HubSpot parity; a contact really can sit on two accounts. §4. |
+| Lifecycle / lead status | First-class enum columns on Company and Contact | They drive filters and reporting; HubSpot parity. §4. |
+| Last activity date | Denormalised `lastActivityAt` column, written with the activity | It's a sortable column on every list; a subquery per row would be the slowest thing here. §4. |
+| Saved views | `SavedView` row storing a serialised query string | Falls out of URL-as-state for almost nothing. §11. |
+| RBAC | Better Auth `admin` plugin + `createAccessControl` | §6. No orgs, so the org plugin's role model doesn't apply. |
+| Attachments | Vercel Blob, client uploads, presigned reads | §7. |
+| Speed | Redis for sessions, property defs and aggregates + RSC prefetch | §8. |
+| Forms | `react-hook-form` + `zodResolver` + `@crm/ui` Field primitives | §11 — matches mvp exactly. |
+| Effects | Banned, lint-enforced, `useMountEffect` escape hatch | §12. |
+| Comments | None in new code | §12. |
+
+### Judgment calls worth your veto
+
+- **`UNQUALIFIED_TO_BUY` is terminal, not linear.** You listed it between two
+ active stages, but it's a disqualification. Treated like `CLOSED_LOST`:
+ excluded from pipeline value and forecast, shown under a Closed tab. Say the
+ word if you want it mid-funnel.
+- **Reps read everything, write only what they own.** Sales teams need
+ visibility; letting anyone edit anyone's deal is how data rots. Activities are
+ the exception — anyone can log an activity against any record.
+- **`Company.domain` and `Contact.email` are unique.** Duplicates are the #1
+ way a CRM rots, and it makes the HubSpot import idempotent. Cost: two people
+ behind one `info@` need separate records.
+- **Not everything is a custom property.** The sales-critical fields are real
+ columns with real constraints. Custom properties exist for the team's own
+ additions. Making everything dynamic is the Salesforce trap.
+- **Many-to-many associations everywhere, with labels and primary flags.** Your
+ call, over my earlier suggestion to flatten them. It costs a join on every
+ company column and turns the company timeline into a union (§4) — both
+ handled, neither free. In exchange the model matches how you actually sell,
+ and we never hit the wall where a contact genuinely sits on two accounts.
+- **No Tickets, Quotes, Subscriptions, Payments, Orders or Payment links.** The
+ record sidebars in your screenshots are mostly empty `(0)` cards. Rebuilding
+ those is rebuilding HubSpot. §15.
+
+### Repo issues found while surveying
+
+- **`docs/review.md` does not exist** but `AGENTS.md` says "Always review" it.
+ Every agent session currently starts by failing to read a required file.
+- **`docs/api.md` describes a multi-tenant world this repo doesn't have.** The
+ org-context and per-org cache-generation sections came from the MVP; there are
+ no organizations here. The logging rules apply verbatim and must stay. Trim
+ the rest in Phase 0.
+- `apps/app/make-session.tmp.ts` is a stray scratch file.
+- The existing codebase is heavily commented. The no-comments rule applies to
+ new code; existing comments are left alone rather than churned.
+
+---
+
+## 2. Hosting on Vercel, and what it costs us
+
+Vercel is a serverless platform. Three things about this stack break there if
+we don't design for them, and all three are cheap to handle now and expensive
+to retrofit.
+
+**The API runtime changes from Bun to Node.** `apps/api` currently builds with
+`bun build --target=bun` and runs `bun src/main.ts`. Vercel has no Bun runtime.
+NestJS deploys as a single Node serverless function via `@vercel/node`, with a
+cached bootstrap so warm invocations reuse the Nest app:
+
+```ts
+let cached: Promise<INestApplication> | null = null;
+
+export default async function handler(req: IncomingMessage, res: ServerResponse) {
+ cached ??= bootstrap();
+ const app = await cached;
+ app.getHttpAdapter().getInstance()(req, res);
+}
+```
+
+Keep the Bun scripts for local dev; add Node build/start scripts for Vercel.
+`bun test` stays as-is for local test runs.
+
+**Fire-and-forget dies on serverless.** The function freezes once the response
+is sent, so `void this.enrichment.enqueue(id)` silently never finishes. Use
+`waitUntil` from `@vercel/functions` — the same primitive mvp already relies on
+per `docs/api.md`. Enrichment is a ~7–18s Context.dev call, comfortably inside
+the function budget. When volume outgrows it, move to a durable queue; the
+`EnrichmentService` interface stays the same either way, which is the point of
+putting it behind a service in the first place.
+
+**Postgres connections exhaust.** Every concurrent invocation is a new client.
+Use a pooled connection string for the app and a direct one for migrations:
+
+```
+DATABASE_URL="postgres://...pooler...?pgbouncer=true&connection_limit=1"
+DIRECT_URL="postgres://...direct..."
+```
+
+with `directUrl` in the Prisma datasource. Neon or Supabase both give you this;
+so does Prisma Accelerate. Getting this wrong produces "too many connections"
+under load and nothing before it.
+
+**Redis must be serverless-friendly.** Provision Upstash through the Vercel
+Marketplace. `@keyv/redis` (already a dependency) speaks the Redis protocol,
+which Upstash supports over TLS; Fluid Compute keeps the connection alive
+across invocations.
+
+### Deployment shape
+
+Two Vercel projects from one repo: `crm-app` (root `apps/app`) and `crm-api`
+(root `apps/api`). Turborepo remote caching on. `apps/app` rewrites `/api/*` to
+the API deployment, so the browser stays same-origin and the session cookie
+just works.
+
+---
+
+## 3. Architecture
+
+```
+browser
+ │ same-origin /api/trpc
+ ▼
+apps/app (Next.js 16, RSC) Vercel project crm-app
+ ├─ app/api/[...path]/route.ts ──proxy──▶ crm-api
+ ├─ server components: getServerTrpc() → prefetch → HydrationBoundary
+ └─ client: useTRPC() + TanStack Query, nuqs for all table + sheet state
+ │
+apps/api (NestJS, Node function) ▼ Vercel project crm-api
+ ├─ /api/trpc routers: companies contacts deals activities
+ │ properties attachments users dashboard
+ ├─ /api/auth/* Better Auth (Google) + admin plugin (RBAC)
+ ├─ /api/blob/upload client-upload token handshake
+ ├─ services Prisma, property validation, ownership guards
+ └─ enrichment Context.dev via waitUntil
+ │ │ │
+ Postgres (pooled) Redis (Upstash) Vercel Blob
+ packages/db sessions, defs, attachments
+ aggregates
+```
+
+### Dependencies to add
+
+| Package | Where | Version |
+| --- | --- | --- |
+| `@trpc/server`, `zod` | `apps/api` | `^11.18.0`, `^4.4.3` |
+| `@trpc/client`, `@trpc/server`, `@trpc/tanstack-react-query` | `apps/app` | `^11.18.0` |
+| `@tanstack/react-query`, `@tanstack/react-query-devtools` | `apps/app` | `^5.101.2` |
+| `nuqs` | `apps/app`, `packages/ui` | `^2.8.9` |
+| `zod`, `@hookform/resolvers` | `apps/app` | `^4.4.3`, latest |
+| `@vercel/blob`, `@vercel/functions` | `apps/api`, `apps/app` | latest |
+| `keyv`, `@keyv/redis` | `packages/auth` | matching `apps/api` |
+| `context.dev` | `apps/api` | latest |
+
+`nestjs-trpc@^2.13.0`, `@keyv/redis`, `cache-manager`, `react-hook-form` and
+`better-auth@^1.6.25` are already present.
+
+---
+
+## 4. Core data model
+
+Auth models are owned by Better Auth and regenerated by `bun run auth:generate`
+— never hand-edited. `User` gains only back-relations (`CompanyOwner`,
+`ContactOwner`, `DealOwner`, `ActivityAuthor`, `AttachmentUploader`,
+`SavedViewAuthor`) plus the `admin` plugin's fields (§6).
+
+`SavedView` below references `PropertyEntity`, which is declared in §5 — Prisma
+schemas are order-independent, so the split across sections is presentational
+only. It is all one `schema.prisma`.
+
+```prisma
+enum DealStage {
+ DEMO_BOOKED
+ QUALIFIED_TO_BUY
+ UNQUALIFIED_TO_BUY
+ DECISION_MAKER_BOUGHT_IN
+ CONTRACT_SENT
+ CLOSED_WON
+ CLOSED_LOST
+}
+
+enum LifecycleStage {
+ SUBSCRIBER
+ LEAD
+ MARKETING_QUALIFIED_LEAD
+ SALES_QUALIFIED_LEAD
+ OPPORTUNITY
+ CUSTOMER
+ EVANGELIST
+ OTHER
+}
+
+enum LeadStatus {
+ NEW
+ OPEN
+ IN_PROGRESS
+ OPEN_DEAL
+ UNQUALIFIED
+ ATTEMPTED_TO_CONTACT
+ CONNECTED
+ BAD_TIMING
+}
+
+enum ForecastCategory {
+ PIPELINE
+ BEST_CASE
+ COMMIT
+ CLOSED
+ OMITTED
+}
+
+enum RecordSource {
+ MANUAL
+ IMPORT
+ ENRICHMENT
+ API
+}
+
+enum ActivityType {
+ NOTE
+ CALL
+ EMAIL
+ MEETING
+ TASK
+ STAGE_CHANGE
+ LIFECYCLE_CHANGE
+ ENRICHMENT
+}
+
+enum EnrichmentStatus { PENDING RUNNING COMPLETE FAILED SKIPPED }
+
+model Company {
+ id String @id @default(cuid())
+ name String
+ domain String? @unique
+ website String?
+ description String?
+
+ logoUrl String?
+ logoDarkUrl String?
+ iconUrl String?
+ brandColor String?
+
+ industry String?
+ subIndustry String?
+ streetAddress String?
+ streetAddress2 String?
+ city String?
+ stateCode String?
+ postalCode String?
+ country String?
+ countryCode String?
+
+ phone String?
+ email String?
+ linkedinUrl String?
+ twitterUrl String?
+ githubUrl String?
+ pricingUrl String?
+ careersUrl String?
+
+ lifecycleStage LifecycleStage @default(LEAD)
+ lifecycleStageChangedAt DateTime @default(now())
+ leadStatus LeadStatus?
+ recordSource RecordSource @default(MANUAL)
+ lastActivityAt DateTime?
+
+ ownerId String?
+ owner User? @relation("CompanyOwner", fields: [ownerId], references: [id], onDelete: SetNull)
+
+ enrichmentStatus EnrichmentStatus @default(PENDING)
+ enrichedAt DateTime?
+ enrichmentError String?
+ enrichment CompanyEnrichment?
+
+ customFields Json @default("{}")
+
+ contacts CompanyContact[]
+ deals CompanyDeal[]
+ activities Activity[]
+ attachments Attachment[]
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([ownerId])
+ @@index([name])
+ @@index([lifecycleStage])
+ @@index([lastActivityAt])
+ @@index([createdAt])
+ @@index([customFields], type: Gin)
+ @@map("company")
+}
+
+model CompanyEnrichment {
+ companyId String @id
+ company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ source String @default("context.dev")
+ raw Json
+ fetchedAt DateTime @default(now())
+
+ @@map("companyEnrichment")
+}
+
+model Contact {
+ id String @id @default(cuid())
+ firstName String
+ lastName String?
+ email String? @unique
+ phone String?
+ title String?
+ linkedinUrl String?
+
+ lifecycleStage LifecycleStage @default(LEAD)
+ lifecycleStageChangedAt DateTime @default(now())
+ leadStatus LeadStatus?
+ buyingRole String?
+ recordSource RecordSource @default(MANUAL)
+ lastActivityAt DateTime?
+
+ ownerId String?
+ owner User? @relation("ContactOwner", fields: [ownerId], references: [id], onDelete: SetNull)
+
+ customFields Json @default("{}")
+
+ companies CompanyContact[]
+ deals DealContact[]
+ activities Activity[]
+ attachments Attachment[]
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([ownerId])
+ @@index([lifecycleStage])
+ @@index([leadStatus])
+ @@index([lastActivityAt])
+ @@index([createdAt])
+ @@index([customFields], type: Gin)
+ @@map("contact")
+}
+
+model Deal {
+ id String @id @default(cuid())
+ name String
+ ownerId String
+ owner User @relation("DealOwner", fields: [ownerId], references: [id])
+
+ stage DealStage @default(DEMO_BOOKED)
+ stageChangedAt DateTime @default(now())
+ forecastCategory ForecastCategory @default(PIPELINE)
+ amount Decimal? @db.Decimal(14, 2)
+ currency String @default("USD")
+ expectedCloseDate DateTime?
+ closedAt DateTime?
+ closedReason String?
+ recordSource RecordSource @default(MANUAL)
+ lastActivityAt DateTime?
+
+ customFields Json @default("{}")
+
+ companies CompanyDeal[]
+ contacts DealContact[]
+ activities Activity[]
+ attachments Attachment[]
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([ownerId])
+ @@index([stage])
+ @@index([expectedCloseDate])
+ @@index([lastActivityAt])
+ @@index([createdAt])
+ @@index([customFields], type: Gin)
+ @@map("deal")
+}
+
+enum AssociationPairing {
+ COMPANY_CONTACT
+ COMPANY_DEAL
+ DEAL_CONTACT
+}
+
+model CompanyContact {
+ companyId String
+ company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ contactId String
+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
+
+ isPrimaryCompany Boolean @default(false)
+ isPrimaryContact Boolean @default(false)
+ label String?
+
+ createdAt DateTime @default(now())
+
+ @@id([companyId, contactId])
+ @@index([contactId])
+ @@map("companyContact")
+}
+
+model CompanyDeal {
+ companyId String
+ company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ dealId String
+ deal Deal @relation(fields: [dealId], references: [id], onDelete: Cascade)
+
+ isPrimaryCompany Boolean @default(false)
+ label String?
+
+ createdAt DateTime @default(now())
+
+ @@id([companyId, dealId])
+ @@index([dealId])
+ @@map("companyDeal")
+}
+
+model DealContact {
+ dealId String
+ deal Deal @relation(fields: [dealId], references: [id], onDelete: Cascade)
+ contactId String
+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
+
+ isPrimaryContact Boolean @default(false)
+ label String?
+
+ createdAt DateTime @default(now())
+
+ @@id([dealId, contactId])
+ @@index([contactId])
+ @@map("dealContact")
+}
+
+model AssociationLabel {
+ id String @id @default(cuid())
+ pairing AssociationPairing
+ value String
+ label String
+ order Int @default(0)
+
+ @@unique([pairing, value])
+ @@map("associationLabel")
+}
+
+model Activity {
+ id String @id @default(cuid())
+ type ActivityType
+ subject String?
+ body String?
+
+ occurredAt DateTime?
+ dueAt DateTime?
+ completedAt DateTime?
+
+ companyId String?
+ company Company? @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ dealId String?
+ deal Deal? @relation(fields: [dealId], references: [id], onDelete: Cascade)
+
+ createdById String
+ createdBy User @relation("ActivityAuthor", fields: [createdById], references: [id])
+ meta Json?
+
+ attachments Attachment[]
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([companyId, createdAt])
+ @@index([dealId, createdAt])
+ @@index([contactId, createdAt])
+ @@index([dueAt])
+ @@map("activity")
+}
+
+model SavedView {
+ id String @id @default(cuid())
+ entity PropertyEntity
+ name String
+ search String
+ shared Boolean @default(false)
+ order Int @default(0)
+
+ createdById String
+ createdBy User @relation("SavedViewAuthor", fields: [createdById], references: [id], onDelete: Cascade)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([entity, createdById])
+ @@map("savedView")
+}
+```
+
+**`Activity.companyId` is denormalised, and many-to-many complicates it.** It is
+stamped with the *primary* company of whatever the activity hangs off, so the
+common case — one company, one timeline — stays a single indexed range scan.
+
+But under M2M an activity on a deal shared by two companies belongs on both
+timelines, and one stamped column cannot say that. The company timeline is
+therefore a union:
+
+```sql
+WHERE "companyId" = $1
+ OR "dealId" IN (SELECT "dealId" FROM "companyDeal" WHERE "companyId" = $1)
+ OR "contactId" IN (SELECT "contactId" FROM "companyContact" WHERE "companyId" = $1)
+```
+
+Every branch is indexed, and a company with a few hundred associated records
+resolves in single-digit milliseconds. The denormalised column still earns its
+place: it keeps the overwhelmingly common single-company read on one index, and
+it is what `lastActivityAt` propagation walks.
+
+If a company ever accumulates thousands of associated records, the fix is an
+`ActivityCompany` fan-out table written alongside the activity. Do not build it
+now — measure first. Noting it here so the upgrade path is deliberate rather
+than a rewrite.
+
+**`lastActivityAt` is denormalised too, and this one is not optional.** Your
+HubSpot screenshots show *Last activity date* as a visible, sortable column on
+every list and in every record's Data highlights. Computed as a correlated
+`MAX(activity.createdAt)` subquery it would run once per row per page — the
+single easiest way to make this CRM feel slow. It is a real indexed column,
+written by the same service method that writes the activity, and backfilled by
+the seed. Same argument for the `createdAt` indexes: *Create date* is the
+default sort on the companies list.
+
+**Lifecycle stage and lead status are first-class, not custom.** Both objects
+carry `lifecycleStage`; contacts and companies carry `leadStatus`. They drive
+filters, pipeline reporting and the Data highlights strip, so they get enum
+columns with indexes rather than JSONB. Changing either writes a
+`LIFECYCLE_CHANGE` activity and stamps `lifecycleStageChangedAt`, which is what
+lets the record header say "Customer for 21 hours" and offer history — the
+timeline *is* the history, so there is no second audit table to keep in sync.
+
+**Associations are many-to-many by default**, matching HubSpot — a contact can
+sit on several companies, a deal can span several, and a deal has as many
+contacts as it has humans in the room. This was your call over my earlier
+recommendation, and it is the right one for a company selling to groups and
+subsidiaries; the rest of this section is what it takes to do it without
+paying for it later.
+
+**Three typed join tables, not one polymorphic edge table.** A generic
+`Association { fromType, fromId, toType, toId }` looks tempting and is the same
+mistake as EAV, one level up: no foreign keys, no cascade deletes, no Prisma
+relations, and every query hand-written. There are exactly three pairings, that
+number is bounded, so `CompanyContact`, `CompanyDeal` and `DealContact` each get
+real columns and real integrity.
+
+**There are two independent notions of "primary", and conflating them is a
+bug.** HubSpot only models the first:
+
+- `isPrimaryCompany` — *this contact's* (or *this deal's*) main company. Drives
+ the Primary badge and the "Company" column on list views.
+- `isPrimaryContact` — *this company's* main point of contact, which you asked
+ for in the original brief. Same for a deal's lead contact.
+
+They point in opposite directions across the same row, so `CompanyContact`
+carries both flags.
+
+**Postgres enforces one primary per side; the application does not.** Prisma
+cannot express partial unique indexes, so these go in a hand-written migration
+and are not optional — "two primary companies" is exactly the corruption that
+makes a CRM untrustworthy:
+
+```sql
+CREATE UNIQUE INDEX company_contact_one_primary_company
+ ON "companyContact" ("contactId") WHERE "isPrimaryCompany";
+CREATE UNIQUE INDEX company_contact_one_primary_contact
+ ON "companyContact" ("companyId") WHERE "isPrimaryContact";
+CREATE UNIQUE INDEX company_deal_one_primary_company
+ ON "companyDeal" ("dealId") WHERE "isPrimaryCompany";
+CREATE UNIQUE INDEX deal_contact_one_primary_contact
+ ON "dealContact" ("dealId") WHERE "isPrimaryContact";
+```
+
+Promoting a new primary is a two-statement transaction: demote the old, promote
+the new. The index turns a race into a failed write rather than silent
+duplication.
+
+**`Deal.companyId` was required and is now gone**, so the "every deal belongs to
+a company" invariant moves into the service: creating a deal requires at least
+one company association, and removing the last one is rejected. A schema-level
+`NOT NULL` was doing real work here; losing it means the service has to.
+
+**Association labels are a managed vocabulary**, not free text. `AssociationLabel`
+holds the options per pairing — Decision maker, Champion, Billing contact,
+Parent company — editable in Settings next to custom properties, validated
+server-side on write. Free text would give us four spellings of "champion"
+inside a month.
+
+**What this costs, honestly.** Every list that shows a company column now reads
+through a join filtered to `isPrimaryCompany`, and every per-company count is a
+join count rather than a foreign-key scan. Both are indexed and fine at this
+scale. The real cost is the timeline, below.
+
+**Timeline semantics.** Past = `occurredAt` set, or `completedAt` set, or a
+`NOTE`/`STAGE_CHANGE`/`ENRICHMENT` row using `createdAt`. Upcoming =
+`dueAt > now()` and `completedAt IS NULL`. Overdue = `dueAt < now()` and
+`completedAt IS NULL`.
+
+**Pipeline math.** Open stages are `DEMO_BOOKED`, `QUALIFIED_TO_BUY`,
+`DECISION_MAKER_BOUGHT_IN`, `CONTRACT_SENT`. Closed are `CLOSED_WON`,
+`CLOSED_LOST`, `UNQUALIFIED_TO_BUY`. Pipeline value sums `amount` over open
+stages only. Moving to a closed stage stamps `closedAt` and requires
+`closedReason` on the two losing outcomes.
+
+---
+
+## 5. Custom properties
+
+The part that decides whether this is maintainable in two years.
+
+### Why JSONB and not EAV
+
+An entity-attribute-value table is the textbook answer and the wrong one here.
+Rendering a table with eight custom columns means eight joins or a pivot, on
+every page of every list. Values live in one `customFields` JSONB column on the
+row we already selected: zero extra queries, atomic writes, and a GIN index
+that makes containment filters fast.
+
+The trade — no referential integrity on values — is bought back by validating
+every write against the definition registry server-side.
+
+### The registry
+
+```prisma
+enum PropertyEntity { COMPANY CONTACT DEAL }
+enum PropertySource { SYSTEM CUSTOM }
+
+enum PropertyType {
+ TEXT
+ LONG_TEXT
+ NUMBER
+ CURRENCY
+ DATE
+ BOOLEAN
+ SELECT
+ MULTI_SELECT
+ URL
+ EMAIL
+ PHONE
+ USER
+}
+
+model PropertyDefinition {
+ id String @id @default(cuid())
+ entity PropertyEntity
+ source PropertySource @default(CUSTOM)
+ key String
+ label String
+ type PropertyType
+
+ description String?
+ options Json?
+ required Boolean @default(false)
+ showInTable Boolean @default(false)
+ filterable Boolean @default(true)
+ sortable Boolean @default(false)
+ order Int @default(0)
+
+ archivedAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([entity, key])
+ @@index([entity, archivedAt])
+ @@map("propertyDefinition")
+}
+```
+
+`SYSTEM` rows describe the real columns from §4 — `name`, `domain`, `stage`,
+`amount`, `owner`. They are seeded from a versioned TypeScript constant and
+upserted on boot, never hand-edited, and their `key`/`type` are immutable. Only
+`label`, `showInTable`, `order` are editable on a system row.
+
+`CUSTOM` rows describe keys inside `customFields`.
+
+### Your existing HubSpot custom fields validate the design
+
+The deal record in your screenshots carries *Deal Type*, *Term*, *Deal
+Segment*, *Forecast Context*, *Forecast Context (manual)*, *Competitors
+Mentioned*, *Compliance Frameworks* and *Compliance Timeline*; the company
+carries *VAT ID*, *Record source* and *Frameworks*; the contact carries
+*Buying Role*, *Assessment*, *assessment-source* and the *Original Traffic
+Source* drill-downs. Every one of these is a `CUSTOM` definition in the
+registry — no schema migration, no code change.
+
+Two are worth calling out. *Compliance Frameworks* renders as removable tag
+chips, which is the `MULTI_SELECT` type. And `assesment-source` is misspelled
+in HubSpot today: the import maps it to a correctly-spelled `key` with the old
+name preserved as an alias, so we carry the data across without carrying the
+typo forward forever.
+
+Seed these as part of the migration so day one in the new CRM has the same
+fields the team already uses.
+
+### One registry, four consumers
+
+`properties.list({ entity })` returns both kinds in one array. From it:
+
+| Consumer | Function | Produces |
+| --- | --- | --- |
+| Table | `buildColumns(defs, renderers)` | `DataTableColumn<Row>[]` |
+| Filters | `buildFacets(defs)` | `DataTableFacet[]` for every `SELECT` with `filterable` |
+| Forms | `buildFormSchema(defs)` | the Zod object for the custom section |
+| Detail sheet | `buildProperties(defs, row)` | `DetailSheetProperty` rows |
+
+Adding a property becomes a row in one table. No code change touches four
+files, which is the entire point.
+
+### Rules that keep it safe
+
+- **`key` is immutable after creation.** Renaming the label is free; renaming
+ the key orphans every stored value. The API rejects key changes outright.
+- **Delete is archive.** `archivedAt` hides the property everywhere and leaves
+ the JSONB untouched, so an accidental delete is a one-click restore. Hard
+ purge is a separate, explicit, owner-only action that strips the key from
+ every row in a transaction.
+- **Every write is validated server-side** against a Zod schema compiled from
+ the definitions and cached in Redis, invalidated when a definition changes.
+ Unknown keys are rejected, not silently stored — silent acceptance is how you
+ end up with four spellings of the same field.
+- **Type changes are restricted to safe widenings** (`TEXT`→`LONG_TEXT`,
+ `NUMBER`→`CURRENCY`). Anything else requires archive-and-recreate, so no
+ write can land against a type that no longer matches the stored data.
+- **`USER` type values store a user id** and are resolved through the same
+ owner-picker component as system owner fields.
+
+### Filtering and sorting
+
+Filtering uses Prisma's JSON path filters against the GIN index:
+
+```ts
+where: { customFields: { path: [def.key], equals: value } }
+```
+
+Sorting is the sharp edge: Prisma cannot `orderBy` into a JSON column. The list
+service takes a raw `ORDER BY "customFields" #>> ARRAY[$1]` escape hatch, with
+the key validated against the definition registry before it reaches SQL — an
+allowlist derived from data we control, never the raw query string. Only
+properties flagged `sortable` are offered in the sort menu.
+
+Free-text `q` searches system text columns in v1. Extending it across custom
+text properties wants `pg_trgm`; that is a later, measured change.
+
+---
+
+## 6. Role-based access control
+
+Better Auth's **`admin` plugin** with `createAccessControl`, imported from the
+dedicated paths for tree-shaking. The org plugin's role model does not apply —
+there are no organizations. Roles live on `user.role`.
+
+```ts
+// packages/auth/src/permissions.ts
+import { createAccessControl } from "better-auth/plugins/access";
+import { defaultStatements, adminAc } from "better-auth/plugins/admin/access";
+
+export const statement = {
+ ...defaultStatements,
+ company: ["read", "create", "update", "delete"],
+ contact: ["read", "create", "update", "delete"],
+ deal: ["read", "create", "update", "delete", "reassign"],
+ activity: ["read", "create", "update", "delete"],
+ attachment: ["read", "create", "delete"],
+ property: ["read", "manage"],
+ member: ["read", "manage"],
+} as const;
+
+export const ac = createAccessControl(statement);
+```
+
+| Role | Intent |
+| --- | --- |
+| `owner` | Everything, including user management and hard-purging properties. |
+| `manager` | All records, reassign deals, manage the property schema. No user management. |
+| `rep` | Read everything; create anything; update and delete only records they own. |
+| `readonly` | Read everything. No writes except nothing at all. |
+
+### Three layers, and why each exists
+
+1. **tRPC middleware.** `PermissionsMiddleware` reads
+ `meta: { permissions: { deal: ["update"] } }` off the procedure and checks it
+ against the role — mvp's pattern, minus the org lookup. Coarse-grained, and
+ it catches an entire router that someone forgot to guard.
+2. **Service-level ownership.** No statement grammar expresses "only rows where
+ `ownerId = me`". A shared `assertCanMutate(record, user)` runs inside the
+ service, before the write. This is the layer that actually protects a rep's
+ deal from another rep.
+3. **UI.** `roleCan()` hides buttons a user cannot use. Presentation only.
+ Anything enforced solely here is not enforced.
+
+### Two operational details that bite later
+
+- **Role changes lag the cookie cache.** `session.cookieCache` is on with a
+ 5-minute `maxAge`, and the cached user object carries the role. Revoke the
+ user's sessions when their role changes so the next request re-reads from the
+ database. Otherwise a demotion takes up to five minutes to bite.
+- **Re-run `bun run auth:generate` after adding the plugin.** It adds `role`,
+ `banned`, `banReason`, `banExpires` to `User` and `impersonatedBy` to
+ `Session`. Skipping this produces runtime adapter errors, not type errors.
+
+First Google sign-in bootstraps as `owner` if no users exist; everyone after
+defaults to `rep`, promoted from Settings → Members.
+
+---
+
+## 7. Attachments on Vercel Blob
+
+`vercel blob create-store crm-attachments` writes `BLOB_READ_WRITE_TOKEN` into
+the project. **Not yet created** — see §14.
+
+```prisma
+model Attachment {
+ id String @id @default(cuid())
+ pathname String @unique
+ filename String
+ contentType String
+ size Int
+
+ companyId String?
+ company Company? @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ dealId String?
+ deal Deal? @relation(fields: [dealId], references: [id], onDelete: Cascade)
+ activityId String?
+ activity Activity? @relation(fields: [activityId], references: [id], onDelete: Cascade)
+
+ uploadedById String
+ uploadedBy User @relation("AttachmentUploader", fields: [uploadedById], references: [id])
+ createdAt DateTime @default(now())
+
+ @@index([companyId])
+ @@index([dealId])
+ @@map("attachment")
+}
+```
+
+**Client uploads, not server uploads.** Vercel caps a serverless request body
+at 4.5 MB; a signed contract PDF blows straight through that. Use
+`upload()` from `@vercel/blob/client` against a `handleUpload` route that
+authenticates the session, checks `attachment: ["create"]`, and only then issues
+a token. Server-side `put()` is reserved for small files we generate ourselves.
+
+**Store the pathname, not the URL.** Blob URLs carry an unguessable random
+suffix, which is obscurity, not authorisation — and a CRM holds customer
+contracts. Downloads go through an API route that checks RBAC and then issues a
+presigned URL (the CLI exposes `blob presign` and `blob signed-token`; confirm
+the SDK flag names when implementing). Row payloads never contain a directly
+fetchable URL.
+
+**Deletes are two-phase.** Delete the row, then delete the blob in `waitUntil`.
+A dangling blob costs pennies; a dangling row is a broken download.
+
+The `@crm/ui` `attachment.tsx` component already models the
+idle/uploading/processing/error/done states the upload flow needs.
+
+---
+
+## 8. Speed: Redis and rendering
+
+Three distinct uses of Redis. Conflating them is how caches go stale.
+
+1. **Better Auth secondary storage.** Port mvp's
+ `packages/auth/src/secondary-storage.ts` verbatim. Every RSC render validates
+ a session; on Vercel that is a Postgres round trip per render unless sessions
+ live in Redis. Biggest single win available.
+2. **Application cache** via the existing `AppCacheModule`. Cache the things
+ that are hot and rarely change: property definitions, the user list, and
+ dashboard aggregates. Keys are namespaced `crm:v{gen}:{entity}:{hash}`; a
+ write bumps that entity's generation counter rather than deleting keys.
+3. **Enrichment dedupe.** A short-lived `enrich:lock:{domain}` key stops two
+ concurrent creates of the same domain from both burning 10 credits.
+
+Do **not** cache per-record reads behind Redis in v1. TanStack Query already
+dedupes and caches client-side, and record freshness after a write matters more
+than shaving a query. Cache aggregates and registries; leave records live.
+
+**Rendering.** Every list page prefetches on the server through
+`getServerTrpc()` and hydrates:
+
+```tsx
+const queryClient = getServerQueryClient();
+await queryClient.prefetchQuery(trpc.companies.list.queryOptions(params));
+return (
+ <HydrationBoundary state={dehydrate(queryClient)}>
+ <CompaniesPanel />
+ </HydrationBoundary>
+);
+```
+
+Parsed nuqs values feed the prefetch, so the first paint is already filtered and
+sorted — no loading flash on a shared link. Subsequent filter changes stay
+shallow and are served by TanStack Query.
+
+---
+
+## 9. The agentic layer
+
+`apps/api/src/enrichment/` — a typed `ContextDevClient` over
+`https://api.context.dev/v1` plus an `EnrichmentService` invoked through
+`waitUntil`.
+
+| Trigger | Call | Cost |
+| --- | --- | --- |
+| Company created or given a new `domain` | `POST /brand/retrieve` `{type:"by_domain"}` | 10 credits |
+| Manual re-enrich | same, `maxAgeMs: 0` | 10 credits |
+| Contact created with a work email, no company | `{type:"by_email"}` → find-or-create Company, link as primary | 10 credits |
+| CSV import | `POST /utility/prefetch` per row, then retrieve | prefetch free on paid plan |
+| Research this company | `POST /web/extract` with our schema → `ENRICHMENT` activity | 10 credits |
+
+**Field mapping.** `title`→`name` (only when the record was created domain-first
+and unnamed); `description`/`slogan`→`description`; `logos[]` picked by
+`mode`+`type`, never `logos[0]` — light+`logo`→`logoUrl`, dark+`logo`→
+`logoDarkUrl`, `icon`→`iconUrl`; `colors[0].hex`→`brandColor` (key off `hex`,
+the name is generated); `industries.eic[0]`→`industry`/`subIndustry`;
+`address`→`city`/`stateCode`/`country`/`countryCode`; `socials[]`→ the social
+URLs by `type`; `links`→`pricingUrl`/`careersUrl`. Whole payload →
+`CompanyEnrichment.raw`, so re-deriving a field never costs credits again.
+
+**Error handling.** Every field is nullable — never overwrite a human-entered
+value with `null`. `400 NOT_FOUND` and `WEBSITE_ACCESS_ERROR` are `SKIPPED`, not
+`FAILED`, and are not billed. `422` on an email lookup (free or disposable) is
+`SKIPPED` with no company created. `403` on prefetch logs once and falls through
+to a direct retrieve. `408`/`429` get one backoff retry, then `FAILED` with the
+reason in `enrichmentError`. Cold lookups run p50 ≈ 7s, p90 ≈ 18s, so
+`timeoutMS: 60000` and never in the request path.
+
+**Progress in the UI** is a TanStack Query `refetchInterval` that runs while
+`enrichmentStatus` is `PENDING` or `RUNNING` and returns `false` once it settles
+— not a `setInterval` in an effect.
+
+`CONTEXT_DEV_API_KEY` lives in the API's environment, declared `@IsOptional()`
+in `env.validation.ts`. No key means enrichment is disabled, logged once at
+boot, and companies stay `PENDING`. The key is server-side only.
+
+### Deal intelligence (Phase 11)
+
+Your deal record shows a *Deal Score* card and an AI-written *Forecast Context*
+that reads like a summary of the timeline. That is the second agent, and it is
+the one that makes this "agentic" rather than "enriched":
+
+- **Deal score** — a 0–100 health number with a one-paragraph rationale,
+ derived from stage age, activity recency and cadence, contact coverage
+ (do we have a champion *and* an economic buyer?), and what the notes
+ actually say. Adds `dealScore`, `dealScoreSummary`, `dealScoredAt`,
+ `forecastContext` and `forecastContextManual` to `Deal` in a Phase 11
+ migration — deliberately not in the §4 schema, so the core model ships
+ without waiting on the model work. Recomputed on stage change and on a
+ nightly cron, never in the request path.
+- **Forecast context** — a rolling summary of the deal's timeline, regenerated
+ when the timeline changes materially. Their record keeps *Forecast Context*
+ and *Forecast Context (manual)* side by side; we do the same, and
+ `forecastContextManual` always wins when set.
+- **Stalled-deal detection** — an open deal with no activity in N days raises a
+ task for its owner. This is the cheapest high-value automation in the whole
+ product and needs no model at all.
+
+Use Claude via the Anthropic API for these; the scoring prompt reads the
+timeline the CRM already stores, so there is nothing new to integrate.
+
+---
+
+## 10. API contract
+
+Every list endpoint speaks one shape, so one table component drives everything.
+
+```ts
+export const listInput = z.object({
+ q: z.string().default(""),
+ sort: z.string().default(""),
+ dir: z.enum(["asc", "desc"]).default("asc"),
+ page: z.number().int().min(1).default(1),
+ pageSize: z.number().int().min(1).max(100).default(25),
+ filters: z.record(z.string(), z.string()).default({}),
+});
+```
+
+Returning `{ rows, total, facetCounts }`, where `facetCounts` feeds the counts
+in the filter dropdowns.
+
+| Router | Procedures |
+| --- | --- |
+| `users` | `me`, `list`, `setRole`, `ban` |
+| `companies` | `list`, `byId`, `create`, `update`, `remove`, `enrich` |
+| `contacts` | `list`, `byId`, `create`, `update`, `remove` |
+| `deals` | `list`, `board`, `byId`, `create`, `update`, `setStage`, `remove` |
+| `activities` | `timeline`, `create`, `update`, `complete`, `remove`, `myTasks` |
+| `properties` | `list`, `create`, `update`, `archive`, `restore`, `purge`, `reorder` |
+| `associations` | `list`, `link`, `unlink`, `setLabel`, `setPrimary`, `labels` |
+| `savedViews` | `list`, `create`, `update`, `remove`, `reorder` |
+| `attachments` | `list`, `createUploadToken`, `download`, `remove` |
+| `dashboard` | `summary` |
+
+One `associations` router serves all three pairings, taking
+`{ pairing, fromId, toId }` rather than one endpoint per direction — the
+alternative is nine near-identical procedures. `setPrimary` runs the
+demote-then-promote transaction from §4, and `unlink` refuses to remove a
+deal's last company.
+
+`listInput.filters` carries facet values as strings. Date-range facets encode
+as either a named window (`last_7_days`, `this_month`, `last_quarter`) or an
+explicit `from..to` pair of ISO dates; the service resolves both to a Prisma
+`gte`/`lte` on the mapped column. Named windows are resolved server-side so a
+shared URL means the same thing tomorrow as it does today.
+
+Every router carries `@UseMiddlewares(AuthMiddleware, PermissionsMiddleware)`
+with per-procedure `meta.permissions`. `deals.setStage` writes the
+`STAGE_CHANGE` activity and stamps `stageChangedAt`/`closedAt` in one
+transaction — a stage change that doesn't appear on the timeline is a bug, so
+it cannot be two calls.
+
+---
+
+## 11. Frontend
+
+### Routes — flat, because sheets carry the depth
+
+```
+apps/app/app/(app)/
+ page.tsx dashboard
+ companies/page.tsx
+ contacts/page.tsx
+ deals/page.tsx
+ settings/properties/page.tsx
+ settings/members/page.tsx
+```
+
+There are no `[id]` routes. A record opens in a sheet driven by a URL param:
+`?company=cmp_123`, `?deal=deal_456`, `?new=company`. The back button closes it,
+the URL is shareable, and we never grow a nested route tree. Deep links render
+the list server-side and open the sheet on top.
+
+### Sheets
+
+Port `responsive-sheet.tsx` and `detail-sheet.tsx` from mvp — `Sheet` on
+desktop, `Drawer` on mobile, behind one API. `DetailSheet` supplies `Header` / `Stats` / `Properties` / `Section` / `Body` /
+`Footer`, which maps onto the HubSpot record layout almost one to one — their
+three-column page becomes one vertical sheet:
+
+- **Header** — logo, name, domain link, owner, enrichment chip, then the
+ composer row your screenshots put under the record title: **Note · Email ·
+ Call · Task · Meeting · More**. Same five, same order.
+- **Stats** — `DetailSheetStats` is their *Data highlights* strip verbatim:
+ **Create date · Lifecycle stage · Last activity date**. On a deal, stage
+ replaces lifecycle.
+- **Properties** — their *About this company* / *Details* panel. System
+ properties first in registry order, then custom, all from §5. Inline-editable
+ in place; no separate edit mode.
+- **Sections** — the right rail, flattened: Companies, Contacts, Deals,
+ Attachments, Timeline. Each shows a count and an **Add** action, and each
+ renders a `SimpleTable` rather than the full `DataTable` — these are short
+ embedded lists, not paginated views. The associated-deal rows carry an inline
+ stage dropdown, matching the contact record in your screenshot.
+
+ Because associations are many-to-many, each row also carries a **Primary**
+ badge and an **association label** chip, both editable in place, exactly as
+ your screenshots show. Sections cap at five rows with a *View all associated
+ …* link that opens the full list filtered to that record — a company with
+ forty contacts must not render forty rows inside a sheet. Adding an
+ association is a `cmdk` search over existing records with a create-new
+ fallback, so linking never means leaving the sheet.
+- **Footer** — save, delete, re-enrich.
+
+**Timeline.** Grouped by month with day sub-headers, newest first, matching
+their *Recent activities*. It gets its own search box, an activity-type filter,
+a date-window filter and a collapse-all toggle. Upcoming and overdue items pin
+above the history with a completion checkbox.
+
+### Create buttons live in the page shell header
+
+Every list page puts its primary action in `PageShellActions`, which the shell
+already positions top-right:
+
+```tsx
+<PageShellHeader breadcrumbItems={[{ label: "Companies" }]}>
+ <PageShellHeading>
+ <PageShellTitle>Companies</PageShellTitle>
+ <PageShellDescription>Every account we sell to.</PageShellDescription>
+ </PageShellHeading>
+ <PageShellActions>
+ <CreateCompanyButton />
+ </PageShellActions>
+</PageShellHeader>
+```
+
+The button sets `?new=company`; the same sheet component handles create and
+edit, distinguished by whether an id is present. One component, one form
+schema, two entry points.
+
+### The data table, and its rules
+
+Ported from `/Users/lewiscarhart/mvp/apps/app/components/data-table/`, rewriting
+`@trycompai/ui` → `@crm/ui`:
+
+| Source | Destination |
+| --- | --- |
+| `data-table.tsx` | `packages/ui/src/components/data-table.tsx` |
+| `table-pagination.tsx`, `numbered-pagination.tsx` | `packages/ui/src/components/` |
+| `use-table-query.ts`, `build-search.ts` | `apps/app/components/data-table/` |
+
+Everything it needs already exists in `@crm/ui`: `table`, `dropdown-menu`,
+`input-group`, `button`, `spinner`, `lib/row-accent`. The hook stays app-side
+because it is routing state, not UI. `nuqs` becomes a `packages/ui` dependency
+since the table owns the `expand` and `hide` params.
+
+Behaviour carried over unchanged:
+
+- `table-fixed` layout, `overflow-hidden` cells, so long values truncate instead
+ of blowing out the table
+- sticky header with `bg-background`
+- search in an `InputGroup` with a leading `Search` icon
+- one dropdown per facet, radio-group single-select, `all` as the reset option
+- a tab dropdown for the primary partition, with counts from `facetCounts`
+- a Sort dropdown listing sortable columns plus asc/desc, and clickable sortable
+ headers with an arrow indicator and `aria-sort`
+- a Columns dropdown toggling `hideable` columns, persisted in `?hide=`
+- the whole filter row collapses behind a Filters button under `sm`, with an
+ active-filter count
+- `useDeferredValue` on rows so typing stays smooth
+- `ROW_ACCENT` on clickable rows; expandable rows use `ROW_ACCENT_EXPANDABLE`
+- pagination footer showing range and total
+
+Five CRM-specific additions, four of them driven by the HubSpot screenshots:
+
+1. **Columns come from the property registry**, not a literal array (§5).
+2. **A row click sets the record's URL param** instead of navigating.
+3. **Date-range facets.** mvp's `DataTable` only has single-select radio
+ facets, but every HubSpot list filters on *Create date*, *Last activity
+ date* and *Close date*. Add a `type` discriminator to `DataTableFacet`:
+ `select` keeps today's behaviour, `dateRange` renders a preset list (Today,
+ Last 7 days, This month, Last quarter, Custom) over `@crm/ui`'s existing
+ `calendar` and `popover`. This is the one real extension to the ported
+ component; everything else is reuse.
+4. **Saved views as tabs above the table.** HubSpot's "Active Customers",
+ "Intent", "Closed Won Deals". Because the entire table state already lives
+ in the URL, a saved view is a stored query string — `savedViews.create`
+ snapshots `query.search`, and clicking a tab replaces the search params.
+ A `+` tab saves the current filter set. This is nearly free given the
+ architecture and it is the feature the team will notice missing on day one.
+5. **Standard cell renderers**, so every list looks like one product:
+ `OwnerCell` (avatar + name, `No owner` when null), `RelativeDateCell`
+ ("Today at 10:07", "Yesterday at 3:20 PM", then absolute), `CurrencyCell`
+ (right-aligned, tabular numerals), `StageBadge`, `LifecycleBadge`, and
+ `@crm/ui`'s existing `empty-cell` rendering `--` for every null — matching
+ HubSpot exactly.
+
+### Default columns
+
+Mirroring your screenshots, so the team's muscle memory survives the move.
+
+| List | Columns |
+| --- | --- |
+| Companies | Name (icon + link), Owner, Industry, Lifecycle stage, Create date, Phone, Last activity, City |
+| Contacts | Name, Email, Company, Title, Lead status, Lifecycle stage, Owner, Last activity |
+| Deals | Name, Stage, Close date, Owner, Amount, Forecast category, Last activity |
+
+Companies default-sort by Create date descending; Deals by Close date
+ascending. Everything beyond the first four columns is `hideable`, so the
+Columns dropdown is genuinely useful rather than decorative.
+
+The Company column renders the primary association, with a `+N` chip when a
+record has more — one line per row, no wrapping, and the full set is one click
+away in the sheet. `AssociationCell` owns this so all three lists agree.
+
+### Forms
+
+`react-hook-form` + `zodResolver` + `@crm/ui` `Field` primitives
+(`Field`, `FieldGroup`, `FieldLabel`, `FieldContent`, `FieldDescription`,
+`FieldError`), matching mvp's `person-sheet.tsx`.
+
+- **One schema per form, shared with the tRPC input** where the shapes match.
+- **`Controller` for non-native controls** (Select, Switch, Combobox);
+ `register` for plain inputs.
+- **`""` means clear, `undefined` means leave alone.** The submit handler maps
+ empty strings to explicit `null`. Collapsing the two makes "clear this field"
+ silently a no-op — mvp learned this the hard way.
+- **Submit through `useMutation`** with an optimistic row patch, `toast.error`
+ on failure, invalidate on settle.
+- **The custom-property section is generated** from `buildFormSchema(defs)` and
+ rendered by a `PropertyField` switch on `type`.
+- **No effect resets the form when the selected record changes.** The sheet body
+ is keyed: `<RecordForm key={recordId} />`.
+
+---
+
+## 12. Conventions
+
+### No `useEffect`
+
+Banned in app and feature code. The five replacements:
+
+| Instead of an effect for | Use |
+| --- | --- |
+| Deriving state from state or props | compute inline during render |
+| Fetching | TanStack Query / tRPC |
+| Reacting to a user action | the event handler |
+| Resetting state when a prop changes | `key` on the component |
+| One-time external sync on mount | `useMountEffect` |
+
+`packages/ui/src/hooks/use-mount-effect.ts` already exists and is the only
+sanctioned wrapper. Concretely in this codebase: sheet open state is derived
+from nuqs, never synced; search debounce is nuqs' `limitUrlUpdates`, not a
+timer; enrichment polling is `refetchInterval`, not `setInterval`; form reset is
+a `key`, not a dependency array.
+
+Enforce it with Biome — `noRestrictedImports` banning the `useEffect` named
+import from `react`, scoped to `apps/app/**` and `packages/ui/src/hooks/**`.
+`packages/ui/src/components` is already Biome-excluded, so vendored shadcn files
+(`calendar`, `sidebar`, `carousel`) are unaffected. Verify the `importNames`
+syntax against Biome 2.5 when wiring it.
+
+### No code comments
+
+New code carries no comments. Names, types and small functions do the
+explaining; anything that genuinely needs prose goes in `docs/`. Existing
+comments stay — churning them adds diff noise and no value. `biome-ignore`
+directives and the auto-generated Prisma header are not comments in this sense.
+
+Add both rules to `AGENTS.md` so every agent session picks them up.
+
+---
+
+## 13. Phases
+
+Each phase ends green on `bun run check-types` and `bun run lint`.
+
+**Phase 0 — Plumbing.** Dependencies; `apps/api/src/trpc/` (module, context,
+auth + permissions + logging middleware, error handler) from the mvp reference;
+`nestjs-trpc generate` + `exports["./app-router"]`; the `/api/[...path]` proxy;
+`lib/trpc/*`; `NuqsAdapter` + `TRPCReactProvider`; the data table into
+`packages/ui`; Biome no-`useEffect` rule; housekeeping on `docs/review.md`,
+`docs/api.md` and the stray temp file. *Verify: the dashboard renders
+`users.me` through a server-prefetched tRPC query.*
+
+**Phase 1 — Auth, RBAC and hosting.** `admin` plugin + access control in
+`packages/auth`; `bun run auth:generate`; Redis secondary storage; owner
+bootstrap; `PermissionsMiddleware`; two Vercel projects; pooled `DATABASE_URL` +
+`DIRECT_URL`; Upstash; blob store. *Verify: a `readonly` user gets 403 from a
+mutation, and the button is hidden.*
+
+**Phase 2 — Schema, registry and seed.** Models from §4 and §5; one migration;
+system property definitions seeded from the versioned constant; seed ~15
+companies with real domains, ~40 contacts, ~25 deals across stages, ~150
+activities including overdue and upcoming. *Verify: `db:migrate`, `db:seed`,
+inspect in Studio.*
+
+**Phase 3 — Companies.** `companies` + `properties` routers; the standard cell
+renderers; the `dateRange` facet type; list page with the registry-driven
+DataTable and the default columns from §11; company sheet with header,
+composer row, Data highlights, properties, contacts, deals; lifecycle stage and
+lead status editable inline; create button in `PageShellActions`. *Verify:
+filter by owner and a date window, sort, page; copy the URL into a new tab and
+get the same view with the sheet open.*
+
+**Phase 3b — Associations.** `associations` router; the three join tables with
+their partial unique indexes; `AssociationLabel` vocabulary and its settings
+screen; `AssociationCell`; the add/link/label/set-primary UI in the sheet
+sections. Lands here because Companies is the first surface that needs it and
+every later phase assumes it. *Verify: a contact on two companies shows Primary
+on exactly one, and a concurrent double-promote fails the write instead of
+producing two.*
+
+**Phase 4 — Contacts.** `contacts` router; list; sheet; multi-company
+associations with labels; lifecycle stage, lead status and buying role.
+Replaces the placeholder page.
+
+**Phase 5 — Deals.** `deals` router; list with stage tab, owner facet and close
+date range; inline stage change writing `STAGE_CHANGE`; forecast category; deal
+sheet with stage stepper, amount, associated companies and contacts with
+labels; the at-least-one-company service invariant. *Verify: a stage change
+appears on the deal and on the timelines of every associated company, and
+`lastActivityAt` moves on all affected records.*
+
+**Phase 5b — Saved views.** `savedViews` router; the tab strip above every
+table; save-current-filters, rename, reorder, share. *Verify: a saved view
+survives a reload and a different browser.*
+
+**Phase 6 — Activity, tasks, dashboard.** Timeline component and composer;
+`activities` router; complete and snooze; dashboard with pipeline by stage,
+closing this month, overdue tasks, recent activity.
+
+**Phase 7 — Attachments.** Blob client uploads; `handleUpload` token route;
+RBAC-checked presigned downloads; attachment sections on all three sheets.
+
+**Phase 8 — Custom properties UI.** Settings → Properties: create, edit,
+reorder, archive, restore; live preview against the table.
+
+**Phase 9 — The agent.** `ContextDevClient`, `EnrichmentService`, `waitUntil`,
+field mapping, status polling, contact-email → company, research brief.
+*Verify: create a company with domain `stripe.com` and watch logo, description,
+industry, socials and address populate within ~20s without a reload.*
+
+**Phase 10 — Migration and polish.** HubSpot CSV import for companies,
+contacts, deals, their custom fields **and their associations with labels and
+primary flags** — HubSpot exports associations as separate files, so the
+importer runs records first, associations second, and reconciles primaries in a
+third pass. Dedupe on `domain`/`email`, lifecycle and lead-status value
+mapping, `assesment-source` typo fix, `lastActivityAt` backfill, prefetch
+warming, dry-run report first. Then deal board view (`?view=board`) and the
+`cmdk` quick switcher.
+
+**Phase 11 — Deal intelligence.** Deal score, forecast context, stalled-deal
+tasks (§9). Last because it is worth nothing until the timeline has real data
+in it.
+
+---
+
+## 14. Open items
+
+- **Vercel Blob store — done.** `crm-attachments`
+ (`store_pXY7wYOD7ccPGUNP`), region `iad1`, **private access**, in the
+ `comp-ai-test` team. Not yet attached to a project, because the repo has no
+ Vercel projects yet; attaching it in Phase 1 is what populates
+ `BLOB_READ_WRITE_TOKEN`. Private access confirms §7's design — the CLI
+ requires `--access public|private` and exposes `blob presign`, so
+ RBAC-checked presigned downloads are the supported path, not a workaround.
+- **Postgres provider** for pooled connections — Neon and Supabase both work;
+ pick one and I'll wire `DATABASE_URL`/`DIRECT_URL`.
+- **`docs/review.md`** — write it or drop the `AGENTS.md` reference.
+
+## 15. Deliberately out of scope
+
+Email sync, calendar sync, sequences and cadences, workflow automation, a
+reporting builder, and territory rules. Plus every object sitting at `(0)` in
+your record sidebars: Tickets, Quotes, Subscriptions, Payments, Orders, Payment
+links and Products. Multiple pipelines are out too — your deals list shows an
+"All Pipelines" selector over a single "Deals pipeline", so one opinionated
+pipeline is the honest version of what you actually run.
+
+Each of these is a HubSpot feature we are choosing not to rebuild. If sales
+asks for one, it is a new plan, not a phase.
diff --git a/docs/design.md b/docs/design.md
new file mode 100644
index 00000000..7d19846e
--- /dev/null
+++ b/docs/design.md
@@ -0,0 +1,8 @@
+# Design — Rules for AI Agents
+
+- /packages/ui is the single source of truth for all UI.
+- Always use shared shadcn components from /packages/ui.
+- Do not override component styles with className.
+- Do not introduce custom border radii, spacing, colours, shadows, or other visual deviations.
+- No rounded corners.
+- If a component needs a new variant or style, implement it in /packages/ui so the entire application stays consistent.
\ No newline at end of file
diff --git a/docs/environment.md b/docs/environment.md
new file mode 100644
index 00000000..04ecfca7
--- /dev/null
+++ b/docs/environment.md
@@ -0,0 +1,213 @@
+# Environment
+
+One root `.env` is the only env file. Copy `.env.example` to `.env` and fill it
+in. There are no per-app or per-package `.env` files.
+
+## How it's loaded
+
+`packages/db/src/env.ts` loads the root `.env` with `dotenv` (never overriding
+vars already set in the real environment). Anything that imports `@trycompai/db`
+(the API, the better-auth CLI, Prisma via `prisma.config.ts`) gets the root
+`.env` from any cwd. `apps/app/next.config.ts` loads it too, so `NEXT_PUBLIC_*`
+are inlined at build time.
+
+## Typed, validated env (no scattered `process.env`)
+
+Application config is read through a zod-validated `env` object per app/package,
+not via ad-hoc `process.env.X` reads. Each validated module fails fast at first
+use with a message naming the bad var:
+
+- `packages/auth/src/env.ts` — Stripe secret/webhook, `REDIS_URL`, better-auth
+ URLs/origins, `CONTEXT_DEV_API_KEY`
+- `packages/email/src/env.ts` — `RESEND_API_KEY`, `EMAIL_FROM`, `EMAIL_APP_URL`
+- `apps/api/src/env.ts` — all API secrets/deployment values
+- `apps/app/lib/env.ts` — `API_URL`, `NEXT_PUBLIC_POSTHOG_*`
+
+Deliberate exceptions (do NOT add new ad-hoc reads outside these):
+
+- `packages/db/src/env.ts` is the dotenv loader only (side-effect import); it must
+ not validate/throw, so `import "@trycompai/db/env"` stays safe for test files
+ that compute a skip condition before touching the DB. `DATABASE_URL` is
+ validated in `client.ts` where the Prisma client is built.
+- `NODE_ENV` is read live via `process.env.NODE_ENV` (not a frozen `env` object)
+ in `apps/api/src/logging/context-logger.ts` and `packages/db/src/client.ts` — it
+ is a platform var and must be runtime-togglable (e.g. the logger test sets it).
+- `packages/tracking/src/config.ts` reads `process.env` lazily at call time: the
+ package is imported into Next client bundles (can't pull in `@trycompai/db/env`
+ → `node:fs`) and is imported before dotenv loads, so a parse-at-import `env`
+ object would capture empty values.
+
+turbo runs in strict env mode; each cached task declares its `env` keys and `.env`
+is a task input so caching invalidates correctly.
+
+## What is NOT an env var (by design)
+
+- **Stripe catalog** (meter event names, per-unit prices, free-seat counts, seat
+ amounts, price `lookup_key`s) lives in `packages/auth/src/billing.config.ts`.
+ `unitPriceCents` MUST equal the Stripe metered price's `unit_amount_decimal`.
+ `stripe:setup` creates and verifies against the catalog — it throws on a metered
+ unit-price mismatch (including a `null` unit amount) and on a reused seat price
+ whose graduated tiers (free-seat boundary or per-seat amount) drift from config.
+- **Stripe price IDs** are resolved at boot from Stripe by `lookup_key` and cached
+ in memory (`packages/auth/src/stripe-prices.ts`) — never stored in env.
+- **Log format/level** default off `NODE_ENV` (json + log-level in prod, pretty +
+ all-levels in dev).
+- **AI model/gateway URL**: the gateway base URL and default model
+ (`DEFAULT_CODE_SECURITY_MODEL`) are code constants
+ (`code-security/shared/contracts.ts`);
+ the Vercel AI Gateway (`AI_GATEWAY_API_KEY`) is the single AI path. The per-org
+ model override lives in the DB (`OrganizationModelConfig`, set in **general
+ workspace settings**) and applies to **every AI call in the app** — code
+ security scans/reviews, cluster/promote/triage, cloud remediation, and pentest —
+ via `resolveModel()` in `apps/api/src/ai/model.ts` (default `DEFAULT_AI_MODEL`).
+ The **selectable model list + per-model billing rates are fetched
+ live from the gateway `/v1/models` endpoint** (`billing/model-pricing.ts`,
+ cached in memory) — not env, not a hardcoded list.
+
+## Stripe setup
+
+Create/verify meters, metered prices, and graduated seat prices (with stable
+lookup keys) in the target Stripe account:
+
+```
+bun run --filter @trycompai/stripe-dev stripe:setup
+```
+
+Nothing to paste into `.env` — price IDs resolve via lookup key at boot. Run this
+against prod Stripe before deploying, or the People plan won't be offered. (The
+`mdm_device_v1` IT Security price is no longer created — that module was retired
+into People on 2026-07-27; archive the existing Stripe price rather than deleting
+it.)
+
+## Database migrations
+
+**Migrations apply themselves on deploy.** The `buildCommand` in
+`apps/app/vercel.json` runs `bun run vercel-build`, which is:
+
+```
+prisma generate → db:deploy → trpc codegen → next build
+```
+
+The history is a single squashed `20260726140000_init` migration. Every
+environment has been baselined onto it, so `migrate deploy` is a no-op until the
+next migration is added. Add new migrations with `db:migrate` as normal.
+
+**Migrations must not run through the connection pooler.** `DATABASE_URL` points
+at Neon's `-pooler` host (PgBouncer, transaction pooling). That is correct for
+the app, but DDL and anything session-scoped must use the direct host — drop
+`-pooler` from the hostname. Session-level advisory locks in particular are
+silently broken through the pooler: the lock is stranded on an arbitrary backend
+and the matching unlock lands on a different one, so it is never released and
+every later connection waiting on it blocks forever.
+
+## Admin access (bootstrap)
+
+The database `admin` role is the only admin path (there is no `ADMIN_USER_IDS`
+env). To grant the first admin, set the role directly:
+
+```sql
+UPDATE "user" SET role = 'admin' WHERE email = '[email protected]';
+```
+
+After that, promote others from the in-app admin panel.
+
+## Advanced / rarely set (not in `.env.example`)
+
+- `PENTEST_AGENT_DIST` — override path to the built pentest agent
+ (`packages/pentest/dist`); auto-discovered otherwise.
+- `BUN_BIN` — bun binary path for `apps/api/scripts/build-func.mjs` (default
+ `bun`); a build-tool override, not app config.
+- `VERCEL`, `NODE_ENV`, `CI` — set by the platform; turbo passes them through.
+
+## Pentest traffic enforcement
+
+Production pentest runs require `REDIS_URL` and `PENTEST_PROXY_BASE_URL` in
+addition to the sandbox and Blob variables in `.env.example`.
+`PENTEST_PROXY_BASE_URL` is the public HTTPS origin of the API deployment. The
+Vercel Sandbox firewall forwards every in-scope HTTPS request to the run-scoped
+proxy endpoint at that origin. Redis provides the shared organization, run,
+host, and route counters plus the temporary redacted traffic ledger. Runs fail
+closed when either dependency is absent.
+
+Vercel Sandbox request forwarding must be enabled for the project plan. HTTP
+targets are rejected because the managed firewall forwarding path is HTTPS-only.
+
+`PENTEST_ARTIFACT_RETENTION_DAYS` optionally enforces a 1–3650 day private
+artifact retention window through the signed artifact manifest. When unset,
+retention remains `not-configured`.
+
+## Cloud Security connectors (keyless customer onboarding)
+
+Both Google connectors are keyless for the customer — nobody creates or downloads
+a service-account key on the customer side, so they work under Google's
+secure-by-default `constraints/iam.disableServiceAccountKeyCreation` org policy.
+The trust model mirrors AWS: a single Comp AI-owned identity, granted access from
+the customer side, mints short-lived credentials per scan.
+
+- **AWS** — `AWS_CONNECTOR_ACCESS_KEY_ID` / `AWS_CONNECTOR_SECRET_ACCESS_KEY`
+ (optional `AWS_CONNECTOR_SESSION_TOKEN`, `AWS_CONNECTOR_REGION`). The customer
+ creates an IAM role trusting this account with `sts:ExternalId` = their org id;
+ the API `AssumeRole`s it per scan.
+- **GCP + Google Workspace** — `GCP_CONNECTOR_SA_KEY` (the JSON key of Comp AI's
+ own connector service account). For **GCP**, the customer creates a read-only
+ auditor SA (no key) and grants the connector SA
+ `roles/iam.serviceAccountTokenCreator` on it; the API impersonates it to mint
+ short-lived tokens per scan. For **Workspace**, the customer authorizes the
+ connector SA's OAuth client ID for domain-wide delegation and the connector
+ impersonates a delegated admin. The connector SA's email and OAuth client ID
+ are derived from the key and surfaced to the onboarding UI via
+ `GET /api/cloud-security/gcp-connector` (and, for People, the
+ `peopleConnections.googleConnector` tRPC query). Set up the connector SA once
+ in Comp AI's own GCP project (where key creation is allowed); enabling
+ `iamcredentials.googleapis.com` on the customer project is part of the
+ onboarding script.
+
+## One Google Workspace delegation, shared by People and Cloud Security
+
+Both modules connect to the same Workspace tenant through **one** domain-wide
+delegation grant. Whichever module's setup wizard the customer completes first
+activates both: `WorkspaceConnectionService.activate`
+(`apps/api/src/integrations/google-workspace/workspace-connection.service.ts`)
+writes the shared `google_workspace_connection` row plus the
+`people_provider_connection` row, and the caller links its own
+`cloud_connection`. Because the delegation is shared, neither module's layout
+gate sends the customer back to a setup wizard once either has been run.
+
+- **Scopes** live in `apps/api/src/integrations/google-workspace/scopes.ts` and
+ nowhere else. The customer authorizes `WORKSPACE_ALL_SCOPES` (read **and**
+ write). Both Cloud Security and People request `WORKSPACE_READ_SCOPES` — the
+ same six read-only scopes Cloud Security always requested, unchanged, so
+ existing grants keep working. `WORKSPACE_DIRECTORY_SCOPES` (write) is still
+ probed at activation to record `writeAccessGranted`, but nothing requests a
+ write token today; People reads the directory and never writes to it.
+ Both the `.readonly` and the write variant of a scope must be in the grant:
+ domain-wide delegation matches scope strings exactly, so a grant holding only
+ `admin.directory.user` rejects a request for `admin.directory.user.readonly`.
+- **Cloud Security must never request write scopes.** `mintDelegatedAccessToken`
+ asserts it for `purpose: "read"`, and
+ `apps/api/test/google-workspace-delegation.spec.ts` fails if any file under
+ `apps/api/src/cloud-security/` so much as mentions a write scope or
+ `purpose: "write"`.
+- **Known residual risk:** the scan pipeline writes the connector SA's raw
+ private key into the Vercel Sandbox for Prowler
+ (`scan-pipeline.service.ts`, `google_workspace` case). Because the grant now
+ includes write scopes, that sandbox credential *could* mint a write-scoped
+ token — the read-only guarantee is enforced in our code, not by the grant. The
+ fix, if this becomes unacceptable, is a second read-only connector SA whose
+ client ID is authorized for the read scopes only; the scope-selection seam
+ (`scopesForPurpose`) is where that would plug in.
+- **Domain-wide delegation is the only credential path.** There is no stored
+ secret: every call mints a short-lived token from the shared delegation. The
+ old "sign in with a Google super admin" OAuth mode (refresh token in
+ `people_provider_connection.encryptedPayload`) and its backfill script were
+ removed along with the rest of the People module; `credentialMode`,
+ `encryptedPayload`, `scheme`, and `tokenExpiresAt` are gone from the table.
+- **Re-authorization.** A delegation refused with `unauthorized_client` /
+ `access_denied` flips the shared row to `status = "scopes_outdated"` and
+ `writeAccessGranted = false`, and degrades the People connection; the People
+ setup wizard is where the customer re-authorizes.
+
+Note: customer org policies that restrict cross-org IAM members
+(`constraints/iam.allowedPolicyMemberDomains`, domain-restricted sharing) can
+block granting the connector SA on the customer project — this is inherent to any
+cross-org GCP access model and is surfaced as a connect error.
diff --git a/docs/plan/crm-plan.md b/docs/plan/crm-plan.md
new file mode 100644
index 00000000..54e0ce2f
--- /dev/null
+++ b/docs/plan/crm-plan.md
@@ -0,0 +1,555 @@
+# Plan — Agentic CRM (HubSpot replacement)
+
+A lightweight, opinionated CRM for our sales team. Companies are the top-level
+object; Contacts and Deals hang off them; everything that happens is an
+**Activity** on a timeline. Company knowledge (logo, description, industry,
+socials, address) is filled in by an agent using [Context.dev](https://docs.context.dev)
+rather than typed by a human.
+
+This document is the build plan: decisions, data model, contracts, and phased
+delivery. Read it with [`AGENTS.md`](../AGENTS.md), [`design.md`](./design.md)
+and [`api.md`](./api.md).
+
+---
+
+## 1. Decisions up front
+
+| Decision | Choice | Why |
+| --- | --- | --- |
+| Tenancy | **Single tenant, no organizations** | The repo is already built this way (`20260731160000_remove_organizations`). It's an internal tool; Google sign-in is the only door. |
+| Data fetching | **tRPC (nestjs-trpc) end to end** | Type-safe from Prisma to the table cell, and the pattern is proven in `/Users/lewiscarhart/mvp`. |
+| Table state | **nuqs**, server-side pagination/sort/filter | URLs are shareable and survive reload; the API does the work so 10k rows stay fast. |
+| Data table | Port `mvp`'s `DataTable` into **`packages/ui`** | `design.md` makes `/packages/ui` the single source of truth; `simple-table` and `card-table` already live there. Same code as mvp, different address. |
+| Enrichment | **Context.dev**, fire-and-forget on write, cached in Postgres | 10 credits per company; we never pay twice for the same domain. |
+| Activity model | **One `Activity` table**, denormalised `companyId` | A company timeline must show its deals' and contacts' events. One indexed query beats three joins. |
+| Deal owner | `Deal.ownerId` → `User`, **required** | Every deal has a name against it. Companies and contacts have optional owners. |
+
+### Judgment calls worth your veto
+
+- **`UNQUALIFIED_TO_BUY` is terminal, not linear.** You listed it between
+ "qualified to buy" and "decision maker bought-in", but it's a disqualification,
+ not a step forward. Plan treats it like `CLOSED_LOST`: excluded from pipeline
+ value and forecast, shown in a "Closed" tab rather than the open pipeline. Say
+ the word if you want it mid-funnel instead.
+- **`Contact.email` is unique.** Matches HubSpot's own constraint and makes the
+ CSV import idempotent. The cost: two people behind one `info@` address need
+ separate records with one email each.
+- **`Company.domain` is the enrichment key and is unique.** Two records for the
+ same domain is the #1 way a CRM rots, so we block it at the database.
+
+### Repo inconsistencies found while surveying
+
+- **`docs/review.md` does not exist** but `AGENTS.md` says "Always review" it.
+ Either write it or drop the reference — right now every agent starts by
+ failing to read a required file.
+- **`docs/api.md` describes a multi-tenant world this repo doesn't have.** The
+ org-context (`x-organization-slug`, `OrgContextInterceptor`) and per-org cache
+ generation sections were carried over from the MVP; there are no
+ organizations here. The **logging** rules apply verbatim and should stay.
+ Recommend trimming api.md to logging + a short "no orgs, no org cache keys"
+ note in Phase 0.
+- `apps/app/make-session.tmp.ts` is a stray scratch file, safe to delete.
+
+---
+
+## 2. Architecture
+
+```
+browser
+ │ same-origin /api/trpc (cookies just work)
+ ▼
+apps/app (Next.js 16, RSC)
+ ├─ app/api/[...path]/route.ts ──proxy──▶ apps/api:3001
+ ├─ server components: prefetch via getServerTrpc() → HydrationBoundary
+ └─ client components: useTRPC() + TanStack Query, nuqs for table state
+ │
+apps/api (NestJS on Bun, port 3001) ▼
+ ├─ /api/trpc nestjs-trpc routers (companies, contacts, deals, activities, users)
+ ├─ /api/auth/* Better Auth (Google only)
+ ├─ services Prisma queries, timeline writes
+ └─ enrichment Context.dev client + queue ──▶ api.context.dev
+ │
+packages/db (Prisma) ◀────────────────────────┘
+```
+
+Two things the CRM adds to the existing skeleton:
+
+1. **`apps/app/app/api/[...path]/route.ts`** — a catch-all proxy (ported from
+ `mvp`) so the browser calls `/api/trpc` same-origin. Today the app sends the
+ browser straight to `:3001`; that works for auth redirects but makes every
+ tRPC call a cross-origin, credentialed request. The proxy removes that whole
+ class of problem and streams SSE through untouched.
+2. **`apps/api` exports its router type**: `"exports": { "./app-router": "./src/generated/server.ts" }`,
+ generated by `nestjs-trpc generate`. The app imports `type { AppRouter } from "api/app-router"`.
+
+### Dependencies to add
+
+| Package | Where | Version (matching mvp) |
+| --- | --- | --- |
+| `@trpc/server`, `zod` | `apps/api` | `^11.18.0`, `^4.4.3` |
+| `@trpc/client`, `@trpc/server`, `@trpc/tanstack-react-query` | `apps/app` | `^11.18.0` |
+| `@tanstack/react-query`, `@tanstack/react-query-devtools` | `apps/app` | `^5.101.2` |
+| `nuqs` | `apps/app` + `packages/ui` | `^2.8.9` |
+| `zod` | `apps/app` | `^4.4.3` |
+| `context.dev` | `apps/api` | latest |
+
+`nestjs-trpc` (`^2.13.0`) and `@keyv/redis`/`cache-manager` are already in
+`apps/api`. Note `nestjs-trpc` ships a binary that may need the
+`postinstall` chmod shim mvp uses — check on first install.
+
+---
+
+## 3. Data model
+
+New models in `packages/db/prisma/schema.prisma`. Auth models are untouched.
+
+```prisma
+enum DealStage {
+ DEMO_BOOKED
+ QUALIFIED_TO_BUY
+ UNQUALIFIED_TO_BUY // terminal — disqualified
+ DECISION_MAKER_BOUGHT_IN
+ CONTRACT_SENT
+ CLOSED_WON
+ CLOSED_LOST
+}
+
+enum ActivityType {
+ NOTE
+ CALL
+ EMAIL
+ MEETING
+ TASK
+ STAGE_CHANGE // written by the system on Deal.stage change
+ ENRICHMENT // written by the agent
+}
+
+enum EnrichmentStatus { PENDING RUNNING COMPLETE FAILED SKIPPED }
+
+model Company {
+ id String @id @default(cuid())
+ name String
+ domain String? @unique // bare, normalised: "stripe.com"
+ website String?
+ description String?
+ // brand (Context.dev)
+ logoUrl String?
+ logoDarkUrl String?
+ iconUrl String? // square — used in table rows
+ brandColor String? // hex
+ // firmographics
+ industry String?
+ subIndustry String?
+ city String?
+ stateCode String?
+ country String?
+ countryCode String?
+ // contact + socials
+ phone String?
+ email String?
+ linkedinUrl String?
+ twitterUrl String?
+ githubUrl String?
+ pricingUrl String?
+ careersUrl String?
+ // ownership
+ ownerId String?
+ owner User? @relation("CompanyOwner", fields: [ownerId], references: [id], onDelete: SetNull)
+ primaryContactId String? @unique
+ primaryContact Contact? @relation("PrimaryContact", fields: [primaryContactId], references: [id], onDelete: SetNull)
+ // enrichment bookkeeping
+ enrichmentStatus EnrichmentStatus @default(PENDING)
+ enrichedAt DateTime?
+ enrichmentError String?
+ enrichment CompanyEnrichment?
+
+ contacts Contact[] @relation("CompanyContacts")
+ deals Deal[]
+ activities Activity[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([ownerId])
+ @@index([name])
+ @@map("company")
+}
+
+/// Raw Context.dev payload, kept so re-deriving fields costs nothing.
+model CompanyEnrichment {
+ companyId String @id
+ company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ source String @default("context.dev")
+ raw Json
+ fetchedAt DateTime @default(now())
+
+ @@map("companyEnrichment")
+}
+
+model Contact {
+ id String @id @default(cuid())
+ firstName String
+ lastName String?
+ email String? @unique
+ phone String?
+ title String?
+ linkedinUrl String?
+ companyId String?
+ company Company? @relation("CompanyContacts", fields: [companyId], references: [id], onDelete: SetNull)
+ ownerId String?
+ owner User? @relation("ContactOwner", fields: [ownerId], references: [id], onDelete: SetNull)
+ primaryOf Company? @relation("PrimaryContact")
+
+ deals DealContact[]
+ activities Activity[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([companyId])
+ @@index([ownerId])
+ @@map("contact")
+}
+
+model Deal {
+ id String @id @default(cuid())
+ name String
+ companyId String
+ company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ ownerId String
+ owner User @relation("DealOwner", fields: [ownerId], references: [id])
+ stage DealStage @default(DEMO_BOOKED)
+ stageChangedAt DateTime @default(now())
+ amount Decimal? @db.Decimal(14, 2)
+ currency String @default("USD")
+ expectedCloseDate DateTime?
+ closedAt DateTime?
+ closedReason String?
+
+ contacts DealContact[]
+ activities Activity[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([companyId])
+ @@index([ownerId])
+ @@index([stage])
+ @@index([expectedCloseDate])
+ @@map("deal")
+}
+
+model DealContact {
+ dealId String
+ deal Deal @relation(fields: [dealId], references: [id], onDelete: Cascade)
+ contactId String
+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ role String?
+
+ @@id([dealId, contactId])
+ @@map("dealContact")
+}
+
+model Activity {
+ id String @id @default(cuid())
+ type ActivityType
+ subject String?
+ body String?
+
+ occurredAt DateTime? // logged in the past
+ dueAt DateTime? // scheduled for the future
+ completedAt DateTime?
+
+ /// Always stamped when resolvable, even for deal/contact activity, so a
+ /// company timeline is one indexed range scan.
+ companyId String?
+ company Company? @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ dealId String?
+ deal Deal? @relation(fields: [dealId], references: [id], onDelete: Cascade)
+
+ createdById String
+ createdBy User @relation("ActivityAuthor", fields: [createdById], references: [id])
+ meta Json? // { from, to } for STAGE_CHANGE, credit cost for ENRICHMENT
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([companyId, createdAt])
+ @@index([dealId, createdAt])
+ @@index([contactId, createdAt])
+ @@index([dueAt])
+ @@map("activity")
+}
+```
+
+`User` gains the back-relations (`CompanyOwner`, `ContactOwner`, `DealOwner`,
+`ActivityAuthor`). It is otherwise untouched — Better Auth owns that model and
+`bun run auth:generate` regenerates it.
+
+### Timeline semantics
+
+- **Past** = `occurredAt` set, or `completedAt` set, or a `NOTE`/`STAGE_CHANGE`/`ENRICHMENT` row (use `createdAt`).
+- **Upcoming** = `dueAt > now()` and `completedAt IS NULL`.
+- **Overdue** = `dueAt < now()` and `completedAt IS NULL`.
+- A company's timeline is `WHERE companyId = ?`, which picks up deal and contact
+ activity for free because we stamp `companyId` on write.
+
+### Pipeline math
+
+- **Open stages**: `DEMO_BOOKED`, `QUALIFIED_TO_BUY`, `DECISION_MAKER_BOUGHT_IN`, `CONTRACT_SENT`.
+- **Closed stages**: `CLOSED_WON`, `CLOSED_LOST`, `UNQUALIFIED_TO_BUY`.
+- Pipeline value = `SUM(amount)` over open stages. Setting a closed stage stamps
+ `closedAt` and prompts for `closedReason` on the two losing outcomes.
+
+---
+
+## 4. The agentic layer (Context.dev)
+
+`apps/api/src/enrichment/` — a `ContextDevClient` (thin typed wrapper over
+`https://api.context.dev/v1`) plus an `EnrichmentService` that owns a small
+in-process queue (concurrency 2, one retry with backoff, per-domain dedupe).
+
+**Trigger points**
+
+| Event | Call | Cost |
+| --- | --- | --- |
+| Company created/updated with a new `domain` | `POST /brand/retrieve` `{type:"by_domain"}` | 10 credits |
+| Manual "Re-enrich" button | same, `maxAgeMs: 0` | 10 credits |
+| Contact created with a work email and no company | `POST /brand/retrieve` `{type:"by_email"}` → find-or-create Company | 10 credits |
+| CSV import (bulk) | `POST /utility/prefetch` per row, then retrieve | prefetch free (paid plan) |
+| "Research this company" action | `POST /web/extract` with our schema → `ENRICHMENT` activity | 10 credits |
+
+**Field mapping** from the `brand` object:
+
+- `title` → `name` (only when the record was created domain-first and unnamed)
+- `description`, `slogan` → `description`
+- `logos[]` → pick by `mode`/`type`, never `logos[0]`:
+ `logoUrl` = light+`logo`, `logoDarkUrl` = dark+`logo`, `iconUrl` = `icon`
+- `colors[0].hex` → `brandColor` (key off `hex`; the `name` is generated)
+- `industries.eic[0]` → `industry` / `subIndustry`
+- `address` → `city`, `stateCode`, `country`, `countryCode`
+- `socials[]` → `linkedinUrl` / `twitterUrl` / `githubUrl` by `type`
+- `links` → `pricingUrl`, `careersUrl`
+- `email`, `phone` → same fields
+- Whole payload → `CompanyEnrichment.raw`
+
+**Handling**, per the Context.dev skill:
+- Every field is nullable — never overwrite a human-entered value with `null`.
+- `400 NOT_FOUND` / `WEBSITE_ACCESS_ERROR` → `SKIPPED`, not `FAILED` (and not billed).
+- `422` on email lookup (free/disposable) → `SKIPPED`, no company created.
+- `403 FORBIDDEN` on prefetch → log once, fall through to direct retrieve.
+- `408`/`429` → one backoff retry, then `FAILED` with `enrichmentError`.
+- Cold lookups are p50 ≈ 7s, p90 ≈ 18s. Always background; never block the
+ create mutation. Set `timeoutMS: 60000`.
+
+**Research brief** (`POST /web/extract`) uses a fixed JSON Schema —
+`{ positioning, pricingModel, targetCustomer, notableCustomers[], recentNews[] }`
+— and posts the result as an `ENRICHMENT` activity on the company timeline so a
+rep sees it in context instead of in a side panel.
+
+**Config**: `CONTEXT_DEV_API_KEY` in `apps/api/.env`, declared `@IsOptional()`
+in `env.validation.ts`. Absent key ⇒ enrichment disabled, logged once at boot,
+companies stay `PENDING`. The key never reaches the browser; all calls are
+server-side.
+
+**Caching note**: `docs/api.md`'s org-scoped generation keys don't apply (no
+orgs). tRPC responses aren't served by the HTTP response cache; freshness comes
+from TanStack Query invalidation on mutation. Enrichment finishing is a
+*background* write the client can't see, so the company detail page polls
+(`refetchInterval` while `enrichmentStatus` is `PENDING`/`RUNNING`) and stops
+when it settles.
+
+---
+
+## 5. tRPC contract
+
+Every list endpoint speaks the same shape so one `DataTable` drives all three
+modules.
+
+```ts
+// apps/api/src/trpc/list-input.ts
+export const listInput = z.object({
+ q: z.string().default(""),
+ sort: z.string().default(""),
+ dir: z.enum(["asc", "desc"]).default("asc"),
+ page: z.number().int().min(1).default(1),
+ pageSize: z.number().int().min(1).max(100).default(25),
+});
+// → { rows: T[]; total: number; facetCounts: Record<string, Record<string, number>> }
+```
+
+| Router | Procedures |
+| --- | --- |
+| `users` | `me`, `list` (owner pickers) |
+| `companies` | `list` (+ facets `owner`, `industry`, `enrichment`), `byId`, `create`, `update`, `remove`, `setPrimaryContact`, `enrich` |
+| `contacts` | `list` (+ facets `owner`, `company`), `byId`, `create`, `update`, `remove` |
+| `deals` | `list` (+ tab `stage`, facets `owner`, `closing`), `board`, `byId`, `create`, `update`, `setStage`, `setContacts`, `remove` |
+| `activities` | `timeline` ({ companyId? contactId? dealId?, filter, cursor }), `create`, `update`, `complete`, `remove`, `myTasks` |
+| `dashboard` | `summary` (pipeline by stage, closing this month, overdue tasks, recent activity) |
+
+All routers carry `@UseMiddlewares(AuthMiddleware)` — ported from mvp minus the
+org and permissions middleware, which have no meaning here. `deals.setStage`
+writes the `STAGE_CHANGE` activity and stamps `stageChangedAt`/`closedAt` in the
+same transaction.
+
+Filtering, sorting and pagination happen **in Prisma**, not in the browser.
+`q` searches name/domain/email with a case-insensitive `contains`; add a
+`pg_trgm` index if the tables ever get big enough to notice.
+
+---
+
+## 6. Frontend
+
+### Routes
+
+```
+apps/app/app/(app)/
+ page.tsx dashboard
+ companies/page.tsx DataTable
+ companies/[companyId]/page.tsx detail + timeline
+ contacts/page.tsx DataTable (placeholder exists today)
+ contacts/[contactId]/page.tsx detail + timeline
+ deals/page.tsx DataTable (+ ?view=board)
+ deals/[dealId]/page.tsx detail + timeline
+```
+
+`AppIconRail` gains Companies and Deals entries alongside the existing Overview
+(`Dashboard`) and Contacts (`UserMultiple`) — Carbon glyphs imported one at a
+time through the `Icon` wrapper, per the README. Pick the glyph names off the
+[Carbon icon library](https://carbondesignsystem.com/libraries/icons/) and
+confirm the file exists in `@carbon/icons-react/es/` before importing; the
+package isn't installed in this checkout yet, so the names are unverified.
+
+### The data table
+
+Port these from `/Users/lewiscarhart/mvp/apps/app/components/data-table/`,
+rewriting `@trycompai/ui` → `@crm/ui`:
+
+| Source | Destination |
+| --- | --- |
+| `data-table.tsx` (631 lines) | `packages/ui/src/components/data-table.tsx` |
+| `table-pagination.tsx`, `numbered-pagination.tsx` | `packages/ui/src/components/` |
+| `use-table-query.ts`, `build-search.ts` | `apps/app/components/data-table/` |
+
+Everything it depends on already exists in `@crm/ui`: `table`, `dropdown-menu`,
+`input-group`, `button`, `spinner`, and `lib/row-accent`. The hook stays in the
+app because it's routing state, not UI. `nuqs` becomes a dependency of
+`packages/ui` (the table owns the `expand` and `hide` params).
+
+Behaviour we're keeping verbatim: sticky header, `table-fixed` with truncating
+cells, sort/columns/facet dropdowns, mobile filter collapse, expandable rows,
+`useDeferredValue` so typing stays smooth, and the pagination footer.
+
+### nuqs conventions
+
+- `NuqsAdapter` from `nuqs/adapters/next/app` wraps the root layout, alongside
+ `TRPCReactProvider`.
+- Shared parsers live in a `*-search-params.ts` per module, importing from
+ **`nuqs/server`** so the page and the client component agree.
+- Server components read them with `createLoader`, and pass the parsed values
+ into the tRPC prefetch so the first paint is already filtered.
+- The search box uses `limitUrlUpdates` (nuqs' built-in debounce) rather than a
+ hand-rolled timer.
+- `clearOnDefault` everywhere, so a default view has a clean URL.
+- Table state stays **shallow** (default): TanStack Query refetches; we don't
+ round-trip the RSC on every keystroke. Detail sheets (`?company=`, `?deal=`)
+ are shallow too.
+
+### Server rendering
+
+Each list page prefetches through `getServerTrpc()` + `getServerQueryClient()`
+and wraps the client panel in `<HydrationBoundary state={dehydrate(queryClient)}>`
+— the exact mvp pattern, minus the org slug.
+
+### Company detail page
+
+The page that has to be good, because it's where reps live:
+
+- **Header** — logo (`iconUrl`, falling back to initials), name, domain link,
+ industry badge, owner avatar, and an enrichment state chip that shows a
+ spinner while the agent works.
+- **Left column** — properties card (inline-editable: name, domain, website,
+ phone, address, owner), primary contact card, socials row.
+- **Right column** — the timeline: composer at the top (Note · Call · Email ·
+ Meeting · Task), then Upcoming/Overdue pinned, then history grouped by day.
+ Filter tabs via nuqs (`?tab=all|notes|upcoming|done`).
+- **Below** — Contacts table and Deals table, both `SimpleTable` (not the full
+ `DataTable`; these are short embedded lists).
+
+Per `design.md`: shared components only, no bespoke radii/spacing/colours, no
+rounded corners. `brandColor` is used as a small accent swatch, never as a
+surface — brand colours would fight the design tokens.
+
+---
+
+## 7. Phases
+
+Each phase ends green on `bun run check-types` and `bun run lint`.
+
+### Phase 0 — Plumbing (no product surface)
+- Add the dependencies in §2; wire `apps/api/src/trpc/` (module, context,
+ `AuthMiddleware`, error handler, logging middleware) from the mvp reference.
+- `nestjs-trpc generate` script + `exports["./app-router"]`; add the watch task
+ to `dev`.
+- `apps/app/app/api/[...path]/route.ts` proxy; `lib/trpc/{server.ts,client.tsx,query-client.ts}`.
+- `NuqsAdapter` + `TRPCReactProvider` in the root layout.
+- Port the data table into `packages/ui`.
+- Housekeeping: resolve `docs/review.md`, trim the org sections from
+ `docs/api.md`, delete `make-session.tmp.ts`.
+- **Verify**: dashboard renders `users.me` through tRPC, server-prefetched.
+
+### Phase 1 — Schema and seed
+- The models in §3, one migration, `User` back-relations.
+- Extend `packages/db/prisma/seed.ts`: ~15 companies (real domains so enrichment
+ has something to chew on), ~40 contacts, ~25 deals spread across stages, ~150
+ activities including overdue and upcoming tasks.
+- **Verify**: `bun run db:migrate && bun run db:seed`, inspect in Studio.
+
+### Phase 2 — Companies
+- `companies` router + service; list page with DataTable — columns: logo+name,
+ domain, industry, owner, contacts, open deals, last activity; facets owner /
+ industry / enrichment status; search on name+domain.
+- Company detail page per §6, minus the timeline (Phase 5 stub).
+- Create sheet: name + domain + owner, nothing else. The agent fills the rest.
+- **Verify**: filter + sort + page, copy the URL into a new tab, same view.
+
+### Phase 3 — Contacts
+- `contacts` router; list DataTable (name, title, email, company, owner, last
+ activity); detail page; company link; "make primary contact" action.
+- Replace the existing `contacts/page.tsx` placeholder.
+
+### Phase 4 — Deals
+- `deals` router; list DataTable (name, company, stage badge, amount, owner,
+ expected close, last activity); tab = open/closed/all, facets owner + stage.
+- Inline stage change from the row (dropdown) writing `STAGE_CHANGE`.
+- Deal detail: stage stepper, amount/currency/close date, associated contacts,
+ timeline slot.
+- **Verify**: stage change appears on the deal *and* the company timeline.
+
+### Phase 5 — Activity, tasks and dashboard
+- Timeline component + composer; `activities` router; complete/snooze on tasks.
+- Dashboard: pipeline value by stage, deals closing this month, my overdue
+ tasks, recent activity feed.
+- **Verify**: a note on a deal shows on the company timeline; an overdue task
+ shows on the dashboard.
+
+### Phase 6 — The agent
+- `ContextDevClient`, `EnrichmentService`, queue, field mapping, status polling.
+- Auto-enrich on company create; manual re-enrich; contact-email → company.
+- Research brief action writing an `ENRICHMENT` activity.
+- **Verify**: create a company with domain `stripe.com` → logo, description,
+ industry, socials and address populate within ~20s without a reload.
+
+### Phase 7 — Migration and polish
+- HubSpot CSV import for companies/contacts/deals, dedupe on `domain`/`email`,
+ `utility/prefetch` warming before the retrieve pass, dry-run report first.
+- Deal board view (`?view=board`, stage columns, drag to change stage).
+- `cmdk` quick switcher over companies/contacts/deals.
+
+---
+
+## 8. What this plan deliberately leaves out
+
+Email sync, calendar sync, sequences/cadences, quotes, custom properties,
+multiple pipelines, reporting builder, and permissions/roles. Every one of them
+is a HubSpot feature we're choosing not to rebuild. If the sales team asks for
+one, it's a new plan, not a phase.
diff --git a/package.json b/package.json
index 71313295..14945577 100644
--- a/package.json
+++ b/package.json
@@ -1,29 +1,38 @@
{
- "name": "crm",
- "private": true,
- "scripts": {
- "build": "turbo run build",
- "dev": "turbo run dev",
- "lint": "turbo run lint",
- "format": "prettier --write \"**/*.{ts,tsx,md}\"",
- "check-types": "turbo run check-types"
- },
- "devDependencies": {
- "prettier": "^3.7.4",
- "turbo": "^2.10.8",
- "typescript": "5.9.2"
- },
- "engines": {
- "node": ">=18"
- },
- "devEngines": {
- "packageManager": {
- "name": "bun",
- "version": "1.3.12"
- }
- },
- "workspaces": [
- "apps/*",
- "packages/*"
- ]
+ "name": "crm",
+ "private": true,
+ "scripts": {
+ "build": "turbo run build",
+ "dev": "turbo run dev",
+ "lint": "turbo run lint",
+ "format": "biome format --write .",
+ "check-types": "turbo run check-types",
+ "test": "turbo run test",
+ "auth:generate": "turbo run auth:generate",
+ "db:deploy": "turbo run db:deploy",
+ "db:generate": "turbo run db:generate",
+ "db:migrate": "turbo run db:migrate",
+ "db:push": "turbo run db:push",
+ "db:reset": "turbo run db:reset",
+ "db:seed": "turbo run db:seed",
+ "db:studio": "turbo run db:studio"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "^2.4.10",
+ "turbo": "^2.10.8",
+ "typescript": "5.9.2"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "devEngines": {
+ "packageManager": {
+ "name": "bun",
+ "version": "1.3.12"
+ }
+ },
+ "workspaces": [
+ "apps/*",
+ "packages/*"
+ ]
}
diff --git a/packages/auth/.env.example b/packages/auth/.env.example
new file mode 100644
index 00000000..a14489ab
--- /dev/null
+++ b/packages/auth/.env.example
@@ -0,0 +1,7 @@
+# Required. Generate with: openssl rand -base64 32
+BETTER_AUTH_SECRET="6oXI/PGPx8OGGiVz7zW2EODV6LcKmtyALiR+RvG2yc8="
+BETTER_AUTH_URL="http://localhost:3001"
+AUTH_TRUSTED_ORIGINS="http://localhost:3000"
+GOOGLE_CLIENT_ID=""
+GOOGLE_CLIENT_SECRET=""
+AUTH_COOKIE_DOMAIN=""
diff --git a/packages/auth/README.md b/packages/auth/README.md
new file mode 100644
index 00000000..9d0e886f
--- /dev/null
+++ b/packages/auth/README.md
@@ -0,0 +1,94 @@
+# `@crm/auth`
+
+[Better Auth](https://better-auth.com) configuration for the monorepo, backed by
+`@crm/db`.
+
+Enabled: Google sign-in, account linking, cookie-cached sessions, and
+database-backed rate limiting. This is an internal, single-tenant app — there
+are no organizations, and email + password is switched off so the only way in
+is a Google account.
+
+## Topology
+
+The **NestJS API** (`apps/api`, port 3001) mounts `/api/auth/*` via
+`@thallesp/nestjs-better-auth` and is the only process that writes session
+cookies. The **Next.js app** (`apps/app`, port 3000) imports this package on the
+server to *read* sessions straight from Postgres, and points its browser client
+at the API for sign-in and sign-out.
+
+Both processes therefore need the same `BETTER_AUTH_SECRET` and `DATABASE_URL`,
+or the cookie one writes will not verify in the other.
+
+## Usage
+
+### Server
+
+```ts
+import { auth } from "@crm/auth";
+
+// Session for an incoming request
+const session = await auth.api.getSession({ headers: request.headers });
+```
+
+`auth.handler` is a standard `(Request) => Promise<Response>` function, so it
+mounts anywhere. In a Next.js App Router route (`app/api/auth/[...all]/route.ts`):
+
+```ts
+import { auth } from "@crm/auth";
+
+export const GET = auth.handler;
+export const POST = auth.handler;
+```
+
+### Client
+
+```ts
+import { signIn, signOut, useSession } from "@crm/auth/client";
+
+await signIn.social({ provider: "google", callbackURL: "/" });
+```
+
+`NEXT_PUBLIC_AUTH_URL` decides which origin the client talks to. It must point
+at whichever process mounts the handler; unset, the client uses the current
+origin.
+
+The client plugin list mirrors the server plugin list. Keep them in sync or the
+inferred client API will drift from the routes the server exposes.
+
+## Setup
+
+```bash
+cp packages/auth/.env.example packages/auth/.env
+openssl rand -base64 32 # -> BETTER_AUTH_SECRET
+```
+
+Create an OAuth client in the Google Cloud console and add
+`<BETTER_AUTH_URL>/api/auth/callback/google` — `http://localhost:3001/api/auth/callback/google`
+in development — as an authorised redirect URI.
+
+`BETTER_AUTH_SECRET` and `BETTER_AUTH_URL` are read from the environment by
+Better Auth itself and are deliberately not passed through config.
+
+## Changing the schema
+
+Adding a plugin or an additional user field changes the database schema. After
+editing `src/auth.ts`:
+
+```bash
+bun run auth:generate # rewrites packages/db/prisma/schema.prisma
+bun run db:migrate # create the migration
+```
+
+## Notes
+
+- **JIT package.** `exports` point at TypeScript sources, which keeps Better
+ Auth's inferred types intact — declaration emit tends to break them.
+ Turbopack transpiles workspace packages automatically, so a Next.js app needs
+ no `transpilePackages` entry.
+- **Next.js server actions** need the `nextCookies()` plugin (from
+ `better-auth/next-js`) as the *last* entry in the plugin array. It is omitted
+ here so the package stays framework-agnostic; add it — along with `next` as a
+ dependency — once an app relies on setting cookies from server actions.
+- **Cross-origin cookies.** On localhost the API and the app differ only by
+ port, which cookies ignore. Deployed on separate subdomains they need
+ `AUTH_COOKIE_DOMAIN` set to the shared parent (`.example.com`).
diff --git a/packages/auth/package.json b/packages/auth/package.json
new file mode 100644
index 00000000..55857f93
--- /dev/null
+++ b/packages/auth/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "@crm/auth",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client.ts"
+ },
+ "scripts": {
+ "auth:generate": "better-auth generate --config src/auth.ts --output ../db/prisma/schema.prisma --y",
+ "check-types": "tsc --noEmit",
+ "lint": "biome check .",
+ "clean": "rm -rf .turbo node_modules"
+ },
+ "dependencies": {
+ "@crm/db": "workspace:*",
+ "better-auth": "^1.6.25"
+ },
+ "peerDependencies": {
+ "react": "^19.2.0"
+ },
+ "peerDependenciesMeta": {
+ "react": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "@better-auth/cli": "^1.4.22",
+ "@crm/typescript-config": "workspace:*",
+ "@types/node": "^24.10.1",
+ "@types/react": "^19.2.18",
+ "react": "^19.2.8",
+ "typescript": "5.9.2"
+ }
+}
diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.ts
new file mode 100644
index 00000000..d8058298
--- /dev/null
+++ b/packages/auth/src/auth.ts
@@ -0,0 +1,63 @@
+import { db } from "@crm/db";
+import { type BetterAuthOptions, betterAuth } from "better-auth";
+import { prismaAdapter } from "better-auth/adapters/prisma";
+import { env } from "./env";
+
+const socialProviders: NonNullable<BetterAuthOptions["socialProviders"]> = {};
+
+if (env.google) {
+ socialProviders.google = env.google;
+}
+
+export const auth = betterAuth({
+ appName: "CRM",
+
+ database: prismaAdapter(db, {
+ provider: "postgresql",
+ }),
+
+ emailAndPassword: {
+ enabled: false,
+ },
+
+ socialProviders,
+
+ account: {
+ accountLinking: {
+ enabled: true,
+ trustedProviders: ["google"],
+ },
+ },
+
+ session: {
+ expiresIn: 60 * 60 * 24 * 7,
+ updateAge: 60 * 60 * 24,
+ cookieCache: {
+ enabled: true,
+ maxAge: 5 * 60,
+ },
+ },
+
+ rateLimit: {
+ enabled: true,
+ storage: "database",
+ },
+
+ advanced: {
+ useSecureCookies: env.isProduction,
+ ...(env.cookieDomain && {
+ crossSubDomainCookies: {
+ enabled: true,
+ domain: env.cookieDomain,
+ },
+ }),
+ },
+
+ trustedOrigins: [...env.trustedOrigins],
+ hooks: {},
+ databaseHooks: {},
+});
+
+export type Auth = typeof auth;
+export type Session = typeof auth.$Infer.Session;
+export type SessionUser = Session["user"];
diff --git a/packages/auth/src/client.ts b/packages/auth/src/client.ts
new file mode 100644
index 00000000..149450ee
--- /dev/null
+++ b/packages/auth/src/client.ts
@@ -0,0 +1,9 @@
+import { createAuthClient } from "better-auth/react";
+
+export const authClient = createAuthClient({
+ baseURL: process.env.NEXT_PUBLIC_AUTH_URL,
+});
+
+export const { getSession, signIn, signOut, useSession } = authClient;
+
+export type AuthClient = typeof authClient;
diff --git a/packages/auth/src/env.ts b/packages/auth/src/env.ts
new file mode 100644
index 00000000..c8839989
--- /dev/null
+++ b/packages/auth/src/env.ts
@@ -0,0 +1,37 @@
+const optional = (key: string): string | undefined => {
+ const value = process.env[key];
+ return value && value.length > 0 ? value : undefined;
+};
+
+const googleCredentials = ():
+ | { clientId: string; clientSecret: string }
+ | undefined => {
+ const clientId = optional("GOOGLE_CLIENT_ID");
+ const clientSecret = optional("GOOGLE_CLIENT_SECRET");
+
+ if (!clientId || !clientSecret) {
+ if (clientId || clientSecret) {
+ throw new Error(
+ "GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET must be set together.",
+ );
+ }
+ return undefined;
+ }
+
+ return { clientId, clientSecret };
+};
+
+const trustedOrigins = (
+ optional("AUTH_TRUSTED_ORIGINS")
+ ?.split(",")
+ .map((origin) => origin.trim())
+ .filter(Boolean) ?? []
+).concat(optional("BETTER_AUTH_URL") ?? []);
+
+export const env = {
+ appUrl: optional("BETTER_AUTH_URL"),
+ google: googleCredentials(),
+ cookieDomain: optional("AUTH_COOKIE_DOMAIN"),
+ trustedOrigins: [...new Set(trustedOrigins)],
+ isProduction: process.env.NODE_ENV === "production",
+} as const;
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
new file mode 100644
index 00000000..fa51be9c
--- /dev/null
+++ b/packages/auth/src/index.ts
@@ -0,0 +1 @@
+export { type Auth, auth, type Session, type SessionUser } from "./auth";
diff --git a/packages/auth/tsconfig.json b/packages/auth/tsconfig.json
new file mode 100644
index 00000000..017066e1
--- /dev/null
+++ b/packages/auth/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "@crm/typescript-config/internal-package.json",
+ "compilerOptions": {
+ "jsx": "react-jsx",
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts", "src/**/*.tsx"],
+ "exclude": ["node_modules"]
+}
diff --git a/packages/auth/turbo.json b/packages/auth/turbo.json
new file mode 100644
index 00000000..7160b71b
--- /dev/null
+++ b/packages/auth/turbo.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "https://turborepo.dev/schema.json",
+ "extends": ["//"],
+ "tasks": {
+ "auth:generate": {
+ "cache": false,
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "check-types": {
+ "passThroughEnv": ["DATABASE_URL"]
+ }
+ }
+}
diff --git a/packages/db/.env.example b/packages/db/.env.example
new file mode 100644
index 00000000..dafd9300
--- /dev/null
+++ b/packages/db/.env.example
@@ -0,0 +1,7 @@
+# Connection string used by Prisma CLI (migrate/push/studio) and the runtime client.
+# postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public
+DATABASE_URL="postgresql://postgres:postgres@localhost:5432/crm?schema=public"
+
+# Log every SQL statement Prisma runs (debug level, bound parameters omitted).
+# Off by default: it buries every other log line under a wall of SELECTs.
+# PRISMA_LOG_QUERIES="true"
diff --git a/packages/db/.gitignore b/packages/db/.gitignore
new file mode 100644
index 00000000..bd392e52
--- /dev/null
+++ b/packages/db/.gitignore
@@ -0,0 +1,2 @@
+# Prisma Client is generated from prisma/schema.prisma — never commit it.
+src/generated/
diff --git a/packages/db/README.md b/packages/db/README.md
new file mode 100644
index 00000000..84e9ebd6
--- /dev/null
+++ b/packages/db/README.md
@@ -0,0 +1,68 @@
+# `@crm/db`
+
+PostgreSQL access for the monorepo: the Prisma schema, migrations, and a shared
+`PrismaClient` instance.
+
+## Usage
+
+```ts
+import { db } from "@crm/db";
+
+const users = await db.user.findMany({ take: 10 });
+```
+
+Types and query helpers come from the same entrypoint:
+
+```ts
+import { Prisma, type User } from "@crm/db";
+```
+
+## Setup
+
+```bash
+cp packages/db/.env.example packages/db/.env # then edit DATABASE_URL
+bun run db:generate # generate Prisma Client
+bun run db:deploy # apply the initial migration
+```
+
+`prisma/migrations/20260731150000_init` was generated offline with
+`prisma migrate diff` and has not been applied to any database yet. Delete it
+and run `bun run db:migrate` instead if you would rather let Prisma author the
+first migration against your own database.
+
+`DATABASE_URL` lives in `packages/db/.env` rather than at the repo root so that
+the dependency is explicit and cache invalidation stays scoped to this package.
+
+## Scripts
+
+| Script | Purpose |
+| ------------- | -------------------------------------------------------- |
+| `build` | `prisma generate` — cached by Turborepo, runs via `^build` |
+| `db:generate` | Regenerate Prisma Client |
+| `db:migrate` | Create and apply a migration (development) |
+| `db:deploy` | Apply pending migrations (CI / production) |
+| `db:push` | Push the schema without a migration (prototyping only) |
+| `db:reset` | Drop and recreate the database |
+| `db:seed` | Run `prisma/seed.ts` |
+| `db:studio` | Open Prisma Studio |
+
+Each is also exposed at the repo root (`bun run db:migrate`) and routed through
+`turbo run`.
+
+## Notes
+
+- **Prisma 7 + driver adapter.** There is no query engine binary; the client
+ talks to PostgreSQL through `@prisma/adapter-pg`. See `src/client.ts`.
+- **Generated code is not committed.** `prisma generate` writes to
+ `src/generated/`, which is gitignored and declared as the `build` task's
+ output so Turborepo caches it.
+- **JIT package.** `exports` point at TypeScript sources; the consumer compiles
+ them. Turbopack transpiles workspace packages automatically, so a Next.js app
+ needs no `transpilePackages` entry. Non-bundler consumers need a TypeScript
+ runtime — the NestJS API runs on Bun for exactly this reason.
+- **Auth models are generated.** `User`, `Session`, `Account`, `Verification`
+ and `RateLimit` come from `@better-auth/cli`. Do not hand-edit them — change
+ the Better Auth config in `@crm/auth` and re-run `bun run auth:generate`.
+ The generator is additive: it adds models and fields a plugin needs but never
+ removes the ones a dropped plugin left behind, so removing a plugin means
+ deleting its models from the schema by hand.
diff --git a/packages/db/package.json b/packages/db/package.json
new file mode 100644
index 00000000..4751fad3
--- /dev/null
+++ b/packages/db/package.json
@@ -0,0 +1,38 @@
+{
+ "name": "@crm/db",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client.ts",
+ "./enums": "./src/generated/prisma/enums.ts"
+ },
+ "scripts": {
+ "build": "prisma generate",
+ "check-types": "tsc --noEmit",
+ "db:deploy": "prisma migrate deploy",
+ "db:generate": "prisma generate",
+ "db:migrate": "prisma migrate dev",
+ "db:push": "prisma db push",
+ "db:reset": "prisma migrate reset",
+ "db:seed": "prisma db seed",
+ "db:studio": "prisma studio",
+ "dev": "prisma generate --watch",
+ "lint": "biome check .",
+ "clean": "rm -rf .turbo node_modules src/generated"
+ },
+ "dependencies": {
+ "@prisma/adapter-pg": "^7.9.1",
+ "@prisma/client": "^7.9.1",
+ "pg": "^8.22.0"
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@types/node": "^24.10.1",
+ "@types/pg": "^8.20.0",
+ "dotenv": "^17.2.4",
+ "prisma": "^7.9.1",
+ "typescript": "5.9.2"
+ }
+}
diff --git a/packages/db/prisma.config.ts b/packages/db/prisma.config.ts
new file mode 100644
index 00000000..89fcd28f
--- /dev/null
+++ b/packages/db/prisma.config.ts
@@ -0,0 +1,15 @@
+import "dotenv/config";
+
+import path from "node:path";
+import { defineConfig, env } from "prisma/config";
+
+export default defineConfig({
+ schema: path.join("prisma", "schema.prisma"),
+ migrations: {
+ path: path.join("prisma", "migrations"),
+ seed: "bun run prisma/seed.ts",
+ },
+ datasource: {
+ url: env("DATABASE_URL"),
+ },
+});
diff --git a/packages/db/prisma/migrations/20260731150000_init/migration.sql b/packages/db/prisma/migrations/20260731150000_init/migration.sql
new file mode 100644
index 00000000..1438d748
--- /dev/null
+++ b/packages/db/prisma/migrations/20260731150000_init/migration.sql
@@ -0,0 +1,159 @@
+-- CreateSchema
+CREATE SCHEMA IF NOT EXISTS "public";
+
+-- CreateTable
+CREATE TABLE "user" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "email" TEXT NOT NULL,
+ "emailVerified" BOOLEAN NOT NULL DEFAULT false,
+ "image" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "user_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "session" (
+ "id" TEXT NOT NULL,
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+ "token" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ "ipAddress" TEXT,
+ "userAgent" TEXT,
+ "userId" TEXT NOT NULL,
+ "activeOrganizationId" TEXT,
+
+ CONSTRAINT "session_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "account" (
+ "id" TEXT NOT NULL,
+ "accountId" TEXT NOT NULL,
+ "providerId" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "accessToken" TEXT,
+ "refreshToken" TEXT,
+ "idToken" TEXT,
+ "accessTokenExpiresAt" TIMESTAMP(3),
+ "refreshTokenExpiresAt" TIMESTAMP(3),
+ "scope" TEXT,
+ "password" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "account_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "verification" (
+ "id" TEXT NOT NULL,
+ "identifier" TEXT NOT NULL,
+ "value" TEXT NOT NULL,
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "verification_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "organization" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "slug" TEXT NOT NULL,
+ "logo" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL,
+ "metadata" TEXT,
+
+ CONSTRAINT "organization_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "member" (
+ "id" TEXT NOT NULL,
+ "organizationId" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "role" TEXT NOT NULL DEFAULT 'member',
+ "createdAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "member_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "invitation" (
+ "id" TEXT NOT NULL,
+ "organizationId" TEXT NOT NULL,
+ "email" TEXT NOT NULL,
+ "role" TEXT,
+ "status" TEXT NOT NULL DEFAULT 'pending',
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "inviterId" TEXT NOT NULL,
+
+ CONSTRAINT "invitation_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "rateLimit" (
+ "id" TEXT NOT NULL,
+ "key" TEXT NOT NULL,
+ "count" INTEGER NOT NULL,
+ "lastRequest" BIGINT NOT NULL,
+
+ CONSTRAINT "rateLimit_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "user_email_key" ON "user"("email");
+
+-- CreateIndex
+CREATE INDEX "session_userId_idx" ON "session"("userId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "session_token_key" ON "session"("token");
+
+-- CreateIndex
+CREATE INDEX "account_userId_idx" ON "account"("userId");
+
+-- CreateIndex
+CREATE INDEX "verification_identifier_idx" ON "verification"("identifier");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "organization_slug_key" ON "organization"("slug");
+
+-- CreateIndex
+CREATE INDEX "member_organizationId_idx" ON "member"("organizationId");
+
+-- CreateIndex
+CREATE INDEX "member_userId_idx" ON "member"("userId");
+
+-- CreateIndex
+CREATE INDEX "invitation_organizationId_idx" ON "invitation"("organizationId");
+
+-- CreateIndex
+CREATE INDEX "invitation_email_idx" ON "invitation"("email");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "rateLimit_key_key" ON "rateLimit"("key");
+
+-- AddForeignKey
+ALTER TABLE "session" ADD CONSTRAINT "session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "account" ADD CONSTRAINT "account_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "member" ADD CONSTRAINT "member_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "member" ADD CONSTRAINT "member_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "invitation" ADD CONSTRAINT "invitation_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "invitation" ADD CONSTRAINT "invitation_inviterId_fkey" FOREIGN KEY ("inviterId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/20260731160000_remove_organizations/migration.sql b/packages/db/prisma/migrations/20260731160000_remove_organizations/migration.sql
new file mode 100644
index 00000000..cf9ced53
--- /dev/null
+++ b/packages/db/prisma/migrations/20260731160000_remove_organizations/migration.sql
@@ -0,0 +1,26 @@
+-- The `organization` Better Auth plugin has been removed: this is a
+-- single-tenant internal app, so memberships and invitations no longer exist.
+
+-- DropForeignKey
+ALTER TABLE "invitation" DROP CONSTRAINT IF EXISTS "invitation_inviterId_fkey";
+
+-- DropForeignKey
+ALTER TABLE "invitation" DROP CONSTRAINT IF EXISTS "invitation_organizationId_fkey";
+
+-- DropForeignKey
+ALTER TABLE "member" DROP CONSTRAINT IF EXISTS "member_organizationId_fkey";
+
+-- DropForeignKey
+ALTER TABLE "member" DROP CONSTRAINT IF EXISTS "member_userId_fkey";
+
+-- DropTable
+DROP TABLE IF EXISTS "invitation";
+
+-- DropTable
+DROP TABLE IF EXISTS "member";
+
+-- DropTable
+DROP TABLE IF EXISTS "organization";
+
+-- AlterTable
+ALTER TABLE "session" DROP COLUMN IF EXISTS "activeOrganizationId";
diff --git a/packages/db/prisma/migrations/20260731164536_add_crm_models/migration.sql b/packages/db/prisma/migrations/20260731164536_add_crm_models/migration.sql
new file mode 100644
index 00000000..a9947b56
--- /dev/null
+++ b/packages/db/prisma/migrations/20260731164536_add_crm_models/migration.sql
@@ -0,0 +1,208 @@
+-- CreateEnum
+CREATE TYPE "DealStage" AS ENUM ('DEMO_BOOKED', 'QUALIFIED_TO_BUY', 'UNQUALIFIED_TO_BUY', 'DECISION_MAKER_BOUGHT_IN', 'CONTRACT_SENT', 'CLOSED_WON', 'CLOSED_LOST');
+
+-- CreateEnum
+CREATE TYPE "ActivityType" AS ENUM ('NOTE', 'CALL', 'EMAIL', 'MEETING', 'TASK', 'STAGE_CHANGE', 'ENRICHMENT');
+
+-- CreateEnum
+CREATE TYPE "EnrichmentStatus" AS ENUM ('PENDING', 'RUNNING', 'COMPLETE', 'FAILED', 'SKIPPED');
+
+-- CreateTable
+CREATE TABLE "company" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "domain" TEXT,
+ "website" TEXT,
+ "description" TEXT,
+ "logoUrl" TEXT,
+ "logoDarkUrl" TEXT,
+ "iconUrl" TEXT,
+ "brandColor" TEXT,
+ "industry" TEXT,
+ "subIndustry" TEXT,
+ "city" TEXT,
+ "stateCode" TEXT,
+ "country" TEXT,
+ "countryCode" TEXT,
+ "phone" TEXT,
+ "email" TEXT,
+ "linkedinUrl" TEXT,
+ "twitterUrl" TEXT,
+ "githubUrl" TEXT,
+ "pricingUrl" TEXT,
+ "careersUrl" TEXT,
+ "ownerId" TEXT,
+ "primaryContactId" TEXT,
+ "enrichmentStatus" "EnrichmentStatus" NOT NULL DEFAULT 'PENDING',
+ "enrichedAt" TIMESTAMP(3),
+ "enrichmentError" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "company_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "companyEnrichment" (
+ "companyId" TEXT NOT NULL,
+ "source" TEXT NOT NULL DEFAULT 'context.dev',
+ "raw" JSONB NOT NULL,
+ "fetchedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "companyEnrichment_pkey" PRIMARY KEY ("companyId")
+);
+
+-- CreateTable
+CREATE TABLE "contact" (
+ "id" TEXT NOT NULL,
+ "firstName" TEXT NOT NULL,
+ "lastName" TEXT,
+ "email" TEXT,
+ "phone" TEXT,
+ "title" TEXT,
+ "linkedinUrl" TEXT,
+ "companyId" TEXT,
+ "ownerId" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "contact_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "deal" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "ownerId" TEXT NOT NULL,
+ "stage" "DealStage" NOT NULL DEFAULT 'DEMO_BOOKED',
+ "stageChangedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "amount" DECIMAL(14,2),
+ "currency" TEXT NOT NULL DEFAULT 'USD',
+ "expectedCloseDate" TIMESTAMP(3),
+ "closedAt" TIMESTAMP(3),
+ "closedReason" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "deal_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "dealContact" (
+ "dealId" TEXT NOT NULL,
+ "contactId" TEXT NOT NULL,
+ "role" TEXT,
+
+ CONSTRAINT "dealContact_pkey" PRIMARY KEY ("dealId","contactId")
+);
+
+-- CreateTable
+CREATE TABLE "activity" (
+ "id" TEXT NOT NULL,
+ "type" "ActivityType" NOT NULL,
+ "subject" TEXT,
+ "body" TEXT,
+ "occurredAt" TIMESTAMP(3),
+ "dueAt" TIMESTAMP(3),
+ "completedAt" TIMESTAMP(3),
+ "companyId" TEXT,
+ "contactId" TEXT,
+ "dealId" TEXT,
+ "createdById" TEXT NOT NULL,
+ "meta" JSONB,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "activity_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "company_domain_key" ON "company"("domain");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "company_primaryContactId_key" ON "company"("primaryContactId");
+
+-- CreateIndex
+CREATE INDEX "company_ownerId_idx" ON "company"("ownerId");
+
+-- CreateIndex
+CREATE INDEX "company_name_idx" ON "company"("name");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "contact_email_key" ON "contact"("email");
+
+-- CreateIndex
+CREATE INDEX "contact_companyId_idx" ON "contact"("companyId");
+
+-- CreateIndex
+CREATE INDEX "contact_ownerId_idx" ON "contact"("ownerId");
+
+-- CreateIndex
+CREATE INDEX "deal_companyId_idx" ON "deal"("companyId");
+
+-- CreateIndex
+CREATE INDEX "deal_ownerId_idx" ON "deal"("ownerId");
+
+-- CreateIndex
+CREATE INDEX "deal_stage_idx" ON "deal"("stage");
+
+-- CreateIndex
+CREATE INDEX "deal_expectedCloseDate_idx" ON "deal"("expectedCloseDate");
+
+-- CreateIndex
+CREATE INDEX "dealContact_contactId_idx" ON "dealContact"("contactId");
+
+-- CreateIndex
+CREATE INDEX "activity_companyId_createdAt_idx" ON "activity"("companyId", "createdAt");
+
+-- CreateIndex
+CREATE INDEX "activity_dealId_createdAt_idx" ON "activity"("dealId", "createdAt");
+
+-- CreateIndex
+CREATE INDEX "activity_contactId_createdAt_idx" ON "activity"("contactId", "createdAt");
+
+-- CreateIndex
+CREATE INDEX "activity_dueAt_idx" ON "activity"("dueAt");
+
+-- CreateIndex
+CREATE INDEX "activity_createdById_idx" ON "activity"("createdById");
+
+-- AddForeignKey
+ALTER TABLE "company" ADD CONSTRAINT "company_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "company" ADD CONSTRAINT "company_primaryContactId_fkey" FOREIGN KEY ("primaryContactId") REFERENCES "contact"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "companyEnrichment" ADD CONSTRAINT "companyEnrichment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "contact" ADD CONSTRAINT "contact_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "contact" ADD CONSTRAINT "contact_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "deal" ADD CONSTRAINT "deal_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "deal" ADD CONSTRAINT "deal_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "dealContact" ADD CONSTRAINT "dealContact_dealId_fkey" FOREIGN KEY ("dealId") REFERENCES "deal"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "dealContact" ADD CONSTRAINT "dealContact_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "activity" ADD CONSTRAINT "activity_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "activity" ADD CONSTRAINT "activity_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "activity" ADD CONSTRAINT "activity_dealId_fkey" FOREIGN KEY ("dealId") REFERENCES "deal"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "activity" ADD CONSTRAINT "activity_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/migration_lock.toml b/packages/db/prisma/migrations/migration_lock.toml
new file mode 100644
index 00000000..044d57cd
--- /dev/null
+++ b/packages/db/prisma/migrations/migration_lock.toml
@@ -0,0 +1,3 @@
+# Please do not edit this file manually
+# It should be added in your version-control system (e.g., Git)
+provider = "postgresql"
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
new file mode 100644
index 00000000..00b96447
--- /dev/null
+++ b/packages/db/prisma/schema.prisma
@@ -0,0 +1,306 @@
+
+datasource db {
+ provider = "postgresql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../src/generated/prisma"
+ runtime = "nodejs"
+ moduleFormat = "esm"
+ generatedFileExtension = "ts"
+ importFileExtension = ""
+}
+
+model User {
+ id String @id
+ name String
+ email String
+ emailVerified Boolean @default(false)
+ image String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ sessions Session[]
+ accounts Account[]
+
+ // CRM ownership. Better Auth owns every field above and `bun run
+ // auth:generate` rewrites them; these back-relations are ours and have to be
+ // put back if that ever wipes them.
+ ownedCompanies Company[] @relation("CompanyOwner")
+ ownedContacts Contact[] @relation("ContactOwner")
+ ownedDeals Deal[] @relation("DealOwner")
+ activities Activity[] @relation("ActivityAuthor")
+
+ @@unique([email])
+ @@map("user")
+}
+
+model Session {
+ id String @id
+ expiresAt DateTime
+ token String
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ ipAddress String?
+ userAgent String?
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ @@unique([token])
+ @@index([userId])
+ @@map("session")
+}
+
+model Account {
+ id String @id
+ accountId String
+ providerId String
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ accessToken String?
+ refreshToken String?
+ idToken String?
+ accessTokenExpiresAt DateTime?
+ refreshTokenExpiresAt DateTime?
+ scope String?
+ password String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([userId])
+ @@map("account")
+}
+
+model Verification {
+ id String @id
+ identifier String
+ value String
+ expiresAt DateTime
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([identifier])
+ @@map("verification")
+}
+
+model RateLimit {
+ id String @id
+ key String
+ count Int
+ lastRequest BigInt
+
+ @@unique([key])
+ @@map("rateLimit")
+}
+
+// ---------------------------------------------------------------------------
+// CRM
+//
+// Companies are the top-level object; contacts and deals hang off them, and
+// everything that happens is an Activity on a timeline.
+// ---------------------------------------------------------------------------
+
+enum DealStage {
+ DEMO_BOOKED
+ QUALIFIED_TO_BUY
+ /// Terminal, not a step forward — disqualified, and excluded from pipeline value.
+ UNQUALIFIED_TO_BUY
+ DECISION_MAKER_BOUGHT_IN
+ CONTRACT_SENT
+ CLOSED_WON
+ CLOSED_LOST
+}
+
+enum ActivityType {
+ NOTE
+ CALL
+ EMAIL
+ MEETING
+ TASK
+ /// Written by the system when Deal.stage changes.
+ STAGE_CHANGE
+ /// Written by the enrichment agent.
+ ENRICHMENT
+}
+
+enum EnrichmentStatus {
+ PENDING
+ RUNNING
+ COMPLETE
+ /// The lookup failed and is worth retrying — see Company.enrichmentError.
+ FAILED
+ /// There is nothing to find (unknown domain, free email host). Not an error.
+ SKIPPED
+}
+
+model Company {
+ id String @id @default(cuid())
+ name String
+ /// Bare and normalised ("stripe.com"). Unique because two records for one
+ /// domain is the fastest way to rot a CRM, and it is the enrichment key.
+ domain String? @unique
+ website String?
+ description String?
+
+ // Brand, from Context.dev.
+ logoUrl String?
+ logoDarkUrl String?
+ /// Square mark, used in table rows.
+ iconUrl String?
+ /// Hex. An accent only — brand colours would fight the design tokens.
+ brandColor String?
+
+ // Firmographics.
+ industry String?
+ subIndustry String?
+ city String?
+ stateCode String?
+ country String?
+ countryCode String?
+
+ // Contact details and socials.
+ phone String?
+ email String?
+ linkedinUrl String?
+ twitterUrl String?
+ githubUrl String?
+ pricingUrl String?
+ careersUrl String?
+
+ ownerId String?
+ owner User? @relation("CompanyOwner", fields: [ownerId], references: [id], onDelete: SetNull)
+ primaryContactId String? @unique
+ primaryContact Contact? @relation("PrimaryContact", fields: [primaryContactId], references: [id], onDelete: SetNull)
+
+ enrichmentStatus EnrichmentStatus @default(PENDING)
+ enrichedAt DateTime?
+ enrichmentError String?
+ enrichment CompanyEnrichment?
+
+ contacts Contact[] @relation("CompanyContacts")
+ deals Deal[]
+ activities Activity[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([ownerId])
+ @@index([name])
+ @@map("company")
+}
+
+/// The raw Context.dev payload, kept so re-deriving a field costs nothing and
+/// no credits.
+model CompanyEnrichment {
+ companyId String @id
+ company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ source String @default("context.dev")
+ raw Json
+ fetchedAt DateTime @default(now())
+
+ @@map("companyEnrichment")
+}
+
+model Contact {
+ id String @id @default(cuid())
+ firstName String
+ lastName String?
+ /// Unique, matching HubSpot, so a CSV import can be re-run safely. The cost:
+ /// two people behind one info@ address need one email between them.
+ email String? @unique
+ phone String?
+ title String?
+ linkedinUrl String?
+ companyId String?
+ company Company? @relation("CompanyContacts", fields: [companyId], references: [id], onDelete: SetNull)
+ ownerId String?
+ owner User? @relation("ContactOwner", fields: [ownerId], references: [id], onDelete: SetNull)
+ primaryOf Company? @relation("PrimaryContact")
+
+ deals DealContact[]
+ activities Activity[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([companyId])
+ @@index([ownerId])
+ @@map("contact")
+}
+
+model Deal {
+ id String @id @default(cuid())
+ name String
+ companyId String
+ company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ /// Required: every deal has a name against it.
+ ownerId String
+ owner User @relation("DealOwner", fields: [ownerId], references: [id])
+
+ stage DealStage @default(DEMO_BOOKED)
+ stageChangedAt DateTime @default(now())
+ amount Decimal? @db.Decimal(14, 2)
+ currency String @default("USD")
+ expectedCloseDate DateTime?
+ closedAt DateTime?
+ closedReason String?
+
+ contacts DealContact[]
+ activities Activity[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([companyId])
+ @@index([ownerId])
+ @@index([stage])
+ @@index([expectedCloseDate])
+ @@map("deal")
+}
+
+model DealContact {
+ dealId String
+ deal Deal @relation(fields: [dealId], references: [id], onDelete: Cascade)
+ contactId String
+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ role String?
+
+ @@id([dealId, contactId])
+ @@index([contactId])
+ @@map("dealContact")
+}
+
+model Activity {
+ id String @id @default(cuid())
+ type ActivityType
+ subject String?
+ body String?
+
+ /// Set when the thing already happened.
+ occurredAt DateTime?
+ /// Set when it is scheduled. Overdue is dueAt in the past with no completedAt.
+ dueAt DateTime?
+ completedAt DateTime?
+
+ /// Always stamped when it can be resolved, even for deal and contact
+ /// activity, so a company timeline is one indexed range scan rather than
+ /// three joins.
+ companyId String?
+ company Company? @relation(fields: [companyId], references: [id], onDelete: Cascade)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ dealId String?
+ deal Deal? @relation(fields: [dealId], references: [id], onDelete: Cascade)
+
+ createdById String
+ createdBy User @relation("ActivityAuthor", fields: [createdById], references: [id])
+ /// { from, to } for STAGE_CHANGE; the credit cost for ENRICHMENT.
+ meta Json?
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([companyId, createdAt])
+ @@index([dealId, createdAt])
+ @@index([contactId, createdAt])
+ @@index([dueAt])
+ @@index([createdById])
+ @@map("activity")
+}
diff --git a/packages/db/prisma/seed.ts b/packages/db/prisma/seed.ts
new file mode 100644
index 00000000..2b9cea66
--- /dev/null
+++ b/packages/db/prisma/seed.ts
@@ -0,0 +1,688 @@
+import { db } from "../src/client";
+import { ActivityType, DealStage } from "../src/generated/prisma/enums";
+
+/**
+ * A believable pipeline to develop against: real domains so the enrichment
+ * agent has something to look up, deals spread across every stage, and tasks
+ * that are genuinely overdue.
+ *
+ * Idempotent — companies key off `domain`, contacts off `email`, and deals off
+ * a deterministic id — so re-running tops the data up rather than duplicating
+ * it. Randomness comes from a seeded generator for the same reason: two runs
+ * produce the same pipeline.
+ *
+ * Users are the exception. Better Auth owns them, and a row written here has no
+ * Google account attached — but account linking is enabled for Google, so
+ * signing in with a matching address adopts the row rather than creating a
+ * second one. Real users are used when they exist; the placeholders below are
+ * only created when the table is empty.
+ */
+
+// --- deterministic randomness -----------------------------------------------
+
+/** mulberry32 — small, fast, and identical across runs. */
+function makeRandom(seed: number): () => number {
+ let a = seed;
+ return () => {
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+const random = makeRandom(20260731);
+
+function pick<T>(items: readonly T[]): T {
+ const item = items[Math.floor(random() * items.length)];
+ if (item === undefined) throw new Error("pick() on an empty list");
+ return item;
+}
+
+function chance(probability: number): boolean {
+ return random() < probability;
+}
+
+function integer(min: number, max: number): number {
+ return min + Math.floor(random() * (max - min + 1));
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const NOW = Date.now();
+
+/** Negative is the past. */
+function daysFromNow(days: number, jitterHours = 0): Date {
+ const jitter = jitterHours
+ ? (random() - 0.5) * jitterHours * 60 * 60 * 1000
+ : 0;
+ return new Date(NOW + days * DAY_MS + jitter);
+}
+
+// --- source data ------------------------------------------------------------
+
+const OWNERS = [
+ { name: "Ada Okafor", email: "[email protected]" },
+ { name: "Marcus Lindqvist", email: "[email protected]" },
+ { name: "Priya Raman", email: "[email protected]" },
+] as const;
+
+type SeedCompany = {
+ name: string;
+ domain: string;
+ industry: string;
+ city: string;
+ country: string;
+ countryCode: string;
+};
+
+const COMPANIES: readonly SeedCompany[] = [
+ {
+ name: "Stripe",
+ domain: "stripe.com",
+ industry: "Financial Services",
+ city: "San Francisco",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Linear",
+ domain: "linear.app",
+ industry: "Software",
+ city: "San Francisco",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Vercel",
+ domain: "vercel.com",
+ industry: "Software",
+ city: "San Francisco",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Ramp",
+ domain: "ramp.com",
+ industry: "Financial Services",
+ city: "New York",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Notion",
+ domain: "notion.so",
+ industry: "Software",
+ city: "San Francisco",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Monzo",
+ domain: "monzo.com",
+ industry: "Banking",
+ city: "London",
+ country: "United Kingdom",
+ countryCode: "GB",
+ },
+ {
+ name: "Wise",
+ domain: "wise.com",
+ industry: "Financial Services",
+ city: "London",
+ country: "United Kingdom",
+ countryCode: "GB",
+ },
+ {
+ name: "Personio",
+ domain: "personio.com",
+ industry: "Human Resources",
+ city: "Munich",
+ country: "Germany",
+ countryCode: "DE",
+ },
+ {
+ name: "Pennylane",
+ domain: "pennylane.com",
+ industry: "Accounting",
+ city: "Paris",
+ country: "France",
+ countryCode: "FR",
+ },
+ {
+ name: "Cal.com",
+ domain: "cal.com",
+ industry: "Software",
+ city: "San Francisco",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Supabase",
+ domain: "supabase.com",
+ industry: "Software",
+ city: "Singapore",
+ country: "Singapore",
+ countryCode: "SG",
+ },
+ {
+ name: "Retool",
+ domain: "retool.com",
+ industry: "Software",
+ city: "San Francisco",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Deel",
+ domain: "deel.com",
+ industry: "Human Resources",
+ city: "New York",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Mercury",
+ domain: "mercury.com",
+ industry: "Banking",
+ city: "San Francisco",
+ country: "United States",
+ countryCode: "US",
+ },
+ {
+ name: "Attio",
+ domain: "attio.com",
+ industry: "Software",
+ city: "London",
+ country: "United Kingdom",
+ countryCode: "GB",
+ },
+];
+
+const FIRST_NAMES = [
+ "Amara",
+ "Ben",
+ "Chidi",
+ "Dana",
+ "Elias",
+ "Farah",
+ "Gus",
+ "Hana",
+ "Ines",
+ "Jonas",
+ "Kofi",
+ "Lena",
+ "Mateo",
+ "Nadia",
+ "Omar",
+ "Pia",
+ "Quinn",
+ "Rosa",
+ "Sami",
+ "Tara",
+ "Ugo",
+ "Vera",
+ "Wes",
+ "Yuki",
+] as const;
+
+const LAST_NAMES = [
+ "Adeyemi",
+ "Bergström",
+ "Chen",
+ "Dubois",
+ "Eriksen",
+ "Fontaine",
+ "Gupta",
+ "Haddad",
+ "Ivanova",
+ "Jensen",
+ "Kowalski",
+ "Lombardi",
+ "Moreau",
+ "Nakamura",
+ "Oyelaran",
+ "Petrov",
+ "Quintana",
+ "Rossi",
+ "Sørensen",
+ "Takahashi",
+] as const;
+
+const TITLES = [
+ "Head of Security",
+ "CTO",
+ "VP Engineering",
+ "Compliance Manager",
+ "Head of Legal",
+ "Security Engineer",
+ "COO",
+ "IT Director",
+ "Head of Platform",
+ "Chief of Staff",
+] as const;
+
+const OPEN_STAGES = [
+ DealStage.DEMO_BOOKED,
+ DealStage.QUALIFIED_TO_BUY,
+ DealStage.DECISION_MAKER_BOUGHT_IN,
+ DealStage.CONTRACT_SENT,
+] as const;
+
+const CLOSED_STAGES = [
+ DealStage.CLOSED_WON,
+ DealStage.CLOSED_LOST,
+ DealStage.UNQUALIFIED_TO_BUY,
+] as const;
+
+const LOST_REASONS = [
+ "Went with an incumbent vendor",
+ "No budget this cycle",
+ "Timeline slipped to next year",
+ "Not a fit — no compliance requirement yet",
+] as const;
+
+const NOTE_BODIES = [
+ "Ran through the SOC 2 timeline. They want evidence collection automated before the audit window opens.",
+ "Procurement wants a security questionnaire back before they will look at pricing.",
+ "Champion is keen, but the budget owner has not been in a call yet.",
+ "They are evaluating us against two others. Differentiator is the agent, not the checklist.",
+ "Asked for a reference in the same vertical. Following up with marketing.",
+ "Pushed the decision to after their board meeting.",
+] as const;
+
+const CALL_SUBJECTS = [
+ "Discovery call",
+ "Technical deep dive",
+ "Pricing discussion",
+ "Follow-up call",
+ "Security review",
+] as const;
+
+const TASK_SUBJECTS = [
+ "Send the security questionnaire",
+ "Share pricing proposal",
+ "Book the technical deep dive",
+ "Chase procurement",
+ "Send SOC 2 report",
+ "Introduce the implementation team",
+] as const;
+
+const MEETING_SUBJECTS = [
+ "Product demo",
+ "Onboarding walkthrough",
+ "Quarterly check-in",
+ "Stakeholder alignment",
+] as const;
+
+const EMAIL_SUBJECTS = [
+ "Re: next steps",
+ "Following up after the demo",
+ "Pricing and terms",
+ "Intro to your implementation lead",
+] as const;
+
+// --- helpers ----------------------------------------------------------------
+
+/** Letters NFD cannot decompose into base + accent — they are their own letter. */
+const TRANSLITERATIONS: Record<string, string> = {
+ ø: "o",
+ æ: "ae",
+ œ: "oe",
+ å: "a",
+ ß: "ss",
+ đ: "d",
+ ł: "l",
+ þ: "th",
+};
+
+function slug(value: string): string {
+ return (
+ value
+ .toLowerCase()
+ .replace(/[øæœåßđłþ]/g, (char) => TRANSLITERATIONS[char] ?? char)
+ .normalize("NFD")
+ // Combining marks left behind by NFD (é → e + ́ ).
+ .replace(/\p{Mn}/gu, "")
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "")
+ );
+}
+
+// --- seed -------------------------------------------------------------------
+
+async function seedOwners(): Promise<string[]> {
+ const existing = await db.user.findMany({ select: { id: true } });
+
+ if (existing.length > 0) {
+ console.log(`Using ${existing.length} existing user(s) as owners.`);
+ return existing.map((user) => user.id);
+ }
+
+ console.log("No users yet — creating placeholder sales reps.");
+ const created = await Promise.all(
+ OWNERS.map((owner) =>
+ db.user.upsert({
+ where: { email: owner.email },
+ create: {
+ id: `seed-${slug(owner.name)}`,
+ name: owner.name,
+ email: owner.email,
+ emailVerified: true,
+ updatedAt: new Date(),
+ },
+ update: {},
+ select: { id: true },
+ }),
+ ),
+ );
+
+ return created.map((user) => user.id);
+}
+
+async function seedCompanies(
+ ownerIds: string[],
+): Promise<{ id: string; name: string; domain: string }[]> {
+ const companies = [];
+
+ for (const company of COMPANIES) {
+ const row = await db.company.upsert({
+ where: { domain: company.domain },
+ create: {
+ name: company.name,
+ domain: company.domain,
+ website: `https://${company.domain}`,
+ industry: company.industry,
+ city: company.city,
+ country: company.country,
+ countryCode: company.countryCode,
+ ownerId: pick(ownerIds),
+ // Left PENDING on purpose: the logo, description and socials are the
+ // agent's job, and this gives it real work on first run.
+ createdAt: daysFromNow(-integer(30, 400), 12),
+ },
+ update: {},
+ select: { id: true, name: true, domain: true },
+ });
+ companies.push({ ...row, domain: row.domain ?? company.domain });
+ }
+
+ return companies;
+}
+
+type SeededContact = { id: string; companyId: string };
+
+async function seedContacts(
+ companies: { id: string; domain: string }[],
+ ownerIds: string[],
+): Promise<SeededContact[]> {
+ const contacts: SeededContact[] = [];
+ const used = new Set<string>();
+
+ // A handful per company: a primary contact plus the stakeholders a real deal
+ // drags in.
+ for (const company of companies) {
+ for (let index = 0; index < integer(2, 4); index++) {
+ const firstName = pick(FIRST_NAMES);
+ const lastName = pick(LAST_NAMES);
+ const email = `${slug(firstName)}.${slug(lastName)}@${company.domain}`;
+ if (used.has(email)) continue;
+ used.add(email);
+
+ const contact = await db.contact.upsert({
+ where: { email },
+ create: {
+ firstName,
+ lastName,
+ email,
+ title: pick(TITLES),
+ phone: chance(0.4) ? `+1 415 555 ${integer(1000, 9999)}` : null,
+ companyId: company.id,
+ ownerId: pick(ownerIds),
+ createdAt: daysFromNow(-integer(10, 300), 12),
+ },
+ update: {},
+ select: { id: true },
+ });
+
+ contacts.push({ id: contact.id, companyId: company.id });
+ }
+ }
+
+ // The first contact at each company is the one to call.
+ for (const company of companies) {
+ const first = contacts.find((contact) => contact.companyId === company.id);
+ if (!first) continue;
+ await db.company.update({
+ where: { id: company.id },
+ data: { primaryContactId: first.id },
+ });
+ }
+
+ return contacts;
+}
+
+type SeededDeal = {
+ id: string;
+ companyId: string;
+ ownerId: string;
+ closed: boolean;
+};
+
+async function seedDeals(
+ companies: { id: string; name: string }[],
+ contacts: SeededContact[],
+ ownerIds: string[],
+): Promise<SeededDeal[]> {
+ const deals: SeededDeal[] = [];
+
+ for (const [index, company] of companies.entries()) {
+ // Every company has a deal; about half also have an expansion.
+ const count = index % 2 === 0 ? 2 : 1;
+
+ for (let n = 0; n < count; n++) {
+ const id = `seed-deal-${slug(company.name)}-${n}`;
+ const closed = chance(0.35);
+ const stage = closed ? pick(CLOSED_STAGES) : pick(OPEN_STAGES);
+ const ownerId = pick(ownerIds);
+ const createdAt = daysFromNow(-integer(20, 200), 12);
+ const stageChangedAt = daysFromNow(-integer(1, 20), 12);
+
+ await db.deal.upsert({
+ where: { id },
+ create: {
+ id,
+ name:
+ n === 0
+ ? `${company.name} — Comp AI`
+ : `${company.name} — expansion`,
+ companyId: company.id,
+ ownerId,
+ stage,
+ stageChangedAt,
+ amount: integer(6, 90) * 1000,
+ currency: "USD",
+ expectedCloseDate: daysFromNow(
+ closed ? -integer(1, 60) : integer(-10, 75),
+ ),
+ closedAt: closed ? stageChangedAt : null,
+ closedReason:
+ stage === DealStage.CLOSED_LOST ||
+ stage === DealStage.UNQUALIFIED_TO_BUY
+ ? pick(LOST_REASONS)
+ : null,
+ createdAt,
+ },
+ update: {},
+ });
+
+ // One or two people from the company are on the deal.
+ const companyContacts = contacts.filter(
+ (contact) => contact.companyId === company.id,
+ );
+ for (const contact of companyContacts.slice(0, integer(1, 2))) {
+ await db.dealContact.upsert({
+ where: { dealId_contactId: { dealId: id, contactId: contact.id } },
+ create: {
+ dealId: id,
+ contactId: contact.id,
+ role: chance(0.5) ? "Champion" : "Decision maker",
+ },
+ update: {},
+ });
+ }
+
+ deals.push({ id, companyId: company.id, ownerId, closed });
+ }
+ }
+
+ return deals;
+}
+
+async function seedActivities(
+ companies: { id: string }[],
+ contacts: SeededContact[],
+ deals: SeededDeal[],
+ ownerIds: string[],
+): Promise<number> {
+ // Re-running should not stack another 150 rows on top.
+ const existing = await db.activity.count();
+ if (existing > 0) {
+ console.log(`Activities already seeded (${existing}) — skipping.`);
+ return existing;
+ }
+
+ type ActivityRow = {
+ type: ActivityType;
+ subject: string | null;
+ body: string | null;
+ occurredAt: Date | null;
+ dueAt: Date | null;
+ completedAt: Date | null;
+ companyId: string | null;
+ contactId: string | null;
+ dealId: string | null;
+ createdById: string;
+ createdAt: Date;
+ meta?: { from: DealStage; to: DealStage };
+ };
+
+ const rows: ActivityRow[] = [];
+
+ const base = (companyId: string, createdById: string, createdAt: Date) => ({
+ companyId,
+ contactId: null,
+ dealId: null,
+ occurredAt: null,
+ dueAt: null,
+ completedAt: null,
+ subject: null,
+ body: null,
+ createdById,
+ createdAt,
+ });
+
+ // History on every deal: the calls, notes and emails that got it here.
+ for (const deal of deals) {
+ const dealContacts = contacts.filter((c) => c.companyId === deal.companyId);
+
+ for (let n = 0; n < integer(3, 6); n++) {
+ const at = daysFromNow(-integer(2, 120), 18);
+ const type = pick([
+ ActivityType.NOTE,
+ ActivityType.CALL,
+ ActivityType.EMAIL,
+ ActivityType.MEETING,
+ ]);
+
+ rows.push({
+ ...base(deal.companyId, deal.ownerId, at),
+ type,
+ // The company id is stamped above so this shows on the company
+ // timeline as well as the deal's.
+ dealId: deal.id,
+ contactId: dealContacts.length > 0 ? pick(dealContacts).id : null,
+ subject:
+ type === ActivityType.CALL
+ ? pick(CALL_SUBJECTS)
+ : type === ActivityType.MEETING
+ ? pick(MEETING_SUBJECTS)
+ : type === ActivityType.EMAIL
+ ? pick(EMAIL_SUBJECTS)
+ : null,
+ body: type === ActivityType.NOTE ? pick(NOTE_BODIES) : null,
+ occurredAt: type === ActivityType.NOTE ? null : at,
+ });
+ }
+
+ // The stage change that landed it where it is.
+ rows.push({
+ ...base(deal.companyId, deal.ownerId, daysFromNow(-integer(1, 20), 12)),
+ type: ActivityType.STAGE_CHANGE,
+ dealId: deal.id,
+ subject: "Stage changed",
+ meta: {
+ from: DealStage.DEMO_BOOKED,
+ to: deal.closed ? DealStage.CLOSED_WON : DealStage.QUALIFIED_TO_BUY,
+ },
+ });
+ }
+
+ // Tasks: a spread of done, upcoming and overdue, so the dashboard has all
+ // three to show on the first run.
+ for (const deal of deals) {
+ if (deal.closed) continue;
+
+ for (let n = 0; n < integer(1, 3); n++) {
+ const roll = random();
+ const overdue = roll < 0.3;
+ const done = roll >= 0.3 && roll < 0.6;
+ const dueAt = overdue
+ ? daysFromNow(-integer(1, 14), 6)
+ : daysFromNow(integer(1, 21), 6);
+
+ rows.push({
+ ...base(deal.companyId, deal.ownerId, daysFromNow(-integer(1, 30), 12)),
+ type: ActivityType.TASK,
+ dealId: deal.id,
+ subject: pick(TASK_SUBJECTS),
+ dueAt: done ? daysFromNow(-integer(1, 20), 6) : dueAt,
+ completedAt: done ? daysFromNow(-integer(1, 10), 6) : null,
+ });
+ }
+ }
+
+ // A few notes that belong to the company rather than any one deal.
+ for (const company of companies) {
+ if (!chance(0.6)) continue;
+ rows.push({
+ ...base(company.id, pick(ownerIds), daysFromNow(-integer(5, 200), 12)),
+ type: ActivityType.NOTE,
+ body: pick(NOTE_BODIES),
+ });
+ }
+
+ await db.activity.createMany({ data: rows });
+ return rows.length;
+}
+
+async function main() {
+ const ownerIds = await seedOwners();
+ const companies = await seedCompanies(ownerIds);
+ const contacts = await seedContacts(companies, ownerIds);
+ const deals = await seedDeals(companies, contacts, ownerIds);
+ const activities = await seedActivities(companies, contacts, deals, ownerIds);
+
+ console.log(
+ `Seeded ${companies.length} companies, ${contacts.length} contacts, ` +
+ `${deals.length} deals, ${activities} activities.`,
+ );
+}
+
+main()
+ .catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+ })
+ .finally(async () => {
+ await db.$disconnect();
+ });
diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts
new file mode 100644
index 00000000..f7e18de1
--- /dev/null
+++ b/packages/db/src/client.ts
@@ -0,0 +1,105 @@
+import { PrismaPg } from "@prisma/adapter-pg";
+import { type Prisma, PrismaClient } from "./generated/prisma/client";
+
+const connectionString = process.env.DATABASE_URL;
+
+if (!connectionString) {
+ throw new Error(
+ "DATABASE_URL is not set. Copy packages/db/.env.example to packages/db/.env (or set it in the consuming app's environment).",
+ );
+}
+
+/** A log line emitted by the Prisma engine, normalised for whichever sink is installed. */
+export interface PrismaLogRecord {
+ level: Prisma.LogLevel;
+ message: string;
+ /** The Prisma emitter, e.g. `quaint::connector::metrics`. */
+ target: string;
+ /** Statement timing. Present on `query` records only. */
+ durationMs?: number;
+}
+
+export type PrismaLogSink = (record: PrismaLogRecord) => void;
+
+/**
+ * Seeds, one-off scripts and the Next.js app have no application logger to hand,
+ * so database problems still have to surface somewhere by default.
+ */
+const consoleSink: PrismaLogSink = ({ level, message, target, durationMs }) => {
+ const suffix = durationMs === undefined ? "" : ` (+${durationMs}ms)`;
+ const line = `[prisma:${level}] ${message}${suffix} [${target}]`;
+
+ if (level === "error") {
+ console.error(line);
+ } else if (level === "warn") {
+ console.warn(line);
+ } else {
+ console.log(line);
+ }
+};
+
+let sink: PrismaLogSink = consoleSink;
+
+/**
+ * Redirect Prisma engine logs. The API points this at the Nest logger so
+ * database logs are formatted and correlated like every other log line.
+ * Pass `null` to restore the console sink.
+ */
+export function setPrismaLogSink(next: PrismaLogSink | null): void {
+ sink = next ?? consoleSink;
+}
+
+/**
+ * Prisma logs every statement it runs when `query` is enabled, which buries
+ * anything worth reading under a wall of `SELECT`s — so it is opt-in rather
+ * than on in development. Bound parameters are dropped even when it is on:
+ * they routinely carry session tokens and personal data.
+ */
+const logQueries = process.env.PRISMA_LOG_QUERIES === "true";
+
+const logDefinitions: Prisma.LogDefinition[] = [
+ { level: "warn", emit: "event" },
+ { level: "error", emit: "event" },
+ ...(logQueries
+ ? ([
+ { level: "query", emit: "event" },
+ { level: "info", emit: "event" },
+ ] satisfies Prisma.LogDefinition[])
+ : []),
+];
+
+const createPrismaClient = () => {
+ const client = new PrismaClient({
+ adapter: new PrismaPg({ connectionString }),
+ log: logDefinitions,
+ });
+
+ // Every level is subscribed; the ones missing from `logDefinitions` simply
+ // never fire, so the engine does no work for logs nobody asked for.
+ client.$on("error", ({ message, target }) => {
+ sink({ level: "error", message, target });
+ });
+ client.$on("warn", ({ message, target }) => {
+ sink({ level: "warn", message, target });
+ });
+ client.$on("info", ({ message, target }) => {
+ sink({ level: "info", message, target });
+ });
+ client.$on("query", ({ query, duration, target }) => {
+ sink({ level: "query", message: query, target, durationMs: duration });
+ });
+
+ return client;
+};
+
+const globalForPrisma = globalThis as unknown as {
+ prisma: ReturnType<typeof createPrismaClient> | undefined;
+};
+
+export const db = globalForPrisma.prisma ?? createPrismaClient();
+
+if (process.env.NODE_ENV !== "production") {
+ globalForPrisma.prisma = db;
+}
+
+export type Db = typeof db;
diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts
new file mode 100644
index 00000000..8e13a5a0
--- /dev/null
+++ b/packages/db/src/index.ts
@@ -0,0 +1,10 @@
+export {
+ type Db,
+ db,
+ type PrismaLogRecord,
+ type PrismaLogSink,
+ setPrismaLogSink,
+} from "./client";
+export { Prisma, PrismaClient } from "./generated/prisma/client";
+export * from "./generated/prisma/enums";
+export type * from "./generated/prisma/models";
diff --git a/packages/db/tsconfig.json b/packages/db/tsconfig.json
new file mode 100644
index 00000000..df18351a
--- /dev/null
+++ b/packages/db/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "@crm/typescript-config/internal-package.json",
+ "compilerOptions": {
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts", "prisma/**/*.ts", "prisma.config.ts"],
+ "exclude": ["node_modules"]
+}
diff --git a/packages/db/turbo.json b/packages/db/turbo.json
new file mode 100644
index 00000000..b315e5bd
--- /dev/null
+++ b/packages/db/turbo.json
@@ -0,0 +1,53 @@
+{
+ "$schema": "https://turborepo.dev/schema.json",
+ "extends": ["//"],
+ "tasks": {
+ "build": {
+ "inputs": ["$TURBO_DEFAULT$", "prisma/**"],
+ "outputs": ["src/generated/**"],
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "dev": {
+ "cache": false,
+ "persistent": true,
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "db:generate": {
+ "inputs": ["$TURBO_DEFAULT$", "prisma/**"],
+ "outputs": ["src/generated/**"],
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "db:deploy": {
+ "cache": false,
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "db:migrate": {
+ "cache": false,
+ "interactive": true,
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "db:push": {
+ "cache": false,
+ "interactive": true,
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "db:reset": {
+ "cache": false,
+ "interactive": true,
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "db:seed": {
+ "cache": false,
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "db:studio": {
+ "cache": false,
+ "persistent": true,
+ "passThroughEnv": ["DATABASE_URL"]
+ },
+ "check-types": {
+ "dependsOn": ["$TURBO_EXTENDS$", "build"],
+ "passThroughEnv": ["DATABASE_URL"]
+ }
+ }
+}
diff --git a/packages/eslint-config/README.md b/packages/eslint-config/README.md
deleted file mode 100644
index 8b42d901..00000000
--- a/packages/eslint-config/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# `@turbo/eslint-config`
-
-Collection of internal eslint configurations.
diff --git a/packages/eslint-config/base.js b/packages/eslint-config/base.js
deleted file mode 100644
index 09d316ef..00000000
--- a/packages/eslint-config/base.js
+++ /dev/null
@@ -1,32 +0,0 @@
-import js from "@eslint/js";
-import eslintConfigPrettier from "eslint-config-prettier";
-import turboPlugin from "eslint-plugin-turbo";
-import tseslint from "typescript-eslint";
-import onlyWarn from "eslint-plugin-only-warn";
-
-/**
- * A shared ESLint configuration for the repository.
- *
- * @type {import("eslint").Linter.Config[]}
- * */
-export const config = [
- js.configs.recommended,
- eslintConfigPrettier,
- ...tseslint.configs.recommended,
- {
- plugins: {
- turbo: turboPlugin,
- },
- rules: {
- "turbo/no-undeclared-env-vars": "warn",
- },
- },
- {
- plugins: {
- onlyWarn,
- },
- },
- {
- ignores: ["dist/**"],
- },
-];
diff --git a/packages/eslint-config/next.js b/packages/eslint-config/next.js
deleted file mode 100644
index 4df088ac..00000000
--- a/packages/eslint-config/next.js
+++ /dev/null
@@ -1,57 +0,0 @@
-import js from "@eslint/js";
-import { globalIgnores } from "eslint/config";
-import eslintConfigPrettier from "eslint-config-prettier";
-import tseslint from "typescript-eslint";
-import pluginReactHooks from "eslint-plugin-react-hooks";
-import pluginReact from "eslint-plugin-react";
-import globals from "globals";
-import pluginNext from "@next/eslint-plugin-next";
-import { config as baseConfig } from "./base.js";
-
-/**
- * A custom ESLint configuration for libraries that use Next.js.
- *
- * @type {import("eslint").Linter.Config[]}
- * */
-export const nextJsConfig = [
- ...baseConfig,
- js.configs.recommended,
- eslintConfigPrettier,
- ...tseslint.configs.recommended,
- globalIgnores([
- // Default ignores of eslint-config-next:
- ".next/**",
- "out/**",
- "build/**",
- "next-env.d.ts",
- ]),
- {
- ...pluginReact.configs.flat.recommended,
- languageOptions: {
- ...pluginReact.configs.flat.recommended.languageOptions,
- globals: {
- ...globals.serviceworker,
- },
- },
- },
- {
- plugins: {
- "@next/next": pluginNext,
- },
- rules: {
- ...pluginNext.configs.recommended.rules,
- ...pluginNext.configs["core-web-vitals"].rules,
- },
- },
- {
- plugins: {
- "react-hooks": pluginReactHooks,
- },
- settings: { react: { version: "detect" } },
- rules: {
- ...pluginReactHooks.configs.recommended.rules,
- // React scope no longer necessary with new JSX transform.
- "react/react-in-jsx-scope": "off",
- },
- },
-];
diff --git a/packages/eslint-config/package.json b/packages/eslint-config/package.json
deleted file mode 100644
index 6fd5c24d..00000000
--- a/packages/eslint-config/package.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "name": "@repo/eslint-config",
- "version": "0.0.0",
- "type": "module",
- "private": true,
- "exports": {
- "./base": "./base.js",
- "./next-js": "./next.js",
- "./react-internal": "./react-internal.js"
- },
- "devDependencies": {
- "@eslint/js": "^9.39.1",
- "@next/eslint-plugin-next": "^16.2.0",
- "eslint": "^9.39.1",
- "eslint-config-prettier": "^10.1.1",
- "eslint-plugin-only-warn": "^1.1.0",
- "eslint-plugin-react": "^7.37.5",
- "eslint-plugin-react-hooks": "^5.2.0",
- "eslint-plugin-turbo": "^2.7.1",
- "globals": "^16.5.0",
- "typescript": "^5.9.2",
- "typescript-eslint": "^8.50.0"
- }
-}
diff --git a/packages/eslint-config/react-internal.js b/packages/eslint-config/react-internal.js
deleted file mode 100644
index daeccba2..00000000
--- a/packages/eslint-config/react-internal.js
+++ /dev/null
@@ -1,39 +0,0 @@
-import js from "@eslint/js";
-import eslintConfigPrettier from "eslint-config-prettier";
-import tseslint from "typescript-eslint";
-import pluginReactHooks from "eslint-plugin-react-hooks";
-import pluginReact from "eslint-plugin-react";
-import globals from "globals";
-import { config as baseConfig } from "./base.js";
-
-/**
- * A custom ESLint configuration for libraries that use React.
- *
- * @type {import("eslint").Linter.Config[]} */
-export const config = [
- ...baseConfig,
- js.configs.recommended,
- eslintConfigPrettier,
- ...tseslint.configs.recommended,
- pluginReact.configs.flat.recommended,
- {
- languageOptions: {
- ...pluginReact.configs.flat.recommended.languageOptions,
- globals: {
- ...globals.serviceworker,
- ...globals.browser,
- },
- },
- },
- {
- plugins: {
- "react-hooks": pluginReactHooks,
- },
- settings: { react: { version: "detect" } },
- rules: {
- ...pluginReactHooks.configs.recommended.rules,
- // React scope no longer necessary with new JSX transform.
- "react/react-in-jsx-scope": "off",
- },
- },
-];
diff --git a/packages/typescript-config/base.json b/packages/typescript-config/base.json
index 5117f2a3..0756a8cd 100644
--- a/packages/typescript-config/base.json
+++ b/packages/typescript-config/base.json
@@ -1,19 +1,19 @@
{
- "$schema": "https://json.schemastore.org/tsconfig",
- "compilerOptions": {
- "declaration": true,
- "declarationMap": true,
- "esModuleInterop": true,
- "incremental": false,
- "isolatedModules": true,
- "lib": ["es2022", "DOM", "DOM.Iterable"],
- "module": "NodeNext",
- "moduleDetection": "force",
- "moduleResolution": "NodeNext",
- "noUncheckedIndexedAccess": true,
- "resolveJsonModule": true,
- "skipLibCheck": true,
- "strict": true,
- "target": "ES2022"
- }
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "compilerOptions": {
+ "declaration": true,
+ "declarationMap": true,
+ "esModuleInterop": true,
+ "incremental": false,
+ "isolatedModules": true,
+ "lib": ["es2022", "DOM", "DOM.Iterable"],
+ "module": "NodeNext",
+ "moduleDetection": "force",
+ "moduleResolution": "NodeNext",
+ "noUncheckedIndexedAccess": true,
+ "resolveJsonModule": true,
+ "skipLibCheck": true,
+ "strict": true,
+ "target": "ES2022"
+ }
}
diff --git a/packages/typescript-config/internal-package.json b/packages/typescript-config/internal-package.json
new file mode 100644
index 00000000..68364216
--- /dev/null
+++ b/packages/typescript-config/internal-package.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./base.json",
+ "compilerOptions": {
+ "module": "Preserve",
+ "moduleResolution": "Bundler",
+ "noEmit": true
+ }
+}
diff --git a/packages/typescript-config/nestjs.json b/packages/typescript-config/nestjs.json
new file mode 100644
index 00000000..163cdd64
--- /dev/null
+++ b/packages/typescript-config/nestjs.json
@@ -0,0 +1,12 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./internal-package.json",
+ "compilerOptions": {
+ "target": "ES2023",
+ "lib": ["ES2023"],
+ "experimentalDecorators": true,
+ "emitDecoratorMetadata": true,
+ "noFallthroughCasesInSwitch": true,
+ "noImplicitOverride": true
+ }
+}
diff --git a/packages/typescript-config/nextjs.json b/packages/typescript-config/nextjs.json
index e6defa48..0bb7bc22 100644
--- a/packages/typescript-config/nextjs.json
+++ b/packages/typescript-config/nextjs.json
@@ -1,12 +1,15 @@
{
- "$schema": "https://json.schemastore.org/tsconfig",
- "extends": "./base.json",
- "compilerOptions": {
- "plugins": [{ "name": "next" }],
- "module": "ESNext",
- "moduleResolution": "Bundler",
- "allowJs": true,
- "jsx": "preserve",
- "noEmit": true
- }
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./base.json",
+ "compilerOptions": {
+ "plugins": [{ "name": "next" }],
+ "target": "ES2017",
+ "lib": ["dom", "dom.iterable", "esnext"],
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "allowJs": true,
+ "jsx": "react-jsx",
+ "incremental": true,
+ "noEmit": true
+ }
}
diff --git a/packages/typescript-config/package.json b/packages/typescript-config/package.json
index 27c0e604..342a2270 100644
--- a/packages/typescript-config/package.json
+++ b/packages/typescript-config/package.json
@@ -1,9 +1,13 @@
{
- "name": "@repo/typescript-config",
- "version": "0.0.0",
- "private": true,
- "license": "MIT",
- "publishConfig": {
- "access": "public"
- }
+ "name": "@crm/typescript-config",
+ "version": "0.0.0",
+ "private": true,
+ "license": "MIT",
+ "exports": {
+ "./base.json": "./base.json",
+ "./internal-package.json": "./internal-package.json",
+ "./nestjs.json": "./nestjs.json",
+ "./nextjs.json": "./nextjs.json",
+ "./react-library.json": "./react-library.json"
+ }
}
diff --git a/packages/typescript-config/react-library.json b/packages/typescript-config/react-library.json
index c3a1b26f..59f2c202 100644
--- a/packages/typescript-config/react-library.json
+++ b/packages/typescript-config/react-library.json
@@ -1,7 +1,7 @@
{
- "$schema": "https://json.schemastore.org/tsconfig",
- "extends": "./base.json",
- "compilerOptions": {
- "jsx": "react-jsx"
- }
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./internal-package.json",
+ "compilerOptions": {
+ "jsx": "react-jsx"
+ }
}
diff --git a/packages/ui/components.json b/packages/ui/components.json
new file mode 100644
index 00000000..3ccf2601
--- /dev/null
+++ b/packages/ui/components.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://ui.shadcn.com/schema.json",
+ "style": "radix-nova",
+ "rsc": true,
+ "tsx": true,
+ "tailwind": {
+ "config": "",
+ "css": "src/styles/globals.css",
+ "baseColor": "neutral",
+ "cssVariables": true
+ },
+ "iconLibrary": "lucide",
+ "aliases": {
+ "components": "@crm/ui/components",
+ "utils": "@crm/ui/lib/utils",
+ "hooks": "@crm/ui/hooks",
+ "lib": "@crm/ui/lib",
+ "ui": "@crm/ui/components"
+ },
+ "rtl": false,
+ "menuColor": "default",
+ "menuAccent": "subtle"
+}
diff --git a/packages/ui/eslint.config.mjs b/packages/ui/eslint.config.mjs
deleted file mode 100644
index 19170f88..00000000
--- a/packages/ui/eslint.config.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-import { config } from "@repo/eslint-config/react-internal";
-
-/** @type {import("eslint").Linter.Config} */
-export default config;
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 715430ca..b149b196 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -1,26 +1,56 @@
{
- "name": "@repo/ui",
- "version": "0.0.0",
- "private": true,
- "exports": {
- "./*": "./src/*.tsx"
- },
- "scripts": {
- "lint": "eslint . --max-warnings 0",
- "generate:component": "turbo gen react-component",
- "check-types": "tsc --noEmit"
- },
- "devDependencies": {
- "@repo/eslint-config": "*",
- "@repo/typescript-config": "*",
- "@types/node": "^22.15.3",
- "@types/react": "19.2.2",
- "@types/react-dom": "19.2.2",
- "eslint": "^9.39.1",
- "typescript": "5.9.2"
- },
- "dependencies": {
- "react": "^19.2.0",
- "react-dom": "^19.2.0"
- }
+ "name": "@crm/ui",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ "./globals.css": "./src/styles/globals.css",
+ "./postcss.config": "./postcss.config.mjs",
+ "./components/*": "./src/components/*.tsx",
+ "./hooks/*": "./src/hooks/*.ts",
+ "./lib/*": "./src/lib/*.ts"
+ },
+ "scripts": {
+ "check-types": "tsc --noEmit",
+ "ui:add": "shadcn add",
+ "lint": "biome check .",
+ "clean": "rm -rf .turbo node_modules"
+ },
+ "dependencies": {
+ "@carbon/icons-react": "^11.82.0",
+ "@shadcn/react": "^0.2.1",
+ "class-variance-authority": "^0.7.1",
+ "clsx": "^2.1.1",
+ "cmdk": "^1.1.1",
+ "embla-carousel-react": "^8.6.0",
+ "input-otp": "^1.4.2",
+ "lucide-react": "^1.28.0",
+ "next-themes": "^0.4.6",
+ "nuqs": "^2.8.9",
+ "radix-ui": "^1.6.0",
+ "react-day-picker": "^10.0.1",
+ "react-hook-form": "^7.80.0",
+ "react-resizable-panels": "^4.12.2",
+ "recharts": "3.8.0",
+ "sonner": "^2.0.7",
+ "tailwind-merge": "^3.6.0",
+ "tw-animate-css": "^1.4.0",
+ "vaul": "^1.1.2"
+ },
+ "peerDependencies": {
+ "react": "^19.2.0",
+ "react-dom": "^19.2.0"
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@tailwindcss/postcss": "^4",
+ "@types/node": "^24.10.1",
+ "@types/react": "^19.2.18",
+ "@types/react-dom": "^19",
+ "react": "19.2.4",
+ "react-dom": "19.2.4",
+ "shadcn": "^4.16.1",
+ "tailwindcss": "^4",
+ "typescript": "5.9.2"
+ }
}
diff --git a/packages/ui/postcss.config.mjs b/packages/ui/postcss.config.mjs
new file mode 100644
index 00000000..6ba14df9
--- /dev/null
+++ b/packages/ui/postcss.config.mjs
@@ -0,0 +1,8 @@
+/** @type {import('postcss-load-config').Config} */
+const config = {
+ plugins: {
+ "@tailwindcss/postcss": {},
+ },
+};
+
+export default config;
diff --git a/packages/ui/src/button.tsx b/packages/ui/src/button.tsx
deleted file mode 100644
index 78e5420c..00000000
--- a/packages/ui/src/button.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-"use client";
-
-import { ReactNode } from "react";
-
-interface ButtonProps {
- children: ReactNode;
- className?: string;
- appName: string;
-}
-
-export const Button = ({ children, className, appName }: ButtonProps) => {
- return (
- <button
- className={className}
- onClick={() => alert(`Hello from your ${appName} app!`)}
- >
- {children}
- </button>
- );
-};
diff --git a/packages/ui/src/card.tsx b/packages/ui/src/card.tsx
deleted file mode 100644
index 7b988937..00000000
--- a/packages/ui/src/card.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { type JSX } from "react";
-
-export function Card({
- className,
- title,
- children,
- href,
-}: {
- className?: string;
- title: string;
- children: React.ReactNode;
- href: string;
-}): JSX.Element {
- return (
- <a
- className={className}
- href={`${href}?utm_source=create-turbo&utm_medium=basic&utm_campaign=create-turbo"`}
- rel="noopener noreferrer"
- target="_blank"
- >
- <h2>
- {title} <span>-&gt;</span>
- </h2>
- <p>{children}</p>
- </a>
- );
-}
diff --git a/packages/ui/src/code.tsx b/packages/ui/src/code.tsx
deleted file mode 100644
index f7cbd22a..00000000
--- a/packages/ui/src/code.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { type JSX } from "react";
-
-export function Code({
- children,
- className,
-}: {
- children: React.ReactNode;
- className?: string;
-}): JSX.Element {
- return <code className={className}>{children}</code>;
-}
diff --git a/packages/ui/src/components/accordion.tsx b/packages/ui/src/components/accordion.tsx
new file mode 100644
index 00000000..ee068760
--- /dev/null
+++ b/packages/ui/src/components/accordion.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
+import { Accordion as AccordionPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Accordion({
+ className,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
+ return (
+ <AccordionPrimitive.Root
+ data-slot="accordion"
+ className={cn("flex w-full flex-col", className)}
+ {...props}
+ />
+ );
+}
+
+function AccordionItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
+ return (
+ <AccordionPrimitive.Item
+ data-slot="accordion-item"
+ className={cn("not-last:border-b", className)}
+ {...props}
+ />
+ );
+}
+
+function AccordionTrigger({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
+ return (
+ <AccordionPrimitive.Header className="flex">
+ <AccordionPrimitive.Trigger
+ data-slot="accordion-trigger"
+ className={cn(
+ "group/accordion-trigger relative flex flex-1 items-start justify-between rounded-none border border-transparent py-2.5 text-left text-xs font-medium transition-all outline-none hover:underline focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 focus-visible:after:border-ring disabled:pointer-events-none disabled:opacity-50 **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4 **:data-[slot=accordion-trigger-icon]:text-muted-foreground",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronDownIcon
+ data-slot="accordion-trigger-icon"
+ className="pointer-events-none shrink-0 group-aria-expanded/accordion-trigger:hidden"
+ />
+ <ChevronUpIcon
+ data-slot="accordion-trigger-icon"
+ className="pointer-events-none hidden shrink-0 group-aria-expanded/accordion-trigger:inline"
+ />
+ </AccordionPrimitive.Trigger>
+ </AccordionPrimitive.Header>
+ );
+}
+
+function AccordionContent({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
+ return (
+ <AccordionPrimitive.Content
+ data-slot="accordion-content"
+ className="overflow-hidden text-xs data-open:animate-accordion-down data-closed:animate-accordion-up"
+ {...props}
+ >
+ <div
+ className={cn(
+ "h-(--radix-accordion-content-height) pt-0 pb-2.5 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
+ className,
+ )}
+ >
+ {children}
+ </div>
+ </AccordionPrimitive.Content>
+ );
+}
+
+export { Accordion, AccordionContent, AccordionItem, AccordionTrigger };
diff --git a/packages/ui/src/components/alert-dialog.tsx b/packages/ui/src/components/alert-dialog.tsx
new file mode 100644
index 00000000..7be0b107
--- /dev/null
+++ b/packages/ui/src/components/alert-dialog.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import { AlertDialog as AlertDialogPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function AlertDialog({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
+ return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
+}
+
+function AlertDialogTrigger({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
+ return (
+ <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
+ );
+}
+
+function AlertDialogPortal({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
+ return (
+ <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
+ );
+}
+
+function AlertDialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
+ return (
+ <AlertDialogPrimitive.Overlay
+ data-slot="alert-dialog-overlay"
+ className={cn(
+ "fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogContent({
+ className,
+ size = "default",
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
+ size?: "default" | "sm";
+}) {
+ return (
+ <AlertDialogPortal>
+ <AlertDialogOverlay />
+ <AlertDialogPrimitive.Content
+ data-slot="alert-dialog-content"
+ data-size={size}
+ className={cn(
+ "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-none bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ </AlertDialogPortal>
+ );
+}
+
+function AlertDialogHeader({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-header"
+ className={cn(
+ "grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogFooter({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-footer"
+ className={cn(
+ "flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogMedia({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-media"
+ className={cn(
+ "mb-2 inline-flex size-10 items-center justify-center rounded-none bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
+ return (
+ <AlertDialogPrimitive.Title
+ data-slot="alert-dialog-title"
+ className={cn(
+ "font-heading text-sm font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
+ return (
+ <AlertDialogPrimitive.Description
+ data-slot="alert-dialog-description"
+ className={cn(
+ "text-xs/relaxed text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDialogAction({
+ className,
+ variant = "default",
+ size = "default",
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
+ Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
+ return (
+ <Button variant={variant} size={size} asChild>
+ <AlertDialogPrimitive.Action
+ data-slot="alert-dialog-action"
+ className={cn(className)}
+ {...props}
+ />
+ </Button>
+ );
+}
+
+function AlertDialogCancel({
+ className,
+ variant = "outline",
+ size = "default",
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
+ Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
+ return (
+ <Button variant={variant} size={size} asChild>
+ <AlertDialogPrimitive.Cancel
+ data-slot="alert-dialog-cancel"
+ className={cn(className)}
+ {...props}
+ />
+ </Button>
+ );
+}
+
+export {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogOverlay,
+ AlertDialogPortal,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+};
diff --git a/packages/ui/src/components/alert.tsx b/packages/ui/src/components/alert.tsx
new file mode 100644
index 00000000..d6d01689
--- /dev/null
+++ b/packages/ui/src/components/alert.tsx
@@ -0,0 +1,78 @@
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import type * as React from "react";
+
+const alertVariants = cva(
+ "group/alert relative grid w-full gap-0.5 rounded-none border px-2.5 py-2 text-left text-xs has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ variant: {
+ default: "bg-card text-card-foreground",
+ destructive:
+ "bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+function Alert({
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
+ return (
+ <div
+ data-slot="alert"
+ role="alert"
+ className={cn(alertVariants({ variant }), className)}
+ {...props}
+ />
+ );
+}
+
+function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-title"
+ className={cn(
+ "font-medium group-has-[>svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDescription({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-description"
+ className={cn(
+ "text-xs/relaxed text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-action"
+ className={cn(
+ "absolute top-[calc(--spacing(1.25))] right-[calc(--spacing(1.25))]",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Alert, AlertAction, AlertDescription, AlertTitle };
diff --git a/packages/ui/src/components/aspect-ratio.tsx b/packages/ui/src/components/aspect-ratio.tsx
new file mode 100644
index 00000000..956e8bb0
--- /dev/null
+++ b/packages/ui/src/components/aspect-ratio.tsx
@@ -0,0 +1,11 @@
+"use client";
+
+import { AspectRatio as AspectRatioPrimitive } from "radix-ui";
+
+function AspectRatio({
+ ...props
+}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
+ return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />;
+}
+
+export { AspectRatio };
diff --git a/packages/ui/src/components/attachment.tsx b/packages/ui/src/components/attachment.tsx
new file mode 100644
index 00000000..db4cd358
--- /dev/null
+++ b/packages/ui/src/components/attachment.tsx
@@ -0,0 +1,205 @@
+import { Button } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { Slot } from "radix-ui";
+import type * as React from "react";
+
+const attachmentVariants = cva(
+ "group/attachment relative flex w-fit max-w-full min-w-0 shrink-0 flex-wrap rounded-none border bg-card text-card-foreground transition-colors focus-within:ring-1 focus-within:ring-ring/50 has-[>a,>button]:hover:bg-muted/50 data-[state=error]:border-destructive/30 data-[state=idle]:border-dashed",
+ {
+ variants: {
+ size: {
+ default:
+ "gap-2 text-xs has-data-[slot=attachment-content]:px-2 has-data-[slot=attachment-content]:py-1.5 has-data-[slot=attachment-media]:p-1.5",
+ sm: "gap-2.5 text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1",
+ xs: "gap-1.5 rounded-none text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1",
+ },
+ orientation: {
+ horizontal: "min-w-40 items-center",
+ vertical: "w-24 flex-col has-data-[slot=attachment-content]:w-30",
+ },
+ },
+ },
+);
+
+function Attachment({
+ className,
+ state = "done",
+ size = "default",
+ orientation = "horizontal",
+ ...props
+}: React.ComponentProps<"div"> &
+ VariantProps<typeof attachmentVariants> & {
+ state?: "idle" | "uploading" | "processing" | "error" | "done";
+ }) {
+ const resolvedOrientation = orientation ?? "horizontal";
+
+ return (
+ <div
+ data-slot="attachment"
+ data-state={state}
+ data-size={size}
+ data-orientation={resolvedOrientation}
+ className={cn(attachmentVariants({ size, orientation }), className)}
+ {...props}
+ />
+ );
+}
+
+const attachmentMediaVariants = cva(
+ "relative flex aspect-square w-10 shrink-0 items-center justify-center overflow-hidden rounded-none bg-muted text-foreground group-data-[orientation=vertical]/attachment:w-full group-data-[size=sm]/attachment:w-8 group-data-[size=xs]/attachment:w-7 group-data-[size=xs]/attachment:rounded-none group-data-[state=error]/attachment:bg-destructive/10 group-data-[state=error]/attachment:text-destructive group-data-[orientation=vertical]/attachment:*:data-[slot=spinner]:size-6! [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 group-data-[orientation=vertical]/attachment:[&_svg:not([class*='size-'])]:size-6 group-data-[size=xs]/attachment:[&_svg:not([class*='size-'])]:size-3.5",
+ {
+ variants: {
+ variant: {
+ icon: "",
+ image:
+ "opacity-60 group-data-[state=done]/attachment:opacity-100 group-data-[state=idle]/attachment:opacity-100 *:[img]:aspect-square *:[img]:w-full *:[img]:object-cover",
+ },
+ },
+ defaultVariants: {
+ variant: "icon",
+ },
+ },
+);
+
+function AttachmentMedia({
+ className,
+ variant = "icon",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof attachmentMediaVariants>) {
+ return (
+ <div
+ data-slot="attachment-media"
+ data-variant={variant}
+ className={cn(attachmentMediaVariants({ variant }), className)}
+ {...props}
+ />
+ );
+}
+
+function AttachmentContent({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="attachment-content"
+ className={cn(
+ "max-w-full min-w-0 flex-1 leading-tight group-data-[orientation=vertical]/attachment:px-1",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AttachmentTitle({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="attachment-title"
+ className={cn(
+ "block max-w-full min-w-0 truncate font-medium group-data-[state=processing]/attachment:shimmer group-data-[state=uploading]/attachment:shimmer",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AttachmentDescription({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="attachment-description"
+ className={cn(
+ "mt-0.5 block min-w-0 truncate text-xs text-muted-foreground group-data-[state=error]/attachment:text-destructive/80",
+ "max-w-full",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AttachmentActions({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="attachment-actions"
+ className={cn(
+ "relative z-20 flex shrink-0 items-center group-data-[orientation=vertical]/attachment:absolute group-data-[orientation=vertical]/attachment:top-3 group-data-[orientation=vertical]/attachment:right-3 group-data-[orientation=vertical]/attachment:gap-1",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AttachmentAction({
+ className,
+ variant,
+ size = "icon-xs",
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ return (
+ <Button
+ data-slot="attachment-action"
+ variant={variant ?? "ghost"}
+ size={size}
+ className={cn(className)}
+ {...props}
+ />
+ );
+}
+
+function AttachmentTrigger({
+ className,
+ asChild = false,
+ type,
+ ...props
+}: React.ComponentProps<"button"> & {
+ asChild?: boolean;
+}) {
+ const Comp = asChild ? Slot.Root : "button";
+
+ return (
+ <Comp
+ data-slot="attachment-trigger"
+ type={asChild ? undefined : (type ?? "button")}
+ className={cn("absolute inset-0 z-10 outline-none", className)}
+ {...props}
+ />
+ );
+}
+
+function AttachmentGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="attachment-group"
+ className={cn(
+ "flex min-w-0 scroll-fade-x snap-x snap-mandatory scroll-px-1 scrollbar-none gap-3 overflow-x-auto overscroll-x-contain py-1 *:data-[slot=attachment]:flex-none *:data-[slot=attachment]:snap-start",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Attachment,
+ AttachmentAction,
+ AttachmentActions,
+ AttachmentContent,
+ AttachmentDescription,
+ AttachmentGroup,
+ AttachmentMedia,
+ AttachmentTitle,
+ AttachmentTrigger,
+};
diff --git a/packages/ui/src/components/avatar.tsx b/packages/ui/src/components/avatar.tsx
new file mode 100644
index 00000000..eaa0ca85
--- /dev/null
+++ b/packages/ui/src/components/avatar.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { Avatar as AvatarPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Avatar({
+ className,
+ size = "default",
+ ...props
+}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
+ size?: "default" | "sm" | "lg";
+}) {
+ return (
+ <AvatarPrimitive.Root
+ data-slot="avatar"
+ data-size={size}
+ className={cn(
+ "group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AvatarImage({
+ className,
+ referrerPolicy = "no-referrer",
+ ...props
+}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
+ return (
+ <AvatarPrimitive.Image
+ data-slot="avatar-image"
+ referrerPolicy={referrerPolicy}
+ className={cn(
+ "aspect-square size-full rounded-full object-cover",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AvatarFallback({
+ className,
+ ...props
+}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
+ return (
+ <AvatarPrimitive.Fallback
+ data-slot="avatar-fallback"
+ className={cn(
+ "flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="avatar-badge"
+ className={cn(
+ "absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
+ "group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
+ "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
+ "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="avatar-group"
+ className={cn(
+ "group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AvatarGroupCount({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="avatar-group-count"
+ className={cn(
+ "relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Avatar,
+ AvatarBadge,
+ AvatarFallback,
+ AvatarGroup,
+ AvatarGroupCount,
+ AvatarImage,
+};
diff --git a/packages/ui/src/components/brand-logos/google.tsx b/packages/ui/src/components/brand-logos/google.tsx
new file mode 100644
index 00000000..70965c82
--- /dev/null
+++ b/packages/ui/src/components/brand-logos/google.tsx
@@ -0,0 +1,30 @@
+import type * as React from "react";
+
+const GoogleLogo = (props: React.SVGProps<SVGSVGElement>) => (
+ <svg
+ viewBox="-3 0 262 262"
+ xmlns="http://www.w3.org/2000/svg"
+ preserveAspectRatio="xMidYMid"
+ aria-hidden="true"
+ {...props}
+ >
+ <path
+ d="M255.878 133.451c0-10.734-.871-18.567-2.756-26.69H130.55v48.448h71.947c-1.45 12.04-9.283 30.172-26.69 42.356l-.244 1.622 38.755 30.023 2.685.268c24.659-22.774 38.875-56.282 38.875-96.027"
+ fill="#4285f4"
+ />
+ <path
+ d="M130.55 261.1c35.248 0 64.839-11.605 86.453-31.622l-41.196-31.913c-11.024 7.688-25.82 13.055-45.257 13.055-34.523 0-63.824-22.773-74.269-54.25l-1.531.13-40.298 31.187-.527 1.465C35.393 231.798 79.49 261.1 130.55 261.1"
+ fill="#34a853"
+ />
+ <path
+ d="M56.281 156.37c-2.756-8.123-4.351-16.827-4.351-25.82 0-8.994 1.595-17.697 4.206-25.82l-.073-1.73L15.26 71.312l-1.335.635C5.077 89.644 0 109.517 0 130.55s5.077 40.905 13.925 58.602z"
+ fill="#fbbc05"
+ />
+ <path
+ d="M130.55 50.479c24.514 0 41.05 10.589 50.479 19.438l36.844-35.974C195.245 12.91 165.798 0 130.55 0 79.49 0 35.393 29.301 13.925 71.947l42.211 32.783c10.59-31.477 39.891-54.251 74.414-54.251"
+ fill="#eb4335"
+ />
+ </svg>
+);
+
+export default GoogleLogo;
diff --git a/packages/ui/src/components/breadcrumb.tsx b/packages/ui/src/components/breadcrumb.tsx
new file mode 100644
index 00000000..1aaae3f7
--- /dev/null
+++ b/packages/ui/src/components/breadcrumb.tsx
@@ -0,0 +1,118 @@
+import { cn } from "@crm/ui/lib/utils";
+import { ChevronRightIcon, MoreHorizontalIcon } from "lucide-react";
+import { Slot } from "radix-ui";
+import type * as React from "react";
+
+function Breadcrumb({ className, ...props }: React.ComponentProps<"nav">) {
+ return (
+ <nav
+ aria-label="breadcrumb"
+ data-slot="breadcrumb"
+ className={cn(className)}
+ {...props}
+ />
+ );
+}
+
+function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
+ return (
+ <ol
+ data-slot="breadcrumb-list"
+ className={cn(
+ "flex flex-wrap items-center gap-1.5 text-xs wrap-break-word text-muted-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="breadcrumb-item"
+ className={cn("inline-flex items-center gap-1", className)}
+ {...props}
+ />
+ );
+}
+
+function BreadcrumbLink({
+ asChild,
+ className,
+ ...props
+}: React.ComponentProps<"a"> & {
+ asChild?: boolean;
+}) {
+ const Comp = asChild ? Slot.Root : "a";
+
+ return (
+ <Comp
+ data-slot="breadcrumb-link"
+ className={cn("transition-colors hover:text-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="breadcrumb-page"
+ role="link"
+ aria-disabled="true"
+ aria-current="page"
+ className={cn("font-normal text-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+function BreadcrumbSeparator({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="breadcrumb-separator"
+ role="presentation"
+ aria-hidden="true"
+ className={cn("[&>svg]:size-3.5", className)}
+ {...props}
+ >
+ {children ?? <ChevronRightIcon />}
+ </li>
+ );
+}
+
+function BreadcrumbEllipsis({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="breadcrumb-ellipsis"
+ role="presentation"
+ aria-hidden="true"
+ className={cn(
+ "flex size-5 items-center justify-center [&>svg]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ <MoreHorizontalIcon />
+ <span className="sr-only">More</span>
+ </span>
+ );
+}
+
+export {
+ Breadcrumb,
+ BreadcrumbEllipsis,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbList,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+};
diff --git a/packages/ui/src/components/bubble.tsx b/packages/ui/src/components/bubble.tsx
new file mode 100644
index 00000000..0636f5a6
--- /dev/null
+++ b/packages/ui/src/components/bubble.tsx
@@ -0,0 +1,124 @@
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { Slot } from "radix-ui";
+import type * as React from "react";
+
+function BubbleGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="bubble-group"
+ className={cn("flex min-w-0 flex-col gap-2", className)}
+ {...props}
+ />
+ );
+}
+
+const bubbleVariants = cva(
+ "group/bubble relative flex w-fit max-w-[80%] min-w-0 flex-col gap-1 group-data-[align=end]/message:self-end data-[align=end]:self-end data-[variant=ghost]:max-w-full",
+ {
+ variants: {
+ variant: {
+ default:
+ "*:data-[slot=bubble-content]:bg-primary *:data-[slot=bubble-content]:text-primary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-primary/80",
+ secondary:
+ "*:data-[slot=bubble-content]:bg-secondary *:data-[slot=bubble-content]:text-secondary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]",
+ muted:
+ "*:data-[slot=bubble-content]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--muted),var(--foreground)_5%)]",
+ tinted:
+ "*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.93_calc(c*0.4)_h)] *:data-[slot=bubble-content]:text-foreground dark:*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.3_calc(c*0.4)_h)] [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.88_calc(c*0.5)_h)] dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.35_calc(c*0.5)_h)]",
+ outline:
+ "*:data-[slot=bubble-content]:border-border *:data-[slot=bubble-content]:bg-background [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-input/30",
+ ghost:
+ "border-none *:data-[slot=bubble-content]:rounded-none *:data-[slot=bubble-content]:bg-transparent *:data-[slot=bubble-content]:p-0 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted/50",
+ destructive:
+ "*:data-[slot=bubble-content]:bg-destructive/10 *:data-[slot=bubble-content]:text-destructive dark:*:data-[slot=bubble-content]:bg-destructive/20 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/20 dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/30",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+function Bubble({
+ variant = "default",
+ align = "start",
+ className,
+ ...props
+}: React.ComponentProps<"div"> &
+ VariantProps<typeof bubbleVariants> & {
+ align?: "start" | "end";
+ }) {
+ return (
+ <div
+ data-slot="bubble"
+ data-variant={variant}
+ data-align={align}
+ className={cn(bubbleVariants({ variant }), className)}
+ {...props}
+ />
+ );
+}
+
+function BubbleContent({
+ asChild = false,
+ className,
+ ...props
+}: React.ComponentProps<"div"> & {
+ asChild?: boolean;
+}) {
+ const Comp = asChild ? Slot.Root : "div";
+
+ return (
+ <Comp
+ data-slot="bubble-content"
+ className={cn(
+ "w-fit max-w-full min-w-0 overflow-hidden rounded-none border border-transparent px-2.5 py-2 text-xs leading-relaxed wrap-break-word group-data-[align=end]/bubble:self-end [button]:text-left [button,a]:transition-colors [button,a]:outline-none [button,a]:focus-visible:border-ring [button,a]:focus-visible:ring-1 [button,a]:focus-visible:ring-ring/50",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+const bubbleReactionsVariants = cva(
+ "absolute z-10 flex w-fit shrink-0 items-center justify-center gap-1 rounded-none bg-muted px-1.5 py-0.5 text-xs ring-2 ring-card has-[button]:p-0",
+ {
+ variants: {
+ side: {
+ top: "top-0 -translate-y-3/4",
+ bottom: "bottom-0 translate-y-3/4",
+ },
+ align: {
+ start: "left-3",
+ end: "right-3",
+ },
+ },
+ defaultVariants: {
+ side: "bottom",
+ align: "end",
+ },
+ },
+);
+
+function BubbleReactions({
+ side = "bottom",
+ align = "end",
+ className,
+ ...props
+}: React.ComponentProps<"div"> & {
+ align?: "start" | "end";
+ side?: "top" | "bottom";
+}) {
+ return (
+ <div
+ data-slot="bubble-reactions"
+ data-align={align}
+ data-side={side}
+ className={cn(bubbleReactionsVariants({ side, align }), className)}
+ {...props}
+ />
+ );
+}
+
+export { Bubble, BubbleContent, BubbleGroup, BubbleReactions };
diff --git a/packages/ui/src/components/button-group.tsx b/packages/ui/src/components/button-group.tsx
new file mode 100644
index 00000000..0751f3e2
--- /dev/null
+++ b/packages/ui/src/components/button-group.tsx
@@ -0,0 +1,82 @@
+import { Separator } from "@crm/ui/components/separator";
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { Slot } from "radix-ui";
+
+const buttonGroupVariants = cva(
+ "group/button-group flex w-fit items-stretch rounded-none *:focus-visible:relative *:focus-visible:z-10 has-[>[data-slot=button-group]]:gap-2 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-none [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",
+ {
+ variants: {
+ orientation: {
+ horizontal:
+ "[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
+ vertical:
+ "flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
+ },
+ },
+ defaultVariants: {
+ orientation: "horizontal",
+ },
+ },
+);
+
+function ButtonGroup({
+ className,
+ orientation,
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="button-group"
+ data-orientation={orientation}
+ className={cn(buttonGroupVariants({ orientation }), className)}
+ {...props}
+ />
+ );
+}
+
+function ButtonGroupText({
+ className,
+ asChild = false,
+ ...props
+}: React.ComponentProps<"div"> & {
+ asChild?: boolean;
+}) {
+ const Comp = asChild ? Slot.Root : "div";
+
+ return (
+ <Comp
+ className={cn(
+ "flex items-center gap-2 rounded-none border bg-muted px-2.5 text-xs font-medium [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ButtonGroupSeparator({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return (
+ <Separator
+ data-slot="button-group-separator"
+ orientation={orientation}
+ className={cn(
+ "relative self-stretch bg-input data-horizontal:mx-px data-horizontal:w-auto data-vertical:my-px data-vertical:h-auto",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ ButtonGroup,
+ ButtonGroupSeparator,
+ ButtonGroupText,
+ buttonGroupVariants,
+};
diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx
new file mode 100644
index 00000000..d85ce179
--- /dev/null
+++ b/packages/ui/src/components/button.tsx
@@ -0,0 +1,64 @@
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { Slot } from "radix-ui";
+import type * as React from "react";
+
+const buttonVariants = cva(
+ "group/button inline-flex shrink-0 cursor-pointer items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ variant: {
+ default: "bg-primary text-primary-foreground hover:bg-primary/80",
+ outline:
+ "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
+ secondary:
+ "bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
+ ghost:
+ "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
+ destructive:
+ "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
+ link: "text-primary underline-offset-4 hover:underline",
+ },
+ size: {
+ default:
+ "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
+ xs: "h-6 gap-1 rounded-none px-2 text-xs has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
+ sm: "h-7 gap-1 rounded-none px-2.5 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
+ lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
+ icon: "size-8",
+ "icon-xs": "size-6 rounded-none [&_svg:not([class*='size-'])]:size-3",
+ "icon-sm": "size-7 rounded-none",
+ "icon-lg": "size-9",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+function Button({
+ className,
+ variant = "default",
+ size = "default",
+ asChild = false,
+ ...props
+}: React.ComponentProps<"button"> &
+ VariantProps<typeof buttonVariants> & {
+ asChild?: boolean;
+ }) {
+ const Comp = asChild ? Slot.Root : "button";
+
+ return (
+ <Comp
+ data-slot="button"
+ data-variant={variant}
+ data-size={size}
+ className={cn(buttonVariants({ variant, size, className }))}
+ {...props}
+ />
+ );
+}
+
+export { Button, buttonVariants };
diff --git a/packages/ui/src/components/calendar.tsx b/packages/ui/src/components/calendar.tsx
new file mode 100644
index 00000000..33b77880
--- /dev/null
+++ b/packages/ui/src/components/calendar.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import { Button, buttonVariants } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import {
+ ChevronDownIcon,
+ ChevronLeftIcon,
+ ChevronRightIcon,
+} from "lucide-react";
+import * as React from "react";
+import {
+ type DayButton,
+ DayPicker,
+ getDefaultClassNames,
+ type Locale,
+} from "react-day-picker";
+
+function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ captionLayout = "label",
+ buttonVariant = "ghost",
+ locale,
+ formatters,
+ components,
+ ...props
+}: React.ComponentProps<typeof DayPicker> & {
+ buttonVariant?: React.ComponentProps<typeof Button>["variant"];
+}) {
+ const defaultClassNames = getDefaultClassNames();
+
+ return (
+ <DayPicker
+ showOutsideDays={showOutsideDays}
+ className={cn(
+ "group/calendar bg-background p-2 [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
+ String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
+ String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
+ className,
+ )}
+ captionLayout={captionLayout}
+ locale={locale}
+ formatters={{
+ formatMonthDropdown: (date) =>
+ date.toLocaleString(locale?.code, { month: "short" }),
+ ...formatters,
+ }}
+ classNames={{
+ root: cn("w-fit", defaultClassNames.root),
+ months: cn(
+ "relative flex flex-col gap-4 md:flex-row",
+ defaultClassNames.months,
+ ),
+ month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
+ nav: cn(
+ "absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
+ defaultClassNames.nav,
+ ),
+ button_previous: cn(
+ buttonVariants({ variant: buttonVariant }),
+ "size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
+ defaultClassNames.button_previous,
+ ),
+ button_next: cn(
+ buttonVariants({ variant: buttonVariant }),
+ "size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
+ defaultClassNames.button_next,
+ ),
+ month_caption: cn(
+ "flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
+ defaultClassNames.month_caption,
+ ),
+ dropdowns: cn(
+ "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
+ defaultClassNames.dropdowns,
+ ),
+ dropdown_root: cn(
+ "relative rounded-(--cell-radius)",
+ defaultClassNames.dropdown_root,
+ ),
+ dropdown: cn(
+ "absolute inset-0 bg-popover opacity-0",
+ defaultClassNames.dropdown,
+ ),
+ caption_label: cn(
+ "font-medium select-none",
+ captionLayout === "label"
+ ? "text-sm"
+ : "flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
+ defaultClassNames.caption_label,
+ ),
+ month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
+ weekdays: cn("flex", defaultClassNames.weekdays),
+ weekday: cn(
+ "flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none",
+ defaultClassNames.weekday,
+ ),
+ week: cn("mt-2 flex w-full", defaultClassNames.week),
+ week_number_header: cn(
+ "w-(--cell-size) select-none",
+ defaultClassNames.week_number_header,
+ ),
+ week_number: cn(
+ "text-[0.8rem] text-muted-foreground select-none",
+ defaultClassNames.week_number,
+ ),
+ day: cn(
+ "group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",
+ props.showWeekNumber
+ ? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"
+ : "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",
+ defaultClassNames.day,
+ ),
+ range_start: cn(
+ "relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",
+ defaultClassNames.range_start,
+ ),
+ range_middle: cn("rounded-none", defaultClassNames.range_middle),
+ range_end: cn(
+ "relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",
+ defaultClassNames.range_end,
+ ),
+ today: cn(
+ "rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none",
+ defaultClassNames.today,
+ ),
+ outside: cn(
+ "text-muted-foreground aria-selected:text-muted-foreground",
+ defaultClassNames.outside,
+ ),
+ disabled: cn(
+ "text-muted-foreground opacity-50",
+ defaultClassNames.disabled,
+ ),
+ hidden: cn("invisible", defaultClassNames.hidden),
+ ...classNames,
+ }}
+ components={{
+ Root: ({ className, rootRef, ...props }) => {
+ return (
+ <div
+ data-slot="calendar"
+ ref={rootRef}
+ className={cn(className)}
+ {...props}
+ />
+ );
+ },
+ Chevron: ({ className, orientation, ...props }) => {
+ if (orientation === "left") {
+ return (
+ <ChevronLeftIcon className={cn("size-4", className)} {...props} />
+ );
+ }
+
+ if (orientation === "right") {
+ return (
+ <ChevronRightIcon
+ className={cn("size-4", className)}
+ {...props}
+ />
+ );
+ }
+
+ return (
+ <ChevronDownIcon className={cn("size-4", className)} {...props} />
+ );
+ },
+ DayButton: ({ ...props }) => (
+ <CalendarDayButton locale={locale} {...props} />
+ ),
+ WeekNumber: ({ children, ...props }) => {
+ return (
+ <td {...props}>
+ <div className="flex size-(--cell-size) items-center justify-center text-center">
+ {children}
+ </div>
+ </td>
+ );
+ },
+ ...components,
+ }}
+ {...props}
+ />
+ );
+}
+
+function CalendarDayButton({
+ className,
+ day,
+ modifiers,
+ locale,
+ ...props
+}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
+ const defaultClassNames = getDefaultClassNames();
+
+ const ref = React.useRef<HTMLButtonElement>(null);
+ React.useEffect(() => {
+ if (modifiers.focused) ref.current?.focus();
+ }, [modifiers.focused]);
+
+ return (
+ <Button
+ ref={ref}
+ variant="ghost"
+ size="icon"
+ data-day={day.date.toLocaleDateString(locale?.code)}
+ data-selected-single={
+ modifiers.selected &&
+ !modifiers.range_start &&
+ !modifiers.range_end &&
+ !modifiers.range_middle
+ }
+ data-range-start={modifiers.range_start}
+ data-range-end={modifiers.range_end}
+ data-range-middle={modifiers.range_middle}
+ className={cn(
+ "relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",
+ defaultClassNames.day,
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Calendar, CalendarDayButton };
diff --git a/packages/ui/src/components/card-table.tsx b/packages/ui/src/components/card-table.tsx
new file mode 100644
index 00000000..3ab3b4b7
--- /dev/null
+++ b/packages/ui/src/components/card-table.tsx
@@ -0,0 +1,34 @@
+"use client";
+
+import {
+ SimpleTable,
+ type SimpleTableColumn,
+} from "@crm/ui/components/simple-table";
+import type { ReactNode } from "react";
+
+export type CardTableColumn = SimpleTableColumn;
+
+export function CardTable({
+ columns,
+ children,
+}: {
+ columns: CardTableColumn[];
+ children: ReactNode;
+}) {
+ return (
+ <SimpleTable
+ className="min-w-[48rem] table-fixed [&_td:first-child]:pl-0 [&_th:first-child]:pl-0"
+ columns={columns}
+ >
+ {children}
+ </SimpleTable>
+ );
+}
+
+export function CardTableEmpty({ children }: { children: ReactNode }) {
+ return (
+ <p className="border-t py-6 text-center text-muted-foreground text-xs">
+ {children}
+ </p>
+ );
+}
diff --git a/packages/ui/src/components/card.tsx b/packages/ui/src/components/card.tsx
new file mode 100644
index 00000000..b8b59b62
--- /dev/null
+++ b/packages/ui/src/components/card.tsx
@@ -0,0 +1,91 @@
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+function Card({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card"
+ className={cn("flex flex-col gap-3", className)}
+ {...props}
+ />
+ );
+}
+
+function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-header"
+ className={cn(
+ "@container/card-header grid auto-rows-min items-center gap-x-4 gap-y-1 has-data-[slot=card-action]:grid-cols-[minmax(0,1fr)_auto] sm:has-data-[slot=card-description]:grid-rows-[auto_auto]",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-title"
+ className={cn("text-pretty text-sm font-medium", className)}
+ {...props}
+ />
+ );
+}
+
+function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-description"
+ className={cn(
+ "hidden text-pretty text-xs/relaxed text-muted-foreground sm:block",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function CardAction({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-action"
+ className={cn(
+ "col-start-2 row-span-2 row-start-1 flex items-center gap-2 self-center justify-self-end",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function CardContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-content"
+ className={cn("flex flex-col gap-4 border p-4 md:p-6", className)}
+ {...props}
+ />
+ );
+}
+
+function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-footer"
+ className={cn("flex items-center gap-3 border-t pt-4", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+};
diff --git a/packages/ui/src/components/carousel.tsx b/packages/ui/src/components/carousel.tsx
new file mode 100644
index 00000000..c5aa3e9c
--- /dev/null
+++ b/packages/ui/src/components/carousel.tsx
@@ -0,0 +1,241 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import useEmblaCarousel, {
+ type UseEmblaCarouselType,
+} from "embla-carousel-react";
+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
+import * as React from "react";
+
+type CarouselApi = UseEmblaCarouselType[1];
+type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
+type CarouselOptions = UseCarouselParameters[0];
+type CarouselPlugin = UseCarouselParameters[1];
+
+type CarouselProps = {
+ opts?: CarouselOptions;
+ plugins?: CarouselPlugin;
+ orientation?: "horizontal" | "vertical";
+ setApi?: (api: CarouselApi) => void;
+};
+
+type CarouselContextProps = {
+ carouselRef: ReturnType<typeof useEmblaCarousel>[0];
+ api: ReturnType<typeof useEmblaCarousel>[1];
+ scrollPrev: () => void;
+ scrollNext: () => void;
+ canScrollPrev: boolean;
+ canScrollNext: boolean;
+} & CarouselProps;
+
+const CarouselContext = React.createContext<CarouselContextProps | null>(null);
+
+function useCarousel() {
+ const context = React.useContext(CarouselContext);
+
+ if (!context) {
+ throw new Error("useCarousel must be used within a <Carousel />");
+ }
+
+ return context;
+}
+
+function Carousel({
+ orientation = "horizontal",
+ opts,
+ setApi,
+ plugins,
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & CarouselProps) {
+ const [carouselRef, api] = useEmblaCarousel(
+ {
+ ...opts,
+ axis: orientation === "horizontal" ? "x" : "y",
+ },
+ plugins,
+ );
+ const [canScrollPrev, setCanScrollPrev] = React.useState(false);
+ const [canScrollNext, setCanScrollNext] = React.useState(false);
+
+ const onSelect = React.useCallback((api: CarouselApi) => {
+ if (!api) return;
+ setCanScrollPrev(api.canScrollPrev());
+ setCanScrollNext(api.canScrollNext());
+ }, []);
+
+ const scrollPrev = React.useCallback(() => {
+ api?.scrollPrev();
+ }, [api]);
+
+ const scrollNext = React.useCallback(() => {
+ api?.scrollNext();
+ }, [api]);
+
+ const handleKeyDown = React.useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (event.key === "ArrowLeft") {
+ event.preventDefault();
+ scrollPrev();
+ } else if (event.key === "ArrowRight") {
+ event.preventDefault();
+ scrollNext();
+ }
+ },
+ [scrollPrev, scrollNext],
+ );
+
+ React.useEffect(() => {
+ if (!api || !setApi) return;
+ setApi(api);
+ }, [api, setApi]);
+
+ React.useEffect(() => {
+ if (!api) return;
+ onSelect(api);
+ api.on("reInit", onSelect);
+ api.on("select", onSelect);
+
+ return () => {
+ api?.off("select", onSelect);
+ };
+ }, [api, onSelect]);
+
+ return (
+ <CarouselContext.Provider
+ value={{
+ carouselRef,
+ api: api,
+ opts,
+ orientation:
+ orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
+ scrollPrev,
+ scrollNext,
+ canScrollPrev,
+ canScrollNext,
+ }}
+ >
+ <div
+ onKeyDownCapture={handleKeyDown}
+ className={cn("relative", className)}
+ role="region"
+ aria-roledescription="carousel"
+ data-slot="carousel"
+ {...props}
+ >
+ {children}
+ </div>
+ </CarouselContext.Provider>
+ );
+}
+
+function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
+ const { carouselRef, orientation } = useCarousel();
+
+ return (
+ <div
+ ref={carouselRef}
+ className="overflow-hidden"
+ data-slot="carousel-content"
+ >
+ <div
+ className={cn(
+ "flex",
+ orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
+ className,
+ )}
+ {...props}
+ />
+ </div>
+ );
+}
+
+function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
+ const { orientation } = useCarousel();
+
+ return (
+ <div
+ role="group"
+ aria-roledescription="slide"
+ data-slot="carousel-item"
+ className={cn(
+ "min-w-0 shrink-0 grow-0 basis-full",
+ orientation === "horizontal" ? "pl-4" : "pt-4",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function CarouselPrevious({
+ className,
+ variant = "outline",
+ size = "icon-sm",
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ const { orientation, scrollPrev, canScrollPrev } = useCarousel();
+
+ return (
+ <Button
+ data-slot="carousel-previous"
+ variant={variant}
+ size={size}
+ className={cn(
+ "absolute touch-manipulation",
+ orientation === "horizontal"
+ ? "inset-y-0 -left-12 my-auto"
+ : "-top-12 left-1/2 -translate-x-1/2 rotate-90",
+ className,
+ )}
+ disabled={!canScrollPrev}
+ onClick={scrollPrev}
+ {...props}
+ >
+ <ChevronLeftIcon />
+ <span className="sr-only">Previous slide</span>
+ </Button>
+ );
+}
+
+function CarouselNext({
+ className,
+ variant = "outline",
+ size = "icon-sm",
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ const { orientation, scrollNext, canScrollNext } = useCarousel();
+
+ return (
+ <Button
+ data-slot="carousel-next"
+ variant={variant}
+ size={size}
+ className={cn(
+ "absolute touch-manipulation",
+ orientation === "horizontal"
+ ? "inset-y-0 -right-12 my-auto"
+ : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
+ className,
+ )}
+ disabled={!canScrollNext}
+ onClick={scrollNext}
+ {...props}
+ >
+ <ChevronRightIcon />
+ <span className="sr-only">Next slide</span>
+ </Button>
+ );
+}
+
+export {
+ Carousel,
+ type CarouselApi,
+ CarouselContent,
+ CarouselItem,
+ CarouselNext,
+ CarouselPrevious,
+ useCarousel,
+};
diff --git a/packages/ui/src/components/chart.tsx b/packages/ui/src/components/chart.tsx
new file mode 100644
index 00000000..18adaa3c
--- /dev/null
+++ b/packages/ui/src/components/chart.tsx
@@ -0,0 +1,396 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import * as React from "react";
+import type { TooltipValueType } from "recharts";
+import * as RechartsPrimitive from "recharts";
+
+const THEMES = { light: "", dark: ".dark" } as const;
+
+const INITIAL_DIMENSION = { width: 320, height: 200 } as const;
+type TooltipNameType = number | string;
+
+export type ChartConfig = Record<
+ string,
+ {
+ label?: React.ReactNode;
+ icon?: React.ComponentType;
+ } & (
+ | { color?: string; theme?: never }
+ | { color?: never; theme: Record<keyof typeof THEMES, string> }
+ )
+>;
+
+type ChartContextProps = {
+ config: ChartConfig;
+};
+
+const ChartContext = React.createContext<ChartContextProps | null>(null);
+
+function useChart() {
+ const context = React.useContext(ChartContext);
+
+ if (!context) {
+ throw new Error("useChart must be used within a <ChartContainer />");
+ }
+
+ return context;
+}
+
+function ChartContainer({
+ id,
+ className,
+ children,
+ config,
+ initialDimension = INITIAL_DIMENSION,
+ ...props
+}: React.ComponentProps<"div"> & {
+ config: ChartConfig;
+ children: React.ComponentProps<
+ typeof RechartsPrimitive.ResponsiveContainer
+ >["children"];
+ initialDimension?: {
+ width: number;
+ height: number;
+ };
+}) {
+ const uniqueId = React.useId();
+ const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`;
+
+ return (
+ <ChartContext.Provider value={{ config }}>
+ <div
+ data-slot="chart"
+ data-chart={chartId}
+ className={cn(
+ "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
+ className,
+ )}
+ {...props}
+ >
+ <ChartStyle id={chartId} config={config} />
+ <RechartsPrimitive.ResponsiveContainer
+ initialDimension={initialDimension}
+ >
+ {children}
+ </RechartsPrimitive.ResponsiveContainer>
+ </div>
+ </ChartContext.Provider>
+ );
+}
+
+const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
+ const colorConfig = Object.entries(config).filter(
+ ([, config]) => config.theme ?? config.color,
+ );
+
+ if (!colorConfig.length) {
+ return null;
+ }
+
+ return (
+ <style
+ dangerouslySetInnerHTML={{
+ __html: Object.entries(THEMES)
+ .map(
+ ([theme, prefix]) => `
+${prefix} [data-chart=${id}] {
+${colorConfig
+ .map(([key, itemConfig]) => {
+ const color =
+ itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
+ itemConfig.color;
+ return color ? ` --color-${key}: ${color};` : null;
+ })
+ .join("\n")}
+}
+`,
+ )
+ .join("\n"),
+ }}
+ />
+ );
+};
+
+const ChartTooltip = RechartsPrimitive.Tooltip;
+
+function ChartTooltipContent({
+ active,
+ payload,
+ className,
+ indicator = "dot",
+ hideLabel = false,
+ hideIndicator = false,
+ label,
+ labelFormatter,
+ labelClassName,
+ formatter,
+ color,
+ nameKey,
+ labelKey,
+}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
+ React.ComponentProps<"div"> & {
+ hideLabel?: boolean;
+ hideIndicator?: boolean;
+ indicator?: "line" | "dot" | "dashed";
+ nameKey?: string;
+ labelKey?: string;
+ } & Omit<
+ RechartsPrimitive.DefaultTooltipContentProps<
+ TooltipValueType,
+ TooltipNameType
+ >,
+ "accessibilityLayer"
+ >) {
+ const { config } = useChart();
+
+ const tooltipLabel = React.useMemo(() => {
+ if (hideLabel || !payload?.length) {
+ return null;
+ }
+
+ const [item] = payload;
+ const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`;
+ const itemConfig = getPayloadConfigFromPayload(config, item, key);
+ const value =
+ !labelKey && typeof label === "string"
+ ? (config[label]?.label ?? label)
+ : itemConfig?.label;
+
+ if (labelFormatter) {
+ return (
+ <div className={cn("font-medium", labelClassName)}>
+ {labelFormatter(value, payload)}
+ </div>
+ );
+ }
+
+ if (!value) {
+ return null;
+ }
+
+ return <div className={cn("font-medium", labelClassName)}>{value}</div>;
+ }, [
+ label,
+ labelFormatter,
+ payload,
+ hideLabel,
+ labelClassName,
+ config,
+ labelKey,
+ ]);
+
+ if (!active || !payload?.length) {
+ return null;
+ }
+
+ const nestLabel = payload.length === 1 && indicator !== "dot";
+
+ return (
+ <div
+ className={cn(
+ "grid min-w-32 items-start gap-1.5 rounded-none border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
+ className,
+ )}
+ >
+ {!nestLabel ? tooltipLabel : null}
+ <div className="grid gap-1.5">
+ {payload
+ .filter((item) => item.type !== "none")
+ .map((item, index) => {
+ const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`;
+ const itemConfig = getPayloadConfigFromPayload(config, item, key);
+ const indicatorColor = color ?? item.payload?.fill ?? item.color;
+
+ return (
+ <div
+ key={index}
+ className={cn(
+ "flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
+ indicator === "dot" && "items-center",
+ )}
+ >
+ {formatter && item?.value !== undefined && item.name ? (
+ formatter(item.value, item.name, item, index, item.payload)
+ ) : (
+ <>
+ {itemConfig?.icon ? (
+ <itemConfig.icon />
+ ) : (
+ !hideIndicator && (
+ <div
+ className={cn(
+ "shrink-0 border-(--color-border) bg-(--color-bg)",
+ {
+ "size-1.5": indicator === "dot",
+ "w-1": indicator === "line",
+ "w-0 border-[1.5px] border-dashed bg-transparent":
+ indicator === "dashed",
+ "my-0.5": nestLabel && indicator === "dashed",
+ },
+ )}
+ style={
+ {
+ "--color-bg": indicatorColor,
+ "--color-border": indicatorColor,
+ } as React.CSSProperties
+ }
+ />
+ )
+ )}
+ <div
+ className={cn(
+ "flex flex-1 justify-between gap-4 leading-none",
+ nestLabel ? "items-end" : "items-center",
+ )}
+ >
+ <div className="grid gap-1.5">
+ {nestLabel ? tooltipLabel : null}
+ <span className="text-muted-foreground">
+ {itemConfig?.label ?? item.name}
+ </span>
+ </div>
+ {item.value != null && (
+ <span className="font-mono font-medium text-foreground tabular-nums">
+ {typeof item.value === "number"
+ ? item.value.toLocaleString()
+ : String(item.value)}
+ </span>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+const ChartLegend = RechartsPrimitive.Legend;
+
+function ChartLegendContent({
+ className,
+ hideIcon = false,
+ payload,
+ verticalAlign = "bottom",
+ nameKey,
+}: React.ComponentProps<"div"> & {
+ hideIcon?: boolean;
+ nameKey?: string;
+} & RechartsPrimitive.DefaultLegendContentProps) {
+ const { config } = useChart();
+
+ if (!payload?.length) {
+ return null;
+ }
+
+ return (
+ <div
+ className={cn(
+ "flex items-center justify-center gap-4",
+ verticalAlign === "top" ? "pb-3" : "pt-3",
+ className,
+ )}
+ >
+ {payload
+ .filter((item) => item.type !== "none")
+ .map((item, index) => {
+ const key = `${nameKey ?? item.dataKey ?? "value"}`;
+ const itemConfig = getPayloadConfigFromPayload(config, item, key);
+
+ return (
+ <div
+ key={index}
+ className={cn(
+ "flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",
+ )}
+ >
+ {itemConfig?.icon && !hideIcon ? (
+ <itemConfig.icon />
+ ) : (
+ <div
+ className="size-1.5 shrink-0"
+ style={{
+ backgroundColor: item.color,
+ }}
+ />
+ )}
+ {itemConfig?.label}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function getPayloadConfigFromPayload(
+ config: ChartConfig,
+ payload: unknown,
+ key: string,
+) {
+ if (typeof payload !== "object" || payload === null) {
+ return undefined;
+ }
+
+ const payloadPayload =
+ "payload" in payload &&
+ typeof payload.payload === "object" &&
+ payload.payload !== null
+ ? payload.payload
+ : undefined;
+
+ let configLabelKey: string = key;
+
+ if (
+ key in payload &&
+ typeof payload[key as keyof typeof payload] === "string"
+ ) {
+ configLabelKey = payload[key as keyof typeof payload] as string;
+ } else if (
+ payloadPayload &&
+ key in payloadPayload &&
+ typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
+ ) {
+ configLabelKey = payloadPayload[
+ key as keyof typeof payloadPayload
+ ] as string;
+ }
+
+ return configLabelKey in config ? config[configLabelKey] : config[key];
+}
+
+export {
+ Area,
+ AreaChart,
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Cell,
+ Label,
+ Legend,
+ Line,
+ LineChart,
+ Pie,
+ PieChart,
+ PolarAngleAxis,
+ PolarGrid,
+ PolarRadiusAxis,
+ RadialBar,
+ RadialBarChart,
+ ReferenceLine,
+ ResponsiveContainer,
+ Tooltip as RechartsTooltip,
+ XAxis,
+ YAxis,
+} from "recharts";
+
+export {
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartStyle,
+ ChartTooltip,
+ ChartTooltipContent,
+};
diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsx
new file mode 100644
index 00000000..b3496cc5
--- /dev/null
+++ b/packages/ui/src/components/checkbox.tsx
@@ -0,0 +1,31 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { CheckIcon } from "lucide-react";
+import { Checkbox as CheckboxPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Checkbox({
+ className,
+ ...props
+}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
+ return (
+ <CheckboxPrimitive.Root
+ data-slot="checkbox"
+ className={cn(
+ "peer relative flex size-4 shrink-0 items-center justify-center rounded-none border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",
+ className,
+ )}
+ {...props}
+ >
+ <CheckboxPrimitive.Indicator
+ data-slot="checkbox-indicator"
+ className="grid place-content-center text-current transition-none [&>svg]:size-3.5"
+ >
+ <CheckIcon />
+ </CheckboxPrimitive.Indicator>
+ </CheckboxPrimitive.Root>
+ );
+}
+
+export { Checkbox };
diff --git a/packages/ui/src/components/collapsible.tsx b/packages/ui/src/components/collapsible.tsx
new file mode 100644
index 00000000..fddca16e
--- /dev/null
+++ b/packages/ui/src/components/collapsible.tsx
@@ -0,0 +1,33 @@
+"use client";
+
+import { Collapsible as CollapsiblePrimitive } from "radix-ui";
+
+function Collapsible({
+ ...props
+}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
+ return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
+}
+
+function CollapsibleTrigger({
+ ...props
+}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
+ return (
+ <CollapsiblePrimitive.CollapsibleTrigger
+ data-slot="collapsible-trigger"
+ {...props}
+ />
+ );
+}
+
+function CollapsibleContent({
+ ...props
+}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
+ return (
+ <CollapsiblePrimitive.CollapsibleContent
+ data-slot="collapsible-content"
+ {...props}
+ />
+ );
+}
+
+export { Collapsible, CollapsibleContent, CollapsibleTrigger };
diff --git a/packages/ui/src/components/command.tsx b/packages/ui/src/components/command.tsx
new file mode 100644
index 00000000..ec2ce8b7
--- /dev/null
+++ b/packages/ui/src/components/command.tsx
@@ -0,0 +1,195 @@
+"use client";
+
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@crm/ui/components/dialog";
+import {
+ InputGroup,
+ InputGroupAddon,
+} from "@crm/ui/components/input-group";
+
+import { cn } from "@crm/ui/lib/utils";
+import { Command as CommandPrimitive } from "cmdk";
+import { CheckIcon, SearchIcon } from "lucide-react";
+import type * as React from "react";
+
+function Command({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive>) {
+ return (
+ <CommandPrimitive
+ data-slot="command"
+ className={cn(
+ "flex size-full flex-col overflow-hidden rounded-none bg-popover text-popover-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function CommandDialog({
+ title = "Command Palette",
+ description = "Search for a command to run...",
+ children,
+ className,
+ showCloseButton = false,
+ ...props
+}: React.ComponentProps<typeof Dialog> & {
+ title?: string;
+ description?: string;
+ className?: string;
+ showCloseButton?: boolean;
+}) {
+ return (
+ <Dialog {...props}>
+ <DialogHeader className="sr-only">
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{description}</DialogDescription>
+ </DialogHeader>
+ <DialogContent
+ className={cn(
+ "top-1/3 translate-y-0 overflow-hidden rounded-none p-0",
+ className,
+ )}
+ showCloseButton={showCloseButton}
+ >
+ {children}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function CommandInput({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Input>) {
+ return (
+ <div data-slot="command-input-wrapper" className="border-b pb-0">
+ <InputGroup className="h-8 border-none border-input/30 bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!">
+ <CommandPrimitive.Input
+ data-slot="command-input"
+ className={cn(
+ "w-full text-xs outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
+ className,
+ )}
+ {...props}
+ />
+ <InputGroupAddon>
+ <SearchIcon className="size-4 shrink-0 opacity-50" />
+ </InputGroupAddon>
+ </InputGroup>
+ </div>
+ );
+}
+
+function CommandList({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.List>) {
+ return (
+ <CommandPrimitive.List
+ data-slot="command-list"
+ className={cn(
+ "no-scrollbar max-h-72 scroll-py-0 overflow-x-hidden overflow-y-auto outline-none",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function CommandEmpty({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
+ return (
+ <CommandPrimitive.Empty
+ data-slot="command-empty"
+ className={cn("py-6 text-center text-xs", className)}
+ {...props}
+ />
+ );
+}
+
+function CommandGroup({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Group>) {
+ return (
+ <CommandPrimitive.Group
+ data-slot="command-group"
+ className={cn(
+ "overflow-hidden text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:text-muted-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function CommandSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
+ return (
+ <CommandPrimitive.Separator
+ data-slot="command-separator"
+ className={cn("-mx-1 h-px bg-border", className)}
+ {...props}
+ />
+ );
+}
+
+function CommandItem({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Item>) {
+ return (
+ <CommandPrimitive.Item
+ data-slot="command-item"
+ className={cn(
+ "group/command-item relative flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-hidden select-none in-data-[slot=dialog-content]:rounded-none! data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <CheckIcon className="ml-auto opacity-0 group-has-data-[slot=command-shortcut]/command-item:hidden group-data-[checked=true]/command-item:opacity-100" />
+ </CommandPrimitive.Item>
+ );
+}
+
+function CommandShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="command-shortcut"
+ className={cn(
+ "ml-auto text-xs tracking-widest text-muted-foreground group-data-selected/command-item:text-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Command,
+ CommandDialog,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+ CommandShortcut,
+};
diff --git a/packages/ui/src/components/context-menu.tsx b/packages/ui/src/components/context-menu.tsx
new file mode 100644
index 00000000..02d34ebf
--- /dev/null
+++ b/packages/ui/src/components/context-menu.tsx
@@ -0,0 +1,266 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { CheckIcon, ChevronRightIcon } from "lucide-react";
+import { ContextMenu as ContextMenuPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function ContextMenu({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
+ return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />;
+}
+
+function ContextMenuTrigger({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
+ return (
+ <ContextMenuPrimitive.Trigger
+ data-slot="context-menu-trigger"
+ className={cn("select-none", className)}
+ {...props}
+ />
+ );
+}
+
+function ContextMenuGroup({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
+ return (
+ <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
+ );
+}
+
+function ContextMenuPortal({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
+ return (
+ <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
+ );
+}
+
+function ContextMenuSub({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
+ return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />;
+}
+
+function ContextMenuRadioGroup({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
+ return (
+ <ContextMenuPrimitive.RadioGroup
+ data-slot="context-menu-radio-group"
+ {...props}
+ />
+ );
+}
+
+function ContextMenuContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Content> & {
+ side?: "top" | "right" | "bottom" | "left";
+}) {
+ return (
+ <ContextMenuPrimitive.Portal>
+ <ContextMenuPrimitive.Content
+ data-slot="context-menu-content"
+ className={cn(
+ "z-50 max-h-(--radix-context-menu-content-available-height) min-w-36 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-none bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ </ContextMenuPrimitive.Portal>
+ );
+}
+
+function ContextMenuItem({
+ className,
+ inset,
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
+ inset?: boolean;
+ variant?: "default" | "destructive";
+}) {
+ return (
+ <ContextMenuPrimitive.Item
+ data-slot="context-menu-item"
+ data-inset={inset}
+ data-variant={variant}
+ className={cn(
+ "group/context-menu-item relative flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 focus:*:[svg]:text-accent-foreground data-[variant=destructive]:*:[svg]:text-destructive",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ContextMenuSubTrigger({
+ className,
+ inset,
+ children,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
+ inset?: boolean;
+}) {
+ return (
+ <ContextMenuPrimitive.SubTrigger
+ data-slot="context-menu-sub-trigger"
+ data-inset={inset}
+ className={cn(
+ "flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRightIcon className="ml-auto" />
+ </ContextMenuPrimitive.SubTrigger>
+ );
+}
+
+function ContextMenuSubContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
+ return (
+ <ContextMenuPrimitive.SubContent
+ data-slot="context-menu-sub-content"
+ className={cn(
+ "z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-none border bg-popover text-popover-foreground shadow-lg duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ContextMenuCheckboxItem({
+ className,
+ children,
+ checked,
+ inset,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem> & {
+ inset?: boolean;
+}) {
+ return (
+ <ContextMenuPrimitive.CheckboxItem
+ data-slot="context-menu-checkbox-item"
+ data-inset={inset}
+ className={cn(
+ "relative flex cursor-default items-center gap-2 rounded-none py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="pointer-events-none absolute right-2">
+ <ContextMenuPrimitive.ItemIndicator>
+ <CheckIcon />
+ </ContextMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </ContextMenuPrimitive.CheckboxItem>
+ );
+}
+
+function ContextMenuRadioItem({
+ className,
+ children,
+ inset,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem> & {
+ inset?: boolean;
+}) {
+ return (
+ <ContextMenuPrimitive.RadioItem
+ data-slot="context-menu-radio-item"
+ data-inset={inset}
+ className={cn(
+ "relative flex cursor-default items-center gap-2 rounded-none py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ <span className="pointer-events-none absolute right-2">
+ <ContextMenuPrimitive.ItemIndicator>
+ <CheckIcon />
+ </ContextMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </ContextMenuPrimitive.RadioItem>
+ );
+}
+
+function ContextMenuLabel({
+ className,
+ inset,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
+ inset?: boolean;
+}) {
+ return (
+ <ContextMenuPrimitive.Label
+ data-slot="context-menu-label"
+ data-inset={inset}
+ className={cn(
+ "px-2 py-2 text-xs text-muted-foreground data-inset:pl-7",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ContextMenuSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
+ return (
+ <ContextMenuPrimitive.Separator
+ data-slot="context-menu-separator"
+ className={cn("-mx-1 h-px bg-border", className)}
+ {...props}
+ />
+ );
+}
+
+function ContextMenuShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="context-menu-shortcut"
+ className={cn(
+ "ml-auto text-xs tracking-widest text-muted-foreground group-focus/context-menu-item:text-accent-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ ContextMenu,
+ ContextMenuCheckboxItem,
+ ContextMenuContent,
+ ContextMenuGroup,
+ ContextMenuItem,
+ ContextMenuLabel,
+ ContextMenuPortal,
+ ContextMenuRadioGroup,
+ ContextMenuRadioItem,
+ ContextMenuSeparator,
+ ContextMenuShortcut,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+ ContextMenuTrigger,
+};
diff --git a/packages/ui/src/components/danger-card.tsx b/packages/ui/src/components/danger-card.tsx
new file mode 100644
index 00000000..6afe69d7
--- /dev/null
+++ b/packages/ui/src/components/danger-card.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@crm/ui/components/alert-dialog";
+import { Button } from "@crm/ui/components/button";
+import {
+ Card,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@crm/ui/components/card";
+import { CardTable } from "@crm/ui/components/card-table";
+import { TableCell, TableRow } from "@crm/ui/components/table";
+import type { ReactNode } from "react";
+
+export type DangerAction = {
+ id: string;
+ action: ReactNode;
+ description: ReactNode;
+ buttonLabel: string;
+ disabled?: boolean;
+ confirmTitle: string;
+ confirmDescription: ReactNode;
+ confirmLabel: string;
+ onConfirm: () => void;
+};
+
+export function DangerCard({
+ title = "Danger zone",
+ description,
+ actions,
+}: {
+ title?: string;
+ description: ReactNode;
+ actions: DangerAction[];
+}) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{title}</CardTitle>
+ <CardDescription>{description}</CardDescription>
+ </CardHeader>
+ <CardTable
+ columns={[
+ { header: "Action", width: "w-64" },
+ { header: "Description" },
+ { header: "", width: "w-40", srLabel: "Actions", align: "right" },
+ ]}
+ >
+ {actions.map((item) => (
+ <TableRow key={item.id} className="hover:bg-transparent">
+ <TableCell className="px-3 py-3 font-medium">
+ {item.action}
+ </TableCell>
+ <TableCell className="whitespace-normal px-3 py-3 text-muted-foreground">
+ {item.description}
+ </TableCell>
+ <TableCell className="px-3 py-3 text-right">
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button
+ variant="destructive"
+ size="sm"
+ disabled={item.disabled}
+ >
+ {item.buttonLabel}
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{item.confirmTitle}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {item.confirmDescription}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={item.onConfirm}>
+ {item.confirmLabel}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </TableCell>
+ </TableRow>
+ ))}
+ </CardTable>
+ </Card>
+ );
+}
diff --git a/packages/ui/src/components/dashboard-chart.tsx b/packages/ui/src/components/dashboard-chart.tsx
new file mode 100644
index 00000000..0a0333af
--- /dev/null
+++ b/packages/ui/src/components/dashboard-chart.tsx
@@ -0,0 +1,553 @@
+"use client";
+
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+ ChartTooltipContent,
+} from "@crm/ui/components/chart";
+import { cn } from "@crm/ui/lib/utils";
+import * as React from "react";
+import {
+ Area,
+ AreaChart,
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Cell,
+ Label,
+ LabelList,
+ Pie,
+ PieChart,
+ Text,
+ XAxis,
+} from "recharts";
+
+type Datum = Record<string, number | string | null>;
+
+type CartesianProps = {
+ /** Rows to plot, already shaped for the chart. */
+ data: Datum[];
+ /** Maps each series key to a label + color (use `color: "var(--chart-N)"`). */
+ config: ChartConfig;
+ /** The category (x-axis) key. */
+ xKey: string;
+ /** Which keys in `config` to draw as series. Defaults to all config keys. */
+ series?: string[];
+ className?: string;
+ /** Plot height in px. Default 200. */
+ height?: number;
+ /** Show the x-axis tick labels. Default true. */
+ showXAxis?: boolean;
+ /** Show a legend (useful for multi-series). Default false. */
+ showLegend?: boolean;
+ /** Format an x-axis tick (e.g. shorten a date). */
+ formatX?: (value: string) => string;
+};
+
+function seriesKeys(config: ChartConfig, series?: string[]) {
+ return series ?? Object.keys(config);
+}
+
+const tooltip = (formatX?: (value: string) => string) => (
+ <ChartTooltip
+ cursor={false}
+ content={
+ <ChartTooltipContent
+ indicator="dot"
+ labelFormatter={formatX ? (label) => formatX(String(label)) : undefined}
+ />
+ }
+ />
+);
+
+const X_AXIS_PROPS = {
+ tickLine: false,
+ axisLine: false,
+ tickMargin: 12,
+} as const;
+
+/**
+ * With a full-bleed plot (zero horizontal margin) the first and last category
+ * labels sit at the very edges, where a centered label clips against the card.
+ * Anchor the edge labels inward (start / end) and center the rest. Recharts
+ * clones this element per tick, injecting the computed coordinates + index.
+ */
+function EdgeTick({
+ x,
+ y,
+ payload,
+ index,
+ visibleTicksCount,
+ formatX,
+}: {
+ x?: number;
+ y?: number;
+ payload?: { value: string | number };
+ index?: number;
+ visibleTicksCount?: number;
+ formatX?: (value: string) => string;
+}) {
+ const isFirst = index === 0;
+ const isLast = index === (visibleTicksCount ?? 0) - 1;
+ const anchor = isFirst ? "start" : isLast ? "end" : "middle";
+ const raw = String(payload?.value ?? "");
+ return (
+ <Text
+ x={x}
+ y={y}
+ textAnchor={anchor}
+ verticalAnchor="start"
+ className="fill-muted-foreground text-xs"
+ >
+ {formatX ? formatX(raw) : raw}
+ </Text>
+ );
+}
+
+type DitherVariant = "gradient" | "dotted" | "hatched" | "solid";
+type Bloom = "off" | "low" | "high" | "aura";
+
+function bloomFilter(bloom: Bloom, color: string) {
+ switch (bloom) {
+ case "low":
+ return `drop-shadow(0 0 2px ${color})`;
+ case "high":
+ return `drop-shadow(0 0 5px ${color})`;
+ case "aura":
+ return `drop-shadow(0 0 3px ${color}) drop-shadow(0 0 9px ${color})`;
+ default:
+ return undefined;
+ }
+}
+
+function ditherPatternId(base: string, key: string) {
+ return `${base}-dither-${key}`;
+}
+
+function ditherFadeId(base: string, key: string) {
+ return `${base}-fade-${key}`;
+}
+
+function DitherDefs({
+ base,
+ keys,
+ variant,
+}: {
+ base: string;
+ keys: string[];
+ variant: DitherVariant;
+}) {
+ if (variant === "solid") {
+ return null;
+ }
+ return (
+ <>
+ {keys.map((key) => {
+ const color = `var(--color-${key})`;
+ const id = ditherPatternId(base, key);
+ if (variant === "hatched") {
+ return (
+ <pattern
+ key={id}
+ id={id}
+ width={6}
+ height={6}
+ patternUnits="userSpaceOnUse"
+ patternTransform="rotate(45)"
+ >
+ <line
+ x1={0}
+ y1={0}
+ x2={0}
+ y2={6}
+ stroke={color}
+ strokeWidth={1.5}
+ />
+ </pattern>
+ );
+ }
+ return (
+ <pattern
+ key={id}
+ id={id}
+ width={4}
+ height={4}
+ patternUnits="userSpaceOnUse"
+ >
+ <rect x={0} y={0} width={1.4} height={1.4} fill={color} />
+ <rect x={2} y={2} width={1.4} height={1.4} fill={color} />
+ </pattern>
+ );
+ })}
+ {variant === "gradient"
+ ? keys.map((key) => {
+ const fadeId = ditherFadeId(base, key);
+ const fadeGradId = `${fadeId}-grad`;
+ return (
+ <React.Fragment key={fadeId}>
+ <linearGradient id={fadeGradId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor="white" stopOpacity={0.06} />
+ <stop offset="55%" stopColor="white" stopOpacity={0.45} />
+ <stop offset="100%" stopColor="white" stopOpacity={0.95} />
+ </linearGradient>
+ <mask id={fadeId}>
+ <rect
+ x="0"
+ y="0"
+ width="100%"
+ height="100%"
+ fill={`url(#${fadeGradId})`}
+ />
+ </mask>
+ </React.Fragment>
+ );
+ })
+ : null}
+ </>
+ );
+}
+
+function AreaTrend({
+ data,
+ config,
+ xKey,
+ series,
+ className,
+ height = 200,
+ showXAxis = true,
+ showLegend = false,
+ formatX,
+ stacked = false,
+ variant = "gradient",
+ bloom = "low",
+}: CartesianProps & {
+ stacked?: boolean;
+ variant?: DitherVariant;
+ bloom?: Bloom;
+}) {
+ const keys = seriesKeys(config, series);
+ const gradientId = React.useId().replace(/:/g, "");
+ const dithered = variant !== "solid";
+
+ return (
+ <ChartContainer
+ config={config}
+ className={cn("aspect-auto w-full", className)}
+ style={{ height }}
+ >
+ <AreaChart data={data} margin={{ left: 0, right: 0, top: 10, bottom: 0 }}>
+ <defs>
+ {keys.map((key) => (
+ <linearGradient
+ key={key}
+ id={`${gradientId}-${key}`}
+ x1="0"
+ y1="0"
+ x2="0"
+ y2="1"
+ >
+ <stop
+ offset="5%"
+ stopColor={`var(--color-${key})`}
+ stopOpacity={0.3}
+ />
+ <stop
+ offset="95%"
+ stopColor={`var(--color-${key})`}
+ stopOpacity={0}
+ />
+ </linearGradient>
+ ))}
+ <DitherDefs base={gradientId} keys={keys} variant={variant} />
+ </defs>
+ <CartesianGrid vertical={false} stroke="var(--border)" />
+ <XAxis
+ dataKey={xKey}
+ hide={!showXAxis}
+ tick={<EdgeTick formatX={formatX} />}
+ {...X_AXIS_PROPS}
+ />
+ {tooltip(formatX)}
+ {keys.map((key) => (
+ <Area
+ key={key}
+ dataKey={key}
+ type="monotone"
+ stroke={`var(--color-${key})`}
+ strokeWidth={2}
+ fill={`url(#${gradientId}-${key})`}
+ stackId={stacked ? "stack" : undefined}
+ dot={false}
+ activeDot={{ r: 3, strokeWidth: 0 }}
+ style={
+ bloom === "off"
+ ? undefined
+ : { filter: bloomFilter(bloom, `var(--color-${key})`) }
+ }
+ />
+ ))}
+ {dithered
+ ? keys.map((key) => (
+ <Area
+ key={`dither-${key}`}
+ dataKey={key}
+ type="monotone"
+ stroke="none"
+ fill={`url(#${ditherPatternId(gradientId, key)})`}
+ fillOpacity={1}
+ mask={
+ variant === "gradient"
+ ? `url(#${ditherFadeId(gradientId, key)})`
+ : undefined
+ }
+ stackId={stacked ? "dither-stack" : undefined}
+ dot={false}
+ activeDot={false}
+ isAnimationActive={false}
+ legendType="none"
+ tooltipType="none"
+ />
+ ))
+ : null}
+ {showLegend ? (
+ <ChartLegend
+ verticalAlign="bottom"
+ content={<ChartLegendContent />}
+ />
+ ) : null}
+ </AreaChart>
+ </ChartContainer>
+ );
+}
+
+/**
+ * Grouped/stacked bar chart for discrete buckets (per-month counts, breakdowns).
+ * Same prop shape as {@link AreaTrend} for drop-in consistency.
+ */
+function BarTrend({
+ data,
+ config,
+ xKey,
+ series,
+ className,
+ height = 180,
+ showXAxis = true,
+ showLegend = false,
+ formatX,
+ stacked = false,
+}: CartesianProps & { stacked?: boolean }) {
+ const keys = seriesKeys(config, series);
+
+ return (
+ <ChartContainer
+ config={config}
+ className={cn("aspect-auto w-full", className)}
+ style={{ height }}
+ >
+ <BarChart data={data} margin={{ left: 0, right: 0, top: 10, bottom: 0 }}>
+ <CartesianGrid vertical={false} stroke="var(--border)" />
+ <XAxis
+ dataKey={xKey}
+ hide={!showXAxis}
+ tick={<EdgeTick formatX={formatX} />}
+ {...X_AXIS_PROPS}
+ />
+ {tooltip(formatX)}
+ {keys.map((key) => (
+ <Bar
+ key={key}
+ dataKey={key}
+ fill={`var(--color-${key})`}
+ radius={2}
+ stackId={stacked ? "stack" : undefined}
+ maxBarSize={40}
+ />
+ ))}
+ {showLegend ? (
+ <ChartLegend
+ verticalAlign="bottom"
+ content={<ChartLegendContent />}
+ />
+ ) : null}
+ </BarChart>
+ </ChartContainer>
+ );
+}
+
+type DonutSlice = { key: string; label: string; value: number; color: string };
+
+function BarStat({
+ data,
+ className,
+ height = 200,
+ onBarClick,
+}: {
+ data: DonutSlice[];
+ className?: string;
+ height?: number;
+ onBarClick?: (key: string) => void;
+}) {
+ const config: ChartConfig = Object.fromEntries(
+ data.map((d) => [d.key, { label: d.label, color: d.color }]),
+ );
+
+ return (
+ <ChartContainer
+ config={config}
+ className={cn("aspect-auto w-full", className)}
+ style={{ height }}
+ >
+ <BarChart data={data} margin={{ left: 0, right: 0, top: 24, bottom: 0 }}>
+ <CartesianGrid vertical={false} stroke="var(--border)" />
+ <XAxis
+ dataKey="label"
+ tickLine={false}
+ axisLine={false}
+ tickMargin={12}
+ tick={{ fill: "var(--muted-foreground)", fontSize: 12 }}
+ />
+ <ChartTooltip
+ cursor={false}
+ content={<ChartTooltipContent hideLabel nameKey="key" />}
+ />
+ <Bar
+ dataKey="value"
+ radius={2}
+ maxBarSize={40}
+ className={onBarClick ? "cursor-pointer" : undefined}
+ onClick={
+ onBarClick
+ ? (_, index) => {
+ const slice = data[index];
+ if (slice) onBarClick(slice.key);
+ }
+ : undefined
+ }
+ >
+ <LabelList
+ dataKey="value"
+ position="top"
+ className="fill-foreground"
+ fontSize={12}
+ />
+ {data.map((slice) => (
+ <Cell key={slice.key} fill={slice.color} />
+ ))}
+ </Bar>
+ </BarChart>
+ </ChartContainer>
+ );
+}
+
+/**
+ * Donut chart with an optional bold value in the middle and a faint track
+ * behind the data — ideal for a single-metric breakdown (members by role,
+ * findings by severity, plan usage).
+ */
+function DonutStat({
+ data,
+ className,
+ height = 200,
+ centerValue,
+ centerLabel,
+ onSliceClick,
+}: {
+ data: DonutSlice[];
+ className?: string;
+ height?: number;
+ centerValue?: React.ReactNode;
+ centerLabel?: React.ReactNode;
+ onSliceClick?: (key: string) => void;
+}) {
+ const config: ChartConfig = Object.fromEntries(
+ data.map((d) => [d.key, { label: d.label, color: d.color }]),
+ );
+ const hasCenter = centerValue != null || centerLabel != null;
+ const innerRadius = Math.round(height * 0.34);
+ const outerRadius = Math.round(height * 0.46);
+
+ return (
+ <ChartContainer
+ config={config}
+ className={cn("mx-auto aspect-square", className)}
+ style={{ height }}
+ >
+ <PieChart>
+ <ChartTooltip
+ cursor={false}
+ content={<ChartTooltipContent hideLabel nameKey="key" />}
+ />
+ {/* Faint track so a partial ring still reads as a full circle. */}
+ <Pie
+ data={[{ value: 1 }]}
+ dataKey="value"
+ innerRadius={innerRadius}
+ outerRadius={outerRadius}
+ fill="var(--muted)"
+ fillOpacity={0.45}
+ stroke="none"
+ isAnimationActive={false}
+ />
+ <Pie
+ data={data}
+ dataKey="value"
+ nameKey="key"
+ innerRadius={innerRadius}
+ outerRadius={outerRadius}
+ paddingAngle={data.length > 1 ? 2 : 0}
+ className={onSliceClick ? "cursor-pointer" : undefined}
+ onClick={
+ onSliceClick
+ ? (_, index) => {
+ const slice = data[index];
+ if (slice) onSliceClick(slice.key);
+ }
+ : undefined
+ }
+ >
+ {data.map((slice) => (
+ <Cell key={slice.key} fill={slice.color} stroke="none" />
+ ))}
+ {hasCenter ? (
+ <Label
+ content={({ viewBox }) => {
+ if (!viewBox || !("cx" in viewBox)) return null;
+ return (
+ <text
+ x={viewBox.cx}
+ y={viewBox.cy}
+ textAnchor="middle"
+ dominantBaseline="middle"
+ >
+ <tspan
+ x={viewBox.cx}
+ y={viewBox.cy}
+ className="fill-foreground font-medium text-2xl tabular-nums"
+ >
+ {String(centerValue ?? "")}
+ </tspan>
+ {centerLabel != null ? (
+ <tspan
+ x={viewBox.cx}
+ y={(viewBox.cy ?? 0) + 20}
+ className="fill-muted-foreground text-xs"
+ >
+ {String(centerLabel)}
+ </tspan>
+ ) : null}
+ </text>
+ );
+ }}
+ />
+ ) : null}
+ </Pie>
+ </PieChart>
+ </ChartContainer>
+ );
+}
+
+export type { Datum, DonutSlice };
+export { AreaTrend, BarStat, BarTrend, DonutStat };
diff --git a/packages/ui/src/components/dashboard.tsx b/packages/ui/src/components/dashboard.tsx
new file mode 100644
index 00000000..c5ee165a
--- /dev/null
+++ b/packages/ui/src/components/dashboard.tsx
@@ -0,0 +1,257 @@
+import { Skeleton } from "@crm/ui/components/skeleton";
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+/**
+ * Reusable, server-safe dashboard layout primitives. They establish their own
+ * container-query context so the same grids reflow correctly regardless of
+ * where the dashboard is mounted — sidebar open or not.
+ *
+ * Compose them as:
+ * <DashboardSection title="Overview">
+ * <StatGroup>{stats}</StatGroup>
+ * <DashboardRow>{hero}{aside}</DashboardRow>
+ * </DashboardSection>
+ */
+
+/**
+ * An elevated KPI strip: one bordered surface holding several {@link StatCard}s
+ * separated by hairline dividers (stacked + horizontal on narrow widths, a
+ * single divided row on wide). This is the premium alternative to a row of
+ * standalone boxes — see the surfaces guideline.
+ */
+function StatGroup({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="stat-group"
+ className={cn("@container/stats overflow-hidden border", className)}
+ {...props}
+ >
+ <div
+ className={cn(
+ "grid grid-cols-2 @2xl/stats:grid-cols-4",
+ "[&:nth-child(2n)]:border-l [&:nth-child(n+3)]:border-t",
+ "@2xl/stats:[&>*]:border-t-0 @2xl/stats:[&>*]:border-l @2xl/stats:[&>*:first-child]:border-l-0",
+ )}
+ >
+ {children}
+ </div>
+ </div>
+ );
+}
+
+const GRID_COLS = {
+ 2: "@md/dashboard:grid-cols-2",
+ 3: "@md/dashboard:grid-cols-2 @4xl/dashboard:grid-cols-3",
+ 4: "@md/dashboard:grid-cols-2 @4xl/dashboard:grid-cols-4",
+} as const;
+
+function DashboardGrid({
+ className,
+ columns = 4,
+ ...props
+}: React.ComponentProps<"div"> & { columns?: keyof typeof GRID_COLS }) {
+ return (
+ <div className="@container/dashboard">
+ <div
+ data-slot="dashboard-grid"
+ className={cn("grid grid-cols-1 gap-4", GRID_COLS[columns], className)}
+ {...props}
+ />
+ </div>
+ );
+}
+
+/**
+ * A 2-up content row that collapses to a single column on narrow widths.
+ * By default the first child takes ~2/3 (the hero chart) and the second ~1/3
+ * (an aside). Pass `split="even"` for a 1:1 layout.
+ */
+function DashboardRow({
+ className,
+ split = "hero",
+ ...props
+}: React.ComponentProps<"div"> & { split?: "hero" | "even" }) {
+ return (
+ <div className="@container/dashboard">
+ <div
+ data-slot="dashboard-row"
+ className={cn(
+ "grid grid-cols-1 gap-4",
+ split === "hero"
+ ? "@3xl/dashboard:grid-cols-[2fr_1fr]"
+ : "@3xl/dashboard:grid-cols-2",
+ className,
+ )}
+ {...props}
+ />
+ </div>
+ );
+}
+
+/**
+ * A bordered, subtly elevated surface for a single chart, with an optional
+ * header (title / description / action) and footer. The body stretches so
+ * sibling cards in a {@link DashboardRow} stay the same height. Pair with the
+ * client chart wrappers in `dashboard-chart.tsx`.
+ */
+function ChartCard({
+ className,
+ title,
+ description,
+ action,
+ footer,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"div">, "title"> & {
+ title?: React.ReactNode;
+ description?: React.ReactNode;
+ action?: React.ReactNode;
+ footer?: React.ReactNode;
+}) {
+ return (
+ <div
+ data-slot="chart-card"
+ className={cn("flex flex-col border", className)}
+ {...props}
+ >
+ {title || description || action ? (
+ <div className="flex items-start justify-between gap-4 p-5 md:p-6">
+ <div className="flex min-w-0 flex-col gap-1">
+ {title ? (
+ <h3 className="truncate font-medium text-sm">{title}</h3>
+ ) : null}
+ {description ? (
+ <p className="text-muted-foreground text-xs/relaxed">
+ {description}
+ </p>
+ ) : null}
+ </div>
+ {action ? <div className="shrink-0">{action}</div> : null}
+ </div>
+ ) : null}
+ <div className="flex flex-1 flex-col justify-center pb-5 md:pb-6">
+ {children}
+ </div>
+ {footer ? (
+ <div className="border-t px-5 py-3 text-muted-foreground text-xs md:px-6">
+ {footer}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+function KpiCard({
+ className,
+ title,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"div">, "title"> & {
+ title: React.ReactNode;
+}) {
+ return (
+ <div
+ data-slot="kpi-card"
+ className={cn("flex flex-col gap-4 border p-5 md:p-6", className)}
+ {...props}
+ >
+ <h3 className="truncate font-medium text-muted-foreground text-sm">
+ {title}
+ </h3>
+ {children}
+ </div>
+ );
+}
+
+function DashboardSection({
+ className,
+ title,
+ description,
+ action,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"section">, "title"> & {
+ title?: React.ReactNode;
+ description?: React.ReactNode;
+ action?: React.ReactNode;
+}) {
+ const hasHeader = title || description || action;
+ return (
+ <section
+ data-slot="dashboard-section"
+ className={cn("flex flex-col gap-4", className)}
+ {...props}
+ >
+ {hasHeader ? (
+ <div className="flex flex-wrap items-end justify-between gap-x-4 gap-y-1">
+ <div className="flex flex-col gap-1">
+ {title ? (
+ <h2 className="font-medium text-base tracking-tight">{title}</h2>
+ ) : null}
+ {description ? (
+ <p className="text-muted-foreground text-sm">{description}</p>
+ ) : null}
+ </div>
+ {action ? <div className="shrink-0">{action}</div> : null}
+ </div>
+ ) : null}
+ {children}
+ </section>
+ );
+}
+
+/**
+ * A layout-matched loading state for the default dashboard composition
+ * (KPI strip + hero/aside chart row). Use as a `<Suspense>` fallback so the
+ * page paints instantly while server data streams in.
+ */
+function DashboardSkeleton({
+ stats = 4,
+ className,
+}: {
+ stats?: number;
+ className?: string;
+}) {
+ return (
+ <div
+ data-slot="dashboard-skeleton"
+ className={cn("flex flex-col gap-6", className)}
+ aria-hidden
+ >
+ <StatGroup>
+ {Array.from({ length: stats }).map((_, i) => (
+ <div key={i} className="flex flex-col gap-3 p-4 md:p-6">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-8 w-16" />
+ <Skeleton className="h-3 w-28" />
+ </div>
+ ))}
+ </StatGroup>
+ <DashboardRow>
+ <div className="flex flex-col gap-4 border p-5 md:p-6">
+ <Skeleton className="h-4 w-40" />
+ <Skeleton className="h-[200px] w-full" />
+ </div>
+ <div className="flex flex-col items-center gap-4 border p-5 md:p-6">
+ <Skeleton className="h-4 w-32 self-start" />
+ <Skeleton className="size-[200px] rounded-full" />
+ </div>
+ </DashboardRow>
+ </div>
+ );
+}
+
+export {
+ ChartCard,
+ DashboardGrid,
+ DashboardRow,
+ DashboardSection,
+ DashboardSkeleton,
+ KpiCard,
+ StatGroup,
+};
diff --git a/packages/ui/src/components/data-table.tsx b/packages/ui/src/components/data-table.tsx
new file mode 100644
index 00000000..3c2931b9
--- /dev/null
+++ b/packages/ui/src/components/data-table.tsx
@@ -0,0 +1,639 @@
+"use client";
+
+import ArrowDown from "@carbon/icons-react/es/ArrowDown";
+import ArrowsVertical from "@carbon/icons-react/es/ArrowsVertical";
+import ArrowUp from "@carbon/icons-react/es/ArrowUp";
+import ChevronDown from "@carbon/icons-react/es/ChevronDown";
+import ChevronRight from "@carbon/icons-react/es/ChevronRight";
+import Column from "@carbon/icons-react/es/Column";
+import Filter from "@carbon/icons-react/es/Filter";
+import Search from "@carbon/icons-react/es/Search";
+import { Button } from "@crm/ui/components/button";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@crm/ui/components/dropdown-menu";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@crm/ui/components/input-group";
+import { Spinner } from "@crm/ui/components/spinner";
+import { TablePagination } from "@crm/ui/components/table-pagination";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@crm/ui/components/table";
+import { ROW_ACCENT, ROW_ACCENT_EXPANDABLE } from "@crm/ui/lib/row-accent";
+import type { TableQueryState } from "@crm/ui/lib/table-query";
+import { cn } from "@crm/ui/lib/utils";
+import { parseAsArrayOf, parseAsString, useQueryState } from "nuqs";
+import {
+ Fragment,
+ type ReactNode,
+ useDeferredValue,
+ useId,
+ useMemo,
+ useState,
+} from "react";
+
+export type DataTableColumn<TRow> = {
+ id: string;
+ header: ReactNode;
+ cell: (row: TRow) => ReactNode;
+ /** Name used in the Sort and Columns menus when `header` is not a string. */
+ label?: string;
+ sortable?: boolean;
+ width?: string;
+ align?: "left" | "right" | "center";
+ headClassName?: string;
+ cellClassName?: string;
+ hideable?: boolean;
+ defaultHidden?: boolean;
+ hideBelow?: "sm" | "md" | "lg";
+};
+
+export type DataTableFacet = {
+ id: string;
+ label: string;
+ options: { value: string; label: string }[];
+};
+
+export type DataTableTabs = {
+ id: string;
+ allLabel?: string;
+ options: { value: string; label: string }[];
+};
+
+export type DataTableExpandable<TRow, TSub> = {
+ isExpandable: (row: TRow) => boolean;
+ getSubRows: (row: TRow) => TSub[];
+ getSubRowId: (sub: TSub, row: TRow) => string;
+ renderSubCell: (sub: TSub, columnId: string, row: TRow) => ReactNode;
+ onSubRowClick?: (sub: TSub, row: TRow) => void;
+};
+
+export type DataTableProps<TRow, TSub> = {
+ query: TableQueryState;
+ columns: DataTableColumn<TRow>[];
+ getRowId: (row: TRow) => string;
+ rows: TRow[];
+ total: number;
+ facetCounts?: Record<string, Record<string, number>>;
+ loading?: boolean;
+ searchPlaceholder?: string;
+ facets?: DataTableFacet[];
+ tabs?: DataTableTabs;
+ onRowClick?: (row: TRow) => void;
+ expandable?: DataTableExpandable<TRow, TSub>;
+ actions?: ReactNode;
+ leadingActions?: ReactNode;
+ meta?: ReactNode;
+ empty?: ReactNode;
+ className?: string;
+ tableClassName?: string;
+};
+
+const HIDE_BELOW_CLASS = {
+ sm: "hidden sm:table-cell",
+ md: "hidden md:table-cell",
+ lg: "hidden lg:table-cell",
+} as const;
+
+const ALIGN_CLASS = {
+ left: "",
+ right: "text-right",
+ center: "text-center",
+} as const;
+
+function columnLabel<TRow>(column: DataTableColumn<TRow>): string {
+ if (column.label) return column.label;
+ return typeof column.header === "string" ? column.header : column.id;
+}
+
+function SortIndicator({
+ active,
+ dir,
+}: {
+ active: boolean;
+ dir: "asc" | "desc";
+}) {
+ return (
+ <span className="text-muted-foreground">
+ {active ? (
+ dir === "asc" ? (
+ <ArrowUp size={12} />
+ ) : (
+ <ArrowDown size={12} />
+ )
+ ) : (
+ <ArrowsVertical size={12} className="opacity-40" />
+ )}
+ </span>
+ );
+}
+
+/**
+ * The list view for every module.
+ *
+ * Everything it renders is driven by `query`, which is URL state — so a filtered,
+ * sorted, paged view is a link. Rows arrive already filtered and paged from the
+ * API; this component never slices data itself.
+ *
+ * Two params it owns directly, because they are presentation rather than data:
+ * `expand` (which rows are open) and `hide` (which columns are off).
+ */
+export function DataTable<TRow, TSub = unknown>({
+ query,
+ columns,
+ getRowId,
+ rows,
+ total,
+ facetCounts,
+ loading,
+ searchPlaceholder = "Search…",
+ facets,
+ tabs,
+ onRowClick,
+ expandable,
+ actions,
+ leadingActions,
+ meta,
+ empty,
+ className,
+ tableClassName,
+}: DataTableProps<TRow, TSub>) {
+ const [expandedIds, setExpandedIds] = useQueryState(
+ "expand",
+ parseAsArrayOf(parseAsString).withDefault([]),
+ );
+ const expanded = useMemo(() => new Set(expandedIds), [expandedIds]);
+ const defaultHiddenIds = useMemo(
+ () => columns.filter((column) => column.defaultHidden).map((c) => c.id),
+ [columns],
+ );
+ const [hidden, setHidden] = useQueryState(
+ "hide",
+ parseAsArrayOf(parseAsString).withDefault(defaultHiddenIds),
+ );
+ const [filtersOpen, setFiltersOpen] = useState(false);
+ const filtersId = useId();
+
+ const hideable = columns.filter((column) => column.hideable !== false);
+ const visibleColumns = columns.filter(
+ (column) => !hidden.includes(column.id),
+ );
+ const sortableColumns = columns.filter((column) => column.sortable);
+
+ const tabCounts = tabs ? facetCounts?.[tabs.id] : undefined;
+ const activeTabOption =
+ query.tab === "all"
+ ? undefined
+ : tabs?.options.find((option) => option.value === query.tab);
+ const activeTabLabel = activeTabOption
+ ? activeTabOption.label
+ : (tabs?.allLabel ?? "All");
+
+ // Keeps typing responsive: the input updates immediately, the (expensive)
+ // table body re-renders at a lower priority.
+ const deferredRows = useDeferredValue(rows);
+ const anyExpandable =
+ expandable != null &&
+ deferredRows.some((row) => expandable.isExpandable(row));
+ const colCount = visibleColumns.length + (anyExpandable ? 1 : 0);
+
+ const pageSize = query.pageSize;
+ const totalPages = Math.max(1, Math.ceil(total / pageSize));
+
+ const hasFilterControls =
+ tabs != null ||
+ (facets?.length ?? 0) > 0 ||
+ sortableColumns.length > 0 ||
+ anyExpandable ||
+ hideable.length > 0 ||
+ actions != null ||
+ leadingActions != null;
+ const activeFilterCount =
+ (tabs && query.tab !== "all" ? 1 : 0) +
+ (facets?.filter((facet) => (query.filters[facet.id] ?? "all") !== "all")
+ .length ?? 0);
+
+ return (
+ <div className={cn("flex min-h-0 flex-1 flex-col gap-3", className)}>
+ <div className="flex flex-col gap-3">
+ {hasFilterControls && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="w-full justify-between sm:hidden"
+ aria-expanded={filtersOpen}
+ aria-controls={filtersId}
+ onClick={() => setFiltersOpen((open) => !open)}
+ >
+ <span className="flex items-center gap-2">
+ <Filter />
+ Filters
+ {activeFilterCount > 0 && (
+ <span className="tabular-nums opacity-60">
+ ({activeFilterCount})
+ </span>
+ )}
+ </span>
+ <ChevronDown
+ className={cn(
+ "shrink-0 opacity-60 transition-transform",
+ filtersOpen && "rotate-180",
+ )}
+ />
+ </Button>
+ )}
+ <div
+ id={filtersId}
+ className={cn(
+ "flex-col gap-2 lg:flex-row lg:flex-wrap lg:items-center lg:justify-between",
+ filtersOpen ? "flex" : "hidden sm:flex",
+ )}
+ >
+ {tabs && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="w-full justify-between sm:w-auto sm:min-w-44"
+ >
+ <span className="truncate">{activeTabLabel}</span>
+ <ChevronDown className="shrink-0 opacity-60" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-52">
+ <DropdownMenuRadioGroup
+ value={query.tab}
+ onValueChange={(value) => query.setTab(value)}
+ >
+ <DropdownMenuRadioItem value="all">
+ <span className="flex-1">{tabs.allLabel ?? "All"}</span>
+ </DropdownMenuRadioItem>
+ {tabs.options.map((option) => {
+ // A tab that can never match anything is noise, but only
+ // once we actually know the count.
+ if (tabCounts?.[option.value] === 0) return null;
+ return (
+ <DropdownMenuRadioItem
+ key={option.value}
+ value={option.value}
+ >
+ <span className="flex-1">{option.label}</span>
+ </DropdownMenuRadioItem>
+ );
+ })}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+
+ {leadingActions}
+
+ <div className="grid grid-cols-1 gap-2 sm:flex sm:flex-wrap sm:items-center lg:ml-auto">
+ {facets?.map((facet) => {
+ const selected = query.filters[facet.id] ?? "all";
+ const active = facet.options.find((o) => o.value === selected);
+ return (
+ <DropdownMenu key={facet.id}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="justify-between"
+ >
+ <span className="truncate">
+ {active ? active.label : facet.label}
+ </span>
+ <ChevronDown
+ data-icon="inline-end"
+ className="opacity-60"
+ />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-44">
+ <DropdownMenuRadioGroup
+ value={selected}
+ onValueChange={(value) => query.setFilter(facet.id, value)}
+ >
+ <DropdownMenuRadioItem value="all">
+ {facet.label}
+ </DropdownMenuRadioItem>
+ {facet.options.map((option) => (
+ <DropdownMenuRadioItem
+ key={option.value}
+ value={option.value}
+ >
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ })}
+ {(sortableColumns.length > 0 || anyExpandable) && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="justify-start sm:justify-center"
+ >
+ <ArrowsVertical data-icon="inline-start" />
+ Sort
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-48">
+ <DropdownMenuLabel>Sort by</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={query.sort}
+ onValueChange={query.setSort}
+ >
+ {anyExpandable && (
+ <DropdownMenuRadioItem value="detail">
+ Detail
+ </DropdownMenuRadioItem>
+ )}
+ {sortableColumns.map((column) => (
+ <DropdownMenuRadioItem key={column.id} value={column.id}>
+ {columnLabel(column)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioGroup
+ value={query.dir}
+ onValueChange={(value) =>
+ query.setDir(value === "desc" ? "desc" : "asc")
+ }
+ >
+ <DropdownMenuRadioItem value="asc">
+ Ascending
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="desc">
+ Descending
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {hideable.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="justify-start sm:justify-center"
+ >
+ <Column data-icon="inline-start" />
+ Columns
+ <span className="tabular-nums opacity-60">
+ ({visibleColumns.length})
+ </span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-48">
+ <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>
+ {hideable.map((column) => (
+ <DropdownMenuCheckboxItem
+ key={column.id}
+ checked={!hidden.includes(column.id)}
+ onCheckedChange={(checked) =>
+ setHidden((prev) => {
+ const set = new Set(prev);
+ if (checked) set.delete(column.id);
+ else set.add(column.id);
+ return [...set];
+ })
+ }
+ >
+ {columnLabel(column)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {actions}
+ </div>
+ </div>
+
+ <InputGroup>
+ <InputGroupAddon>
+ <Search />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder={searchPlaceholder}
+ value={query.q}
+ onChange={(event) => query.setSearch(event.target.value)}
+ autoComplete="off"
+ />
+ </InputGroup>
+ </div>
+
+ <Table
+ // Fixed layout so columns honour their widths and long cell text
+ // truncates (cells are overflow-hidden) instead of blowing the table
+ // out horizontally.
+ className={cn(
+ "table-fixed [&_td:first-child]:pl-0 [&_th:first-child]:pl-0",
+ tableClassName,
+ )}
+ containerClassName="min-h-0 flex-1 overflow-auto"
+ >
+ <TableHeader className="sticky top-0 z-10 bg-background [&_th]:bg-background">
+ <TableRow>
+ {anyExpandable && (
+ <TableHead className="h-11 w-10 px-3">
+ <span className="sr-only">Detail</span>
+ </TableHead>
+ )}
+ {visibleColumns.map((column) => {
+ const isActive = query.sort === column.id;
+ return (
+ <TableHead
+ key={column.id}
+ className={cn(
+ // overflow-hidden mirrors the body cells so a squeezed
+ // header truncates instead of spilling into the next column.
+ "h-11 overflow-hidden px-3 font-normal text-muted-foreground",
+ column.width,
+ ALIGN_CLASS[column.align ?? "left"],
+ column.hideBelow && HIDE_BELOW_CLASS[column.hideBelow],
+ column.headClassName,
+ )}
+ aria-sort={
+ isActive
+ ? query.dir === "asc"
+ ? "ascending"
+ : "descending"
+ : undefined
+ }
+ >
+ {column.sortable ? (
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => query.toggleSort(column.id)}
+ className={cn(
+ "-ml-2 font-normal text-muted-foreground hover:text-foreground",
+ column.align === "right" && "-mr-2 ml-0 flex-row-reverse",
+ column.align === "center" && "mx-auto",
+ )}
+ >
+ {column.header}
+ <SortIndicator active={isActive} dir={query.dir} />
+ </Button>
+ ) : (
+ column.header
+ )}
+ </TableHead>
+ );
+ })}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {deferredRows.length === 0 ? (
+ <TableRow className="hover:bg-transparent">
+ <TableCell
+ colSpan={colCount}
+ className="h-32 whitespace-normal py-8 text-center align-middle text-muted-foreground"
+ >
+ {loading ? <Spinner /> : (empty ?? "No results found.")}
+ </TableCell>
+ </TableRow>
+ ) : (
+ deferredRows.map((row) => {
+ const id = getRowId(row);
+ const canExpand = expandable?.isExpandable(row) ?? false;
+ const isOpen = canExpand && expanded.has(id);
+ const clickable = canExpand || !!onRowClick;
+ const handleClick = () => {
+ if (canExpand) {
+ setExpandedIds((prev) => {
+ const set = new Set(prev ?? []);
+ if (set.has(id)) set.delete(id);
+ else set.add(id);
+ const next = [...set];
+ // Empty array would still write `?expand=`; null clears it.
+ return next.length > 0 ? next : null;
+ });
+ } else {
+ onRowClick?.(row);
+ }
+ };
+ return (
+ <Fragment key={id}>
+ <TableRow
+ onClick={clickable ? handleClick : undefined}
+ className={
+ clickable
+ ? anyExpandable
+ ? ROW_ACCENT_EXPANDABLE
+ : ROW_ACCENT
+ : undefined
+ }
+ >
+ {anyExpandable && (
+ <TableCell className="w-10 px-3 py-3 text-center text-muted-foreground">
+ {canExpand && (
+ <ChevronRight
+ size={12}
+ className={cn(
+ "inline-block transition-transform",
+ isOpen && "rotate-90",
+ )}
+ />
+ )}
+ </TableCell>
+ )}
+ {visibleColumns.map((column) => (
+ <TableCell
+ key={column.id}
+ className={cn(
+ "overflow-hidden px-3 py-3",
+ column.width,
+ ALIGN_CLASS[column.align ?? "left"],
+ column.hideBelow && HIDE_BELOW_CLASS[column.hideBelow],
+ column.cellClassName,
+ )}
+ >
+ {column.cell(row)}
+ </TableCell>
+ ))}
+ </TableRow>
+ {isOpen &&
+ expandable?.getSubRows(row).map((sub) => {
+ const subClickable = !!expandable.onSubRowClick;
+ return (
+ <TableRow
+ key={expandable.getSubRowId(sub, row)}
+ onClick={
+ subClickable
+ ? () => expandable.onSubRowClick?.(sub, row)
+ : undefined
+ }
+ className={cn(
+ "bg-muted/30",
+ subClickable &&
+ (anyExpandable
+ ? ROW_ACCENT_EXPANDABLE
+ : ROW_ACCENT),
+ )}
+ >
+ {anyExpandable && (
+ <TableCell className="w-10 px-3 py-2.5" />
+ )}
+ {visibleColumns.map((column) => (
+ <TableCell
+ key={column.id}
+ className={cn(
+ "overflow-hidden px-3 py-2.5 align-top",
+ column.width,
+ ALIGN_CLASS[column.align ?? "left"],
+ column.hideBelow &&
+ HIDE_BELOW_CLASS[column.hideBelow],
+ column.cellClassName,
+ )}
+ >
+ {expandable.renderSubCell(sub, column.id, row)}
+ </TableCell>
+ ))}
+ </TableRow>
+ );
+ })}
+ </Fragment>
+ );
+ })
+ )}
+ </TableBody>
+ </Table>
+
+ <TablePagination
+ page={query.page}
+ totalPages={totalPages}
+ pageSize={pageSize}
+ total={total}
+ onPageChange={(page) => query.setPage(page)}
+ loading={loading}
+ meta={meta}
+ />
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/dialog.tsx b/packages/ui/src/components/dialog.tsx
new file mode 100644
index 00000000..1ac8856a
--- /dev/null
+++ b/packages/ui/src/components/dialog.tsx
@@ -0,0 +1,163 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import { XIcon } from "lucide-react";
+import { Dialog as DialogPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Dialog({
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Root>) {
+ return <DialogPrimitive.Root data-slot="dialog" {...props} />;
+}
+
+function DialogTrigger({
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
+}
+
+function DialogPortal({
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
+ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
+}
+
+function DialogClose({
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Close>) {
+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
+}
+
+function DialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
+ return (
+ <DialogPrimitive.Overlay
+ data-slot="dialog-overlay"
+ className={cn(
+ "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function DialogContent({
+ className,
+ children,
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Content> & {
+ showCloseButton?: boolean;
+}) {
+ return (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ data-slot="dialog-content"
+ className={cn(
+ "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-none bg-popover p-4 text-xs/relaxed text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <DialogPrimitive.Close data-slot="dialog-close" asChild>
+ <Button
+ variant="ghost"
+ className="absolute top-2 right-2"
+ size="icon-sm"
+ >
+ <XIcon />
+ <span className="sr-only">Close</span>
+ </Button>
+ </DialogPrimitive.Close>
+ )}
+ </DialogPrimitive.Content>
+ </DialogPortal>
+ );
+}
+
+function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="dialog-header"
+ className={cn("flex flex-col gap-1 text-left", className)}
+ {...props}
+ />
+ );
+}
+
+function DialogFooter({
+ className,
+ showCloseButton = false,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & {
+ showCloseButton?: boolean;
+}) {
+ return (
+ <div
+ data-slot="dialog-footer"
+ className={cn(
+ "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <DialogPrimitive.Close asChild>
+ <Button variant="outline">Close</Button>
+ </DialogPrimitive.Close>
+ )}
+ </div>
+ );
+}
+
+function DialogTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Title>) {
+ return (
+ <DialogPrimitive.Title
+ data-slot="dialog-title"
+ className={cn("font-heading text-sm font-medium", className)}
+ {...props}
+ />
+ );
+}
+
+function DialogDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Description>) {
+ return (
+ <DialogPrimitive.Description
+ data-slot="dialog-description"
+ className={cn(
+ "text-xs/relaxed text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+};
diff --git a/packages/ui/src/components/direction.tsx b/packages/ui/src/components/direction.tsx
new file mode 100644
index 00000000..eb9795f0
--- /dev/null
+++ b/packages/ui/src/components/direction.tsx
@@ -0,0 +1,22 @@
+"use client";
+
+import { Direction } from "radix-ui";
+import type * as React from "react";
+
+function DirectionProvider({
+ dir,
+ direction,
+ children,
+}: React.ComponentProps<typeof Direction.DirectionProvider> & {
+ direction?: React.ComponentProps<typeof Direction.DirectionProvider>["dir"];
+}) {
+ return (
+ <Direction.DirectionProvider dir={direction ?? dir}>
+ {children}
+ </Direction.DirectionProvider>
+ );
+}
+
+const useDirection = Direction.useDirection;
+
+export { DirectionProvider, useDirection };
diff --git a/packages/ui/src/components/drawer.tsx b/packages/ui/src/components/drawer.tsx
new file mode 100644
index 00000000..f25e9c16
--- /dev/null
+++ b/packages/ui/src/components/drawer.tsx
@@ -0,0 +1,147 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import type * as React from "react";
+import { Drawer as DrawerPrimitive } from "vaul";
+
+// Mirrors `sheetTitleVariants` — a drawer is the small-screen form of a sheet,
+// so a record title has to read the same weight in both.
+const drawerTitleVariants = cva("font-heading font-medium text-foreground", {
+ variants: {
+ size: {
+ default: "text-sm",
+ lg: "text-lg leading-tight tracking-tight",
+ },
+ },
+ defaultVariants: {
+ size: "default",
+ },
+});
+
+function Drawer({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
+ return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
+}
+
+function DrawerTrigger({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
+ return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
+}
+
+function DrawerPortal({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
+ return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
+}
+
+function DrawerClose({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
+ return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
+}
+
+function DrawerOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
+ return (
+ <DrawerPrimitive.Overlay
+ data-slot="drawer-overlay"
+ className={cn(
+ "fixed inset-0 z-50 bg-black/10 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function DrawerContent({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
+ return (
+ <DrawerPortal data-slot="drawer-portal">
+ <DrawerOverlay />
+ <DrawerPrimitive.Content
+ data-slot="drawer-content"
+ className={cn(
+ "group/drawer-content fixed z-50 flex h-auto flex-col bg-popover text-xs/relaxed text-popover-foreground data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-none data-[vaul-drawer-direction=bottom]:border-t data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:rounded-none data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:rounded-none data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-none data-[vaul-drawer-direction=top]:border-b data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm",
+ className,
+ )}
+ {...props}
+ >
+ <div className="mx-auto mt-4 hidden h-1 w-[100px] shrink-0 rounded-none bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
+ {children}
+ </DrawerPrimitive.Content>
+ </DrawerPortal>
+ );
+}
+
+function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="drawer-header"
+ className={cn(
+ "flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-0.5 md:text-left",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="drawer-footer"
+ className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ {...props}
+ />
+ );
+}
+
+function DrawerTitle({
+ className,
+ size,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Title> &
+ VariantProps<typeof drawerTitleVariants>) {
+ return (
+ <DrawerPrimitive.Title
+ data-slot="drawer-title"
+ className={cn(drawerTitleVariants({ size }), className)}
+ {...props}
+ />
+ );
+}
+
+function DrawerDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
+ return (
+ <DrawerPrimitive.Description
+ data-slot="drawer-description"
+ className={cn("text-xs/relaxed text-muted-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Drawer,
+ DrawerClose,
+ DrawerContent,
+ DrawerDescription,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ DrawerPortal,
+ DrawerTitle,
+ DrawerTrigger,
+};
diff --git a/packages/ui/src/components/dropdown-menu.tsx b/packages/ui/src/components/dropdown-menu.tsx
new file mode 100644
index 00000000..ddb3bcaf
--- /dev/null
+++ b/packages/ui/src/components/dropdown-menu.tsx
@@ -0,0 +1,272 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { CheckIcon, ChevronRightIcon } from "lucide-react";
+import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function DropdownMenu({
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
+ return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
+}
+
+function DropdownMenuPortal({
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
+ return (
+ <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
+ );
+}
+
+function DropdownMenuTrigger({
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
+ return (
+ <DropdownMenuPrimitive.Trigger
+ data-slot="dropdown-menu-trigger"
+ {...props}
+ />
+ );
+}
+
+function DropdownMenuContent({
+ className,
+ align = "start",
+ sideOffset = 4,
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
+ return (
+ <DropdownMenuPrimitive.Portal>
+ <DropdownMenuPrimitive.Content
+ data-slot="dropdown-menu-content"
+ sideOffset={sideOffset}
+ align={align}
+ className={cn(
+ "z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-none bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ </DropdownMenuPrimitive.Portal>
+ );
+}
+
+function DropdownMenuGroup({
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
+ return (
+ <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
+ );
+}
+
+function DropdownMenuItem({
+ className,
+ inset,
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
+ inset?: boolean;
+ variant?: "default" | "destructive";
+}) {
+ return (
+ <DropdownMenuPrimitive.Item
+ data-slot="dropdown-menu-item"
+ data-inset={inset}
+ data-variant={variant}
+ className={cn(
+ "group/dropdown-menu-item relative flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function DropdownMenuCheckboxItem({
+ className,
+ children,
+ checked,
+ inset,
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem> & {
+ inset?: boolean;
+}) {
+ return (
+ <DropdownMenuPrimitive.CheckboxItem
+ data-slot="dropdown-menu-checkbox-item"
+ data-inset={inset}
+ className={cn(
+ "relative flex cursor-default items-center gap-2 rounded-none py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span
+ className="pointer-events-none absolute right-2 flex items-center justify-center"
+ data-slot="dropdown-menu-checkbox-item-indicator"
+ >
+ <DropdownMenuPrimitive.ItemIndicator>
+ <CheckIcon />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.CheckboxItem>
+ );
+}
+
+function DropdownMenuRadioGroup({
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
+ return (
+ <DropdownMenuPrimitive.RadioGroup
+ data-slot="dropdown-menu-radio-group"
+ {...props}
+ />
+ );
+}
+
+function DropdownMenuRadioItem({
+ className,
+ children,
+ inset,
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem> & {
+ inset?: boolean;
+}) {
+ return (
+ <DropdownMenuPrimitive.RadioItem
+ data-slot="dropdown-menu-radio-item"
+ data-inset={inset}
+ className={cn(
+ "relative flex cursor-default items-center gap-2 rounded-none py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ <span
+ className="pointer-events-none absolute right-2 flex items-center justify-center"
+ data-slot="dropdown-menu-radio-item-indicator"
+ >
+ <DropdownMenuPrimitive.ItemIndicator>
+ <CheckIcon />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.RadioItem>
+ );
+}
+
+function DropdownMenuLabel({
+ className,
+ inset,
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
+ inset?: boolean;
+}) {
+ return (
+ <DropdownMenuPrimitive.Label
+ data-slot="dropdown-menu-label"
+ data-inset={inset}
+ className={cn(
+ "px-2 py-2 text-xs text-muted-foreground data-inset:pl-7",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function DropdownMenuSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
+ return (
+ <DropdownMenuPrimitive.Separator
+ data-slot="dropdown-menu-separator"
+ className={cn("-mx-1 h-px bg-border", className)}
+ {...props}
+ />
+ );
+}
+
+function DropdownMenuShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="dropdown-menu-shortcut"
+ className={cn(
+ "ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function DropdownMenuSub({
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
+ return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
+}
+
+function DropdownMenuSubTrigger({
+ className,
+ inset,
+ children,
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
+ inset?: boolean;
+}) {
+ return (
+ <DropdownMenuPrimitive.SubTrigger
+ data-slot="dropdown-menu-sub-trigger"
+ data-inset={inset}
+ className={cn(
+ "flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRightIcon className="ml-auto" />
+ </DropdownMenuPrimitive.SubTrigger>
+ );
+}
+
+function DropdownMenuSubContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
+ return (
+ <DropdownMenuPrimitive.SubContent
+ data-slot="dropdown-menu-sub-content"
+ className={cn(
+ "z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-none bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuPortal,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+};
diff --git a/packages/ui/src/components/empty-cell.tsx b/packages/ui/src/components/empty-cell.tsx
new file mode 100644
index 00000000..bd10aa76
--- /dev/null
+++ b/packages/ui/src/components/empty-cell.tsx
@@ -0,0 +1,9 @@
+import { cn } from "../lib/utils";
+
+/**
+ * The em dash every table uses for "nothing here". Shared so a missing value
+ * looks identical in People, Cloud Security and Code Security.
+ */
+export function EmptyCellValue({ className }: { className?: string }) {
+ return <span className={cn("text-muted-foreground", className)}>—</span>;
+}
diff --git a/packages/ui/src/components/empty.tsx b/packages/ui/src/components/empty.tsx
new file mode 100644
index 00000000..01071291
--- /dev/null
+++ b/packages/ui/src/components/empty.tsx
@@ -0,0 +1,103 @@
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+
+function Empty({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="empty"
+ className={cn(
+ // Sits at its natural height (a comfortable block) rather than
+ // stretching to fill a flex-1 page shell. Opt into full-height
+ // centering per-usage with `flex-1` on the className when needed.
+ "flex w-full min-w-0 flex-col items-center justify-center gap-4 rounded-none border-dashed px-6 py-12 text-center text-balance",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="empty-header"
+ className={cn("flex max-w-sm flex-col items-center gap-2", className)}
+ {...props}
+ />
+ );
+}
+
+const emptyMediaVariants = cva(
+ "mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ icon: "flex size-8 shrink-0 items-center justify-center rounded-none bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+function EmptyMedia({
+ className,
+ variant = "default",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
+ return (
+ <div
+ data-slot="empty-icon"
+ data-variant={variant}
+ className={cn(emptyMediaVariants({ variant, className }))}
+ {...props}
+ />
+ );
+}
+
+function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="empty-title"
+ className={cn("font-heading text-sm font-medium", className)}
+ {...props}
+ />
+ );
+}
+
+function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
+ return (
+ <div
+ data-slot="empty-description"
+ className={cn(
+ "text-xs/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="empty-content"
+ className={cn(
+ "flex w-full max-w-sm min-w-0 flex-col items-center gap-2.5 text-xs text-balance",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+};
diff --git a/packages/ui/src/components/entity-logo.tsx b/packages/ui/src/components/entity-logo.tsx
new file mode 100644
index 00000000..e07028f3
--- /dev/null
+++ b/packages/ui/src/components/entity-logo.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { initialsFromName } from "@crm/ui/lib/format";
+import { cn } from "@crm/ui/lib/utils";
+import { useState } from "react";
+
+export type EntityLogoSize = "xs" | "sm" | "default" | "lg" | "xl";
+
+/**
+ * A square logo tile with an initials fallback.
+ *
+ * Square rather than an `Avatar`: a round crop is right for a face and wrong
+ * for a wordmark, and company logos arrive from Context.dev as squares already.
+ * Keeping it here rather than composing it per module means a company reads the
+ * same in a table row, a sheet header and an embedded list.
+ */
+export function EntityLogo({
+ src,
+ name,
+ size = "default",
+ className,
+}: {
+ src?: string | null;
+ name: string;
+ size?: EntityLogoSize;
+ className?: string;
+}) {
+ // The *url* that failed, not a boolean: enrichment fills `iconUrl` in behind
+ // a poll, so a `true` left over from the placeholder would pin this to
+ // initials forever once the real logo arrived.
+ const [failedSrc, setFailedSrc] = useState<string | null>(null);
+ // Whether the artwork is a square mark or a wide wordmark. Both arrive
+ // through the same field and neither is tagged, so it is measured on load.
+ // The fit is always `contain` — cropping a logo is never the right answer —
+ // but a wordmark letterboxed edge to edge in a bordered tile reads as
+ // broken, so a wide one gets breathing room and a square one does not.
+ const [wide, setWide] = useState(false);
+
+ const url = src?.trim() ? src : null;
+ const showImage = url !== null && failedSrc !== url;
+
+ return (
+ <span
+ data-slot="entity-logo"
+ data-size={size}
+ className={cn(
+ "inline-flex size-8 shrink-0 select-none items-center justify-center overflow-hidden border bg-card text-center font-medium text-muted-foreground text-xs uppercase leading-none",
+ "data-[size=xs]:size-5 data-[size=xs]:text-[9px] data-[size=sm]:size-6 data-[size=sm]:text-[10px] data-[size=lg]:size-10 data-[size=lg]:text-sm data-[size=xl]:size-14 data-[size=xl]:text-lg",
+ !showImage && "bg-muted",
+ className,
+ )}
+ >
+ {showImage ? (
+ <img
+ src={url}
+ alt=""
+ loading="lazy"
+ decoding="async"
+ // Several logo CDNs refuse a request that carries our origin.
+ referrerPolicy="no-referrer"
+ onLoad={(event) => {
+ const { naturalWidth, naturalHeight } = event.currentTarget;
+ if (!naturalHeight) return;
+ setWide(naturalWidth / naturalHeight > 1.2);
+ }}
+ // A dead logo URL is common — brands move them — and the alt text of
+ // a broken image is worse than the initials we would have shown.
+ onError={() => setFailedSrc(url)}
+ className={cn("size-full object-contain", wide && "p-[3px]")}
+ />
+ ) : (
+ initialsFromName(name)
+ )}
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/field.tsx b/packages/ui/src/components/field.tsx
new file mode 100644
index 00000000..970c6c86
--- /dev/null
+++ b/packages/ui/src/components/field.tsx
@@ -0,0 +1,238 @@
+"use client";
+
+import { Label } from "@crm/ui/components/label";
+import { Separator } from "@crm/ui/components/separator";
+
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { useMemo } from "react";
+
+function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
+ return (
+ <fieldset
+ data-slot="field-set"
+ className={cn(
+ "flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldLegend({
+ className,
+ variant = "legend",
+ ...props
+}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
+ return (
+ <legend
+ data-slot="field-legend"
+ data-variant={variant}
+ className={cn(
+ "mb-2.5 font-medium data-[variant=label]:text-xs data-[variant=legend]:text-sm",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="field-group"
+ className={cn(
+ "group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+const fieldVariants = cva(
+ "group/field flex w-full gap-2 data-[invalid=true]:text-destructive",
+ {
+ variants: {
+ orientation: {
+ vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
+ horizontal:
+ "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
+ responsive:
+ "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
+ },
+ },
+ defaultVariants: {
+ orientation: "vertical",
+ },
+ },
+);
+
+function Field({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="field"
+ data-orientation={orientation}
+ className={cn(fieldVariants({ orientation }), className)}
+ {...props}
+ />
+ );
+}
+
+function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="field-content"
+ className={cn(
+ "group/field-content flex flex-1 flex-col gap-0.5 leading-snug",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldLabel({
+ className,
+ ...props
+}: React.ComponentProps<typeof Label>) {
+ return (
+ <Label
+ data-slot="field-label"
+ className={cn(
+ "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-none has-[>[data-slot=field]]:border *:data-[slot=field]:p-2 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
+ "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="field-label"
+ className={cn(
+ "flex w-fit items-center gap-2 text-xs/relaxed group-data-[disabled=true]/field:opacity-50",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
+ return (
+ <p
+ data-slot="field-description"
+ className={cn(
+ "text-left text-xs/relaxed leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
+ "last:mt-0 nth-last-2:-mt-1",
+ "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldSeparator({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div"> & {
+ children?: React.ReactNode;
+}) {
+ return (
+ <div
+ data-slot="field-separator"
+ data-content={!!children}
+ className={cn(
+ "relative -my-2 h-5 text-xs group-data-[variant=outline]/field-group:-mb-2",
+ className,
+ )}
+ {...props}
+ >
+ <Separator className="absolute inset-0 top-1/2" />
+ {children && (
+ <span
+ className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
+ data-slot="field-separator-content"
+ >
+ {children}
+ </span>
+ )}
+ </div>
+ );
+}
+
+function FieldError({
+ className,
+ children,
+ errors,
+ ...props
+}: React.ComponentProps<"div"> & {
+ errors?: Array<{ message?: string } | undefined>;
+}) {
+ const content = useMemo(() => {
+ if (children) {
+ return children;
+ }
+
+ if (!errors?.length) {
+ return null;
+ }
+
+ const uniqueErrors = [
+ ...new Map(errors.map((error) => [error?.message, error])).values(),
+ ];
+
+ if (uniqueErrors?.length === 1) {
+ return uniqueErrors[0]?.message;
+ }
+
+ return (
+ <ul className="ml-4 flex list-disc flex-col gap-1">
+ {uniqueErrors.map(
+ (error, index) =>
+ error?.message && <li key={index}>{error.message}</li>,
+ )}
+ </ul>
+ );
+ }, [children, errors]);
+
+ if (!content) {
+ return null;
+ }
+
+ return (
+ <div
+ role="alert"
+ data-slot="field-error"
+ className={cn("text-xs font-normal text-destructive", className)}
+ {...props}
+ >
+ {content}
+ </div>
+ );
+}
+
+export {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FieldLegend,
+ FieldSeparator,
+ FieldSet,
+ FieldTitle,
+};
diff --git a/packages/ui/src/components/form.tsx b/packages/ui/src/components/form.tsx
new file mode 100644
index 00000000..18f78ea4
--- /dev/null
+++ b/packages/ui/src/components/form.tsx
@@ -0,0 +1,167 @@
+"use client";
+
+import { Label } from "@crm/ui/components/label";
+import { cn } from "@crm/ui/lib/utils";
+import type { Label as LabelPrimitive } from "radix-ui";
+import { Slot } from "radix-ui";
+import * as React from "react";
+import {
+ Controller,
+ type ControllerProps,
+ type FieldPath,
+ type FieldValues,
+ FormProvider,
+ useFormContext,
+ useFormState,
+} from "react-hook-form";
+
+const Form = FormProvider;
+
+type FormFieldContextValue<
+ TFieldValues extends FieldValues = FieldValues,
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
+> = {
+ name: TName;
+};
+
+const FormFieldContext = React.createContext<FormFieldContextValue>(
+ {} as FormFieldContextValue,
+);
+
+const FormField = <
+ TFieldValues extends FieldValues = FieldValues,
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
+>({
+ ...props
+}: ControllerProps<TFieldValues, TName>) => {
+ return (
+ <FormFieldContext.Provider value={{ name: props.name }}>
+ <Controller {...props} />
+ </FormFieldContext.Provider>
+ );
+};
+
+const useFormField = () => {
+ const fieldContext = React.useContext(FormFieldContext);
+ const itemContext = React.useContext(FormItemContext);
+ const { getFieldState } = useFormContext();
+ const formState = useFormState({ name: fieldContext.name });
+ const fieldState = getFieldState(fieldContext.name, formState);
+
+ if (!fieldContext) {
+ throw new Error("useFormField should be used within <FormField>");
+ }
+
+ const { id } = itemContext;
+
+ return {
+ id,
+ name: fieldContext.name,
+ formItemId: `${id}-form-item`,
+ formDescriptionId: `${id}-form-item-description`,
+ formMessageId: `${id}-form-item-message`,
+ ...fieldState,
+ };
+};
+
+type FormItemContextValue = {
+ id: string;
+};
+
+const FormItemContext = React.createContext<FormItemContextValue>(
+ {} as FormItemContextValue,
+);
+
+function FormItem({ className, ...props }: React.ComponentProps<"div">) {
+ const id = React.useId();
+
+ return (
+ <FormItemContext.Provider value={{ id }}>
+ <div
+ data-slot="form-item"
+ className={cn("grid gap-2", className)}
+ {...props}
+ />
+ </FormItemContext.Provider>
+ );
+}
+
+function FormLabel({
+ className,
+ ...props
+}: React.ComponentProps<typeof LabelPrimitive.Root>) {
+ const { error, formItemId } = useFormField();
+
+ return (
+ <Label
+ data-slot="form-label"
+ data-error={!!error}
+ className={cn("data-[error=true]:text-destructive", className)}
+ htmlFor={formItemId}
+ {...props}
+ />
+ );
+}
+
+function FormControl({ ...props }: React.ComponentProps<typeof Slot.Root>) {
+ const { error, formItemId, formDescriptionId, formMessageId } =
+ useFormField();
+
+ return (
+ <Slot.Root
+ data-slot="form-control"
+ id={formItemId}
+ aria-describedby={
+ !error
+ ? `${formDescriptionId}`
+ : `${formDescriptionId} ${formMessageId}`
+ }
+ aria-invalid={!!error}
+ {...props}
+ />
+ );
+}
+
+function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
+ const { formDescriptionId } = useFormField();
+
+ return (
+ <p
+ data-slot="form-description"
+ id={formDescriptionId}
+ className={cn("text-xs/relaxed text-muted-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
+ const { error, formMessageId } = useFormField();
+ const body = error ? String(error?.message ?? "") : props.children;
+
+ if (!body) {
+ return null;
+ }
+
+ return (
+ <p
+ data-slot="form-message"
+ id={formMessageId}
+ className={cn("text-sm text-destructive", className)}
+ {...props}
+ >
+ {body}
+ </p>
+ );
+}
+
+export {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+ useFormField,
+};
diff --git a/packages/ui/src/components/hover-card.tsx b/packages/ui/src/components/hover-card.tsx
new file mode 100644
index 00000000..3363159e
--- /dev/null
+++ b/packages/ui/src/components/hover-card.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { HoverCard as HoverCardPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function HoverCard({
+ ...props
+}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
+ return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />;
+}
+
+function HoverCardTrigger({
+ ...props
+}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
+ return (
+ <HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
+ );
+}
+
+function HoverCardContent({
+ className,
+ align = "center",
+ sideOffset = 4,
+ ...props
+}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
+ return (
+ <HoverCardPrimitive.Portal data-slot="hover-card-portal">
+ <HoverCardPrimitive.Content
+ data-slot="hover-card-content"
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-none bg-popover p-2.5 text-xs/relaxed text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ </HoverCardPrimitive.Portal>
+ );
+}
+
+export { HoverCard, HoverCardContent, HoverCardTrigger };
diff --git a/packages/ui/src/components/icon.tsx b/packages/ui/src/components/icon.tsx
new file mode 100644
index 00000000..0c51b92f
--- /dev/null
+++ b/packages/ui/src/components/icon.tsx
@@ -0,0 +1,96 @@
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+export const ICON_MOTIONS = [
+ "pop",
+ "scale",
+ "lift",
+ "turn",
+ "rotate",
+ "flip",
+ "spin",
+ "wiggle",
+ "swing",
+ "bounce",
+ "pulse",
+ "nudge-right",
+ "nudge-left",
+ "nudge-up",
+ "nudge-down",
+ "launch",
+ "none",
+] as const;
+
+export type IconMotion = (typeof ICON_MOTIONS)[number];
+
+export type CarbonIconProps = React.SVGProps<SVGSVGElement> & {
+ size?: number | string;
+};
+
+export type CarbonIcon = React.ComponentType<CarbonIconProps> & {
+ displayName?: string;
+ render?: { displayName?: string; name?: string };
+};
+
+const MOTION_BY_ICON: Record<string, IconMotion> = {
+ ArrowRight: "nudge-right",
+ ChevronRight: "nudge-right",
+ Play: "nudge-right",
+ SendAlt: "nudge-right",
+ Logout: "nudge-right",
+ ArrowLeft: "nudge-left",
+ ChevronLeft: "nudge-left",
+ ArrowUp: "nudge-up",
+ ArrowDown: "nudge-down",
+ ChevronDown: "nudge-down",
+ Download: "bounce",
+ Launch: "launch",
+ Settings: "spin",
+ Renew: "spin",
+ Restart: "spin",
+ RecentlyViewed: "spin",
+ Earth: "spin",
+ Add: "turn",
+ Close: "turn",
+ TrashCan: "wiggle",
+ Tools: "wiggle",
+ Locked: "wiggle",
+ Password: "wiggle",
+ MagicWand: "wiggle",
+ Search: "wiggle",
+ WarningAlt: "wiggle",
+ Misuse: "pulse",
+ Information: "pulse",
+ Security: "pulse",
+ Light: "pulse",
+ Ai: "pulse",
+ Chip: "pulse",
+ Asleep: "swing",
+};
+
+function iconName(icon: CarbonIcon): string | undefined {
+ return icon.displayName ?? icon.render?.displayName ?? icon.render?.name;
+}
+
+export function iconMotionFor(icon: CarbonIcon): IconMotion {
+ const name = iconName(icon);
+ return (name && MOTION_BY_ICON[name]) || "pop";
+}
+
+export type IconProps = CarbonIconProps & {
+ icon: CarbonIcon;
+ motion?: IconMotion;
+};
+
+export function Icon({ icon: Glyph, motion, className, ...props }: IconProps) {
+ const resolved = motion ?? iconMotionFor(Glyph);
+ return (
+ <Glyph
+ aria-hidden
+ focusable={false}
+ {...props}
+ data-motion={resolved}
+ className={cn("cds-icon", className)}
+ />
+ );
+}
diff --git a/packages/ui/src/components/input-group.tsx b/packages/ui/src/components/input-group.tsx
new file mode 100644
index 00000000..2c5220df
--- /dev/null
+++ b/packages/ui/src/components/input-group.tsx
@@ -0,0 +1,154 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { Input } from "@crm/ui/components/input";
+import { Textarea } from "@crm/ui/components/textarea";
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import type * as React from "react";
+
+function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="input-group"
+ role="group"
+ className={cn(
+ "group/input-group relative flex h-8 w-full min-w-0 items-center rounded-none border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-1 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-1 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+const inputGroupAddonVariants = cva(
+ "flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-xs font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-none [&>svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ align: {
+ "inline-start":
+ "order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",
+ "inline-end":
+ "order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",
+ "block-start":
+ "order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",
+ "block-end":
+ "order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",
+ },
+ },
+ defaultVariants: {
+ align: "inline-start",
+ },
+ },
+);
+
+function InputGroupAddon({
+ className,
+ align = "inline-start",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="input-group-addon"
+ data-align={align}
+ className={cn(inputGroupAddonVariants({ align }), className)}
+ onClick={(e) => {
+ if ((e.target as HTMLElement).closest("button")) {
+ return;
+ }
+ e.currentTarget.parentElement?.querySelector("input")?.focus();
+ }}
+ {...props}
+ />
+ );
+}
+
+const inputGroupButtonVariants = cva(
+ "flex items-center gap-2 text-xs shadow-none",
+ {
+ variants: {
+ size: {
+ xs: "h-6 gap-1 rounded-none px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
+ sm: "gap-1",
+ "icon-xs": "size-6 rounded-none p-0 has-[>svg]:p-0",
+ "icon-sm": "size-7 p-0 has-[>svg]:p-0",
+ },
+ },
+ defaultVariants: {
+ size: "xs",
+ },
+ },
+);
+
+function InputGroupButton({
+ className,
+ type = "button",
+ variant = "ghost",
+ size = "xs",
+ ...props
+}: Omit<React.ComponentProps<typeof Button>, "size"> &
+ VariantProps<typeof inputGroupButtonVariants>) {
+ return (
+ <Button
+ type={type}
+ data-size={size}
+ variant={variant}
+ className={cn(inputGroupButtonVariants({ size }), className)}
+ {...props}
+ />
+ );
+}
+
+function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ className={cn(
+ "flex items-center gap-2 text-xs text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function InputGroupInput({
+ className,
+ ...props
+}: React.ComponentProps<"input">) {
+ return (
+ <Input
+ data-slot="input-group-control"
+ className={cn(
+ "flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function InputGroupTextarea({
+ className,
+ ...props
+}: React.ComponentProps<"textarea">) {
+ return (
+ <Textarea
+ data-slot="input-group-control"
+ className={cn(
+ "flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupInput,
+ InputGroupText,
+ InputGroupTextarea,
+};
diff --git a/packages/ui/src/components/input-otp.tsx b/packages/ui/src/components/input-otp.tsx
new file mode 100644
index 00000000..8c109d8a
--- /dev/null
+++ b/packages/ui/src/components/input-otp.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { OTPInput, OTPInputContext } from "input-otp";
+import { MinusIcon } from "lucide-react";
+import * as React from "react";
+
+function InputOTP({
+ className,
+ containerClassName,
+ ...props
+}: React.ComponentProps<typeof OTPInput> & {
+ containerClassName?: string;
+}) {
+ return (
+ <OTPInput
+ data-slot="input-otp"
+ containerClassName={cn(
+ "cn-input-otp flex items-center has-disabled:opacity-50",
+ containerClassName,
+ )}
+ spellCheck={false}
+ className={cn("disabled:cursor-not-allowed", className)}
+ {...props}
+ />
+ );
+}
+
+function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="input-otp-group"
+ className={cn(
+ "flex items-center rounded-none has-aria-invalid:border-destructive has-aria-invalid:ring-1 has-aria-invalid:ring-destructive/20 dark:has-aria-invalid:ring-destructive/40",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function InputOTPSlot({
+ index,
+ className,
+ ...props
+}: React.ComponentProps<"div"> & {
+ index: number;
+}) {
+ const inputOTPContext = React.useContext(OTPInputContext);
+ const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {};
+
+ return (
+ <div
+ data-slot="input-otp-slot"
+ data-active={isActive}
+ className={cn(
+ "relative flex size-8 items-center justify-center border-y border-r border-input text-xs transition-all outline-none first:rounded-none first:border-l last:rounded-none aria-invalid:border-destructive data-[active=true]:z-10 data-[active=true]:border-ring data-[active=true]:ring-1 data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40",
+ className,
+ )}
+ {...props}
+ >
+ {char}
+ {hasFakeCaret && (
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
+ <div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
+ </div>
+ )}
+ </div>
+ );
+}
+
+function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="input-otp-separator"
+ className="flex items-center [&_svg:not([class*='size-'])]:size-4"
+ role="separator"
+ {...props}
+ >
+ <MinusIcon />
+ </div>
+ );
+}
+
+export { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot };
diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsx
new file mode 100644
index 00000000..834ddff9
--- /dev/null
+++ b/packages/ui/src/components/input.tsx
@@ -0,0 +1,18 @@
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+function Input({ className, type, ...props }: React.ComponentProps<"input">) {
+ return (
+ <input
+ type={type}
+ data-slot="input"
+ className={cn(
+ "h-8 w-full min-w-0 rounded-none border border-input bg-transparent px-2.5 py-1 text-xs transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-xs file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 md:text-xs dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Input };
diff --git a/packages/ui/src/components/item.tsx b/packages/ui/src/components/item.tsx
new file mode 100644
index 00000000..a96b7f0b
--- /dev/null
+++ b/packages/ui/src/components/item.tsx
@@ -0,0 +1,195 @@
+import { Separator } from "@crm/ui/components/separator";
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { Slot } from "radix-ui";
+import type * as React from "react";
+
+function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ role="list"
+ data-slot="item-group"
+ className={cn(
+ "group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return (
+ <Separator
+ data-slot="item-separator"
+ orientation="horizontal"
+ className={cn("my-2", className)}
+ {...props}
+ />
+ );
+}
+
+const itemVariants = cva(
+ "group/item flex w-full flex-wrap items-center rounded-none border text-xs transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [a]:transition-colors [a]:hover:bg-muted",
+ {
+ variants: {
+ variant: {
+ default: "border-transparent",
+ outline: "border-border",
+ muted: "border-transparent bg-muted/50",
+ },
+ size: {
+ default: "gap-2.5 px-3 py-2.5",
+ sm: "gap-2.5 px-3 py-2.5",
+ xs: "gap-2 px-2.5 py-2 in-data-[slot=dropdown-menu-content]:p-0",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+function Item({
+ className,
+ variant = "default",
+ size = "default",
+ asChild = false,
+ ...props
+}: React.ComponentProps<"div"> &
+ VariantProps<typeof itemVariants> & { asChild?: boolean }) {
+ const Comp = asChild ? Slot.Root : "div";
+ return (
+ <Comp
+ data-slot="item"
+ data-variant={variant}
+ data-size={size}
+ className={cn(itemVariants({ variant, size, className }))}
+ {...props}
+ />
+ );
+}
+
+const itemMediaVariants = cva(
+ "flex shrink-0 items-center justify-center gap-2 group-has-data-[slot=item-description]/item:translate-y-0.5 group-has-data-[slot=item-description]/item:self-start [&_svg]:pointer-events-none",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ icon: "[&_svg:not([class*='size-'])]:size-4",
+ image:
+ "size-10 overflow-hidden rounded-none group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+function ItemMedia({
+ className,
+ variant = "default",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
+ return (
+ <div
+ data-slot="item-media"
+ data-variant={variant}
+ className={cn(itemMediaVariants({ variant, className }))}
+ {...props}
+ />
+ );
+}
+
+function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-content"
+ className={cn(
+ "flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0 [&+[data-slot=item-content]]:flex-none",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-title"
+ className={cn(
+ "line-clamp-1 flex w-fit items-center gap-2 text-xs font-medium underline-offset-4",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
+ return (
+ <p
+ data-slot="item-description"
+ className={cn(
+ "line-clamp-2 text-left text-xs/relaxed font-normal text-muted-foreground group-data-[size=xs]/item:text-xs/relaxed [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-actions"
+ className={cn("flex items-center gap-2", className)}
+ {...props}
+ />
+ );
+}
+
+function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-header"
+ className={cn(
+ "flex basis-full items-center justify-between gap-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-footer"
+ className={cn(
+ "flex basis-full items-center justify-between gap-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemFooter,
+ ItemGroup,
+ ItemHeader,
+ ItemMedia,
+ ItemSeparator,
+ ItemTitle,
+};
diff --git a/packages/ui/src/components/kbd.tsx b/packages/ui/src/components/kbd.tsx
new file mode 100644
index 00000000..f0c8b64d
--- /dev/null
+++ b/packages/ui/src/components/kbd.tsx
@@ -0,0 +1,26 @@
+import { cn } from "@crm/ui/lib/utils";
+
+function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
+ return (
+ <kbd
+ data-slot="kbd"
+ className={cn(
+ "pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-none bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=tooltip-content]:text-background dark:in-data-[slot=tooltip-content]:bg-background/10 [&_svg:not([class*='size-'])]:size-3",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <kbd
+ data-slot="kbd-group"
+ className={cn("inline-flex items-center gap-1", className)}
+ {...props}
+ />
+ );
+}
+
+export { Kbd, KbdGroup };
diff --git a/packages/ui/src/components/label.tsx b/packages/ui/src/components/label.tsx
new file mode 100644
index 00000000..1a0b0652
--- /dev/null
+++ b/packages/ui/src/components/label.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { Label as LabelPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Label({
+ className,
+ ...props
+}: React.ComponentProps<typeof LabelPrimitive.Root>) {
+ return (
+ <LabelPrimitive.Root
+ data-slot="label"
+ className={cn(
+ "flex items-center gap-2 text-xs leading-none select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Label };
diff --git a/packages/ui/src/components/logo.tsx b/packages/ui/src/components/logo.tsx
new file mode 100644
index 00000000..99c1726c
--- /dev/null
+++ b/packages/ui/src/components/logo.tsx
@@ -0,0 +1,19 @@
+import type * as React from "react";
+
+const Logo = (props: React.SVGProps<SVGSVGElement>) => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width={512}
+ height={512}
+ viewBox="0 0 512 512"
+ fill="none"
+ {...props}
+ aria-label="Comp AI Logo"
+ >
+ <path
+ d="m384 99.548 -16.066 -12.508L256.021 0 0 199.096v113.782L256.021 512 512 312.879V199.096zm-127.98 -49.419 79.695 61.975 -40.944 31.803 -3.661 2.837 -35.091 -27.287 -102.399 79.638 35.09 27.287 32.218 25.088 35.09 27.288L358.4 199.074l-35.047 -27.288 3.659 -2.837 40.943 -31.803 79.651 61.952 -40.943 31.852 -150.62 117.163 -79.695 -61.974 -32.218 -25.041 -38.752 -30.125 -40.922 -31.849z"
+ fill="currentColor"
+ />
+ </svg>
+);
+export default Logo;
diff --git a/packages/ui/src/components/marker.tsx b/packages/ui/src/components/marker.tsx
new file mode 100644
index 00000000..e0315581
--- /dev/null
+++ b/packages/ui/src/components/marker.tsx
@@ -0,0 +1,68 @@
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { Slot } from "radix-ui";
+import type * as React from "react";
+
+const markerVariants = cva(
+ "group/marker relative flex min-h-4 w-full items-center gap-2 text-left text-xs text-muted-foreground [&_svg:not([class*='size-'])]:size-3.5 [a]:underline [a]:underline-offset-3 [a]:hover:text-foreground",
+ {
+ variants: {
+ variant: {
+ default: "",
+ separator:
+ "before:mr-1 before:h-px before:min-w-0 before:flex-1 before:bg-border after:ml-1 after:h-px after:min-w-0 after:flex-1 after:bg-border",
+ border: "border-b border-border pb-2",
+ },
+ },
+ },
+);
+
+function Marker({
+ className,
+ variant = "default",
+ asChild = false,
+ ...props
+}: React.ComponentProps<"div"> &
+ VariantProps<typeof markerVariants> & {
+ asChild?: boolean;
+ }) {
+ const Comp = asChild ? Slot.Root : "div";
+
+ return (
+ <Comp
+ data-slot="marker"
+ data-variant={variant}
+ className={cn(markerVariants({ variant, className }))}
+ {...props}
+ />
+ );
+}
+
+function MarkerIcon({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="marker-icon"
+ aria-hidden="true"
+ className={cn(
+ "size-3.5 shrink-0 [&_svg:not([class*='size-'])]:size-3.5",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MarkerContent({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="marker-content"
+ className={cn(
+ "min-w-0 wrap-break-word group-data-[variant=separator]/marker:flex-none group-data-[variant=separator]/marker:text-center *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Marker, MarkerContent, MarkerIcon, markerVariants };
diff --git a/packages/ui/src/components/menubar.tsx b/packages/ui/src/components/menubar.tsx
new file mode 100644
index 00000000..9f8584ae
--- /dev/null
+++ b/packages/ui/src/components/menubar.tsx
@@ -0,0 +1,280 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { CheckIcon, ChevronRightIcon } from "lucide-react";
+import { Menubar as MenubarPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Menubar({
+ className,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
+ return (
+ <MenubarPrimitive.Root
+ data-slot="menubar"
+ className={cn(
+ "flex h-8 items-center gap-0.5 rounded-none border p-1",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MenubarMenu({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
+ return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />;
+}
+
+function MenubarGroup({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
+ return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />;
+}
+
+function MenubarPortal({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
+ return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />;
+}
+
+function MenubarRadioGroup({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
+ return (
+ <MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
+ );
+}
+
+function MenubarTrigger({
+ className,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
+ return (
+ <MenubarPrimitive.Trigger
+ data-slot="menubar-trigger"
+ className={cn(
+ "flex items-center rounded-none px-1.5 py-[calc(--spacing(0.8))] text-xs font-medium outline-hidden select-none hover:bg-muted aria-expanded:bg-muted",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MenubarContent({
+ className,
+ align = "start",
+ alignOffset = -4,
+ sideOffset = 8,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
+ return (
+ <MenubarPortal>
+ <MenubarPrimitive.Content
+ data-slot="menubar-content"
+ align={align}
+ alignOffset={alignOffset}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 min-w-36 origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-none bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95",
+ className,
+ )}
+ {...props}
+ />
+ </MenubarPortal>
+ );
+}
+
+function MenubarItem({
+ className,
+ inset,
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
+ inset?: boolean;
+ variant?: "default" | "destructive";
+}) {
+ return (
+ <MenubarPrimitive.Item
+ data-slot="menubar-item"
+ data-inset={inset}
+ data-variant={variant}
+ className={cn(
+ "group/menubar-item relative flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive!",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MenubarCheckboxItem({
+ className,
+ children,
+ checked,
+ inset,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem> & {
+ inset?: boolean;
+}) {
+ return (
+ <MenubarPrimitive.CheckboxItem
+ data-slot="menubar-checkbox-item"
+ data-inset={inset}
+ className={cn(
+ "relative flex cursor-default items-center gap-2 rounded-none py-2 pr-28 pl-8 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-8 data-disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0",
+ className,
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="pointer-events-none absolute left-1.5 flex size-4 items-center justify-center [&_svg:not([class*='size-'])]:size-4">
+ <MenubarPrimitive.ItemIndicator>
+ <CheckIcon />
+ </MenubarPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </MenubarPrimitive.CheckboxItem>
+ );
+}
+
+function MenubarRadioItem({
+ className,
+ children,
+ inset,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.RadioItem> & {
+ inset?: boolean;
+}) {
+ return (
+ <MenubarPrimitive.RadioItem
+ data-slot="menubar-radio-item"
+ data-inset={inset}
+ className={cn(
+ "relative flex cursor-default items-center gap-2 rounded-none py-2 pr-2 pl-8 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-8 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ <span className="pointer-events-none absolute left-1.5 flex size-4 items-center justify-center [&_svg:not([class*='size-'])]:size-4">
+ <MenubarPrimitive.ItemIndicator>
+ <CheckIcon />
+ </MenubarPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </MenubarPrimitive.RadioItem>
+ );
+}
+
+function MenubarLabel({
+ className,
+ inset,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
+ inset?: boolean;
+}) {
+ return (
+ <MenubarPrimitive.Label
+ data-slot="menubar-label"
+ data-inset={inset}
+ className={cn("px-2 py-2 text-xs data-inset:pl-8", className)}
+ {...props}
+ />
+ );
+}
+
+function MenubarSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
+ return (
+ <MenubarPrimitive.Separator
+ data-slot="menubar-separator"
+ className={cn("-mx-1 my-1 h-px bg-border", className)}
+ {...props}
+ />
+ );
+}
+
+function MenubarShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="menubar-shortcut"
+ className={cn(
+ "ml-auto text-xs tracking-widest text-muted-foreground group-focus/menubar-item:text-accent-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MenubarSub({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
+ return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />;
+}
+
+function MenubarSubTrigger({
+ className,
+ inset,
+ children,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
+ inset?: boolean;
+}) {
+ return (
+ <MenubarPrimitive.SubTrigger
+ data-slot="menubar-sub-trigger"
+ data-inset={inset}
+ className={cn(
+ "flex cursor-default items-center gap-2 rounded-none px-2 py-2 text-xs outline-none select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-8 data-open:bg-accent data-open:text-accent-foreground [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRightIcon className="ml-auto size-4" />
+ </MenubarPrimitive.SubTrigger>
+ );
+}
+
+function MenubarSubContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
+ return (
+ <MenubarPrimitive.SubContent
+ data-slot="menubar-sub-content"
+ className={cn(
+ "z-50 min-w-32 origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-none bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Menubar,
+ MenubarCheckboxItem,
+ MenubarContent,
+ MenubarGroup,
+ MenubarItem,
+ MenubarLabel,
+ MenubarMenu,
+ MenubarPortal,
+ MenubarRadioGroup,
+ MenubarRadioItem,
+ MenubarSeparator,
+ MenubarShortcut,
+ MenubarSub,
+ MenubarSubContent,
+ MenubarSubTrigger,
+ MenubarTrigger,
+};
diff --git a/packages/ui/src/components/message-scroller.tsx b/packages/ui/src/components/message-scroller.tsx
new file mode 100644
index 00000000..695aa9b5
--- /dev/null
+++ b/packages/ui/src/components/message-scroller.tsx
@@ -0,0 +1,126 @@
+"use client";
+
+import {
+ MessageScroller as MessageScrollerPrimitive,
+ useMessageScroller,
+ useMessageScrollerScrollable,
+ useMessageScrollerVisibility,
+} from "@shadcn/react/message-scroller";
+import { Button } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import { ArrowDown } from "lucide-react";
+import type * as React from "react";
+
+function MessageScrollerProvider(
+ props: React.ComponentProps<typeof MessageScrollerPrimitive.Provider>,
+) {
+ return <MessageScrollerPrimitive.Provider {...props} />;
+}
+
+function MessageScroller({
+ className,
+ ...props
+}: React.ComponentProps<typeof MessageScrollerPrimitive.Root>) {
+ return (
+ <MessageScrollerPrimitive.Root
+ data-slot="message-scroller"
+ className={cn(
+ "group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MessageScrollerViewport({
+ className,
+ ...props
+}: React.ComponentProps<typeof MessageScrollerPrimitive.Viewport>) {
+ return (
+ <MessageScrollerPrimitive.Viewport
+ data-slot="message-scroller-viewport"
+ className={cn(
+ "size-full min-h-0 min-w-0 overflow-y-auto overscroll-contain contain-content",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MessageScrollerContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof MessageScrollerPrimitive.Content>) {
+ return (
+ <MessageScrollerPrimitive.Content
+ data-slot="message-scroller-content"
+ className={cn("flex h-max min-h-full flex-col", className)}
+ {...props}
+ />
+ );
+}
+
+function MessageScrollerItem({
+ className,
+ scrollAnchor = false,
+ ...props
+}: React.ComponentProps<typeof MessageScrollerPrimitive.Item>) {
+ return (
+ <MessageScrollerPrimitive.Item
+ data-slot="message-scroller-item"
+ scrollAnchor={scrollAnchor}
+ className={cn("min-w-0 shrink-0", className)}
+ {...props}
+ />
+ );
+}
+
+function MessageScrollerButton({
+ direction = "end",
+ className,
+ children,
+ render,
+ variant = "secondary",
+ size = "icon-sm",
+ ...props
+}: React.ComponentProps<typeof MessageScrollerPrimitive.Button> &
+ Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
+ return (
+ <MessageScrollerPrimitive.Button
+ data-slot="message-scroller-button"
+ data-direction={direction}
+ data-variant={variant}
+ data-size={size}
+ direction={direction}
+ className={cn(
+ "absolute inset-s-1/2 -translate-x-1/2 border-border bg-background text-foreground shadow-sm transition-[translate,scale,opacity] duration-200 hover:bg-muted hover:text-foreground data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180",
+ className,
+ )}
+ render={render ?? <Button variant={variant} size={size} />}
+ {...props}
+ >
+ {children ?? (
+ <>
+ <ArrowDown />
+ <span className="sr-only">
+ {direction === "end" ? "Scroll to end" : "Scroll to start"}
+ </span>
+ </>
+ )}
+ </MessageScrollerPrimitive.Button>
+ );
+}
+
+export {
+ MessageScroller,
+ MessageScrollerButton,
+ MessageScrollerContent,
+ MessageScrollerItem,
+ MessageScrollerProvider,
+ MessageScrollerViewport,
+ useMessageScroller,
+ useMessageScrollerScrollable,
+ useMessageScrollerVisibility,
+};
diff --git a/packages/ui/src/components/message.tsx b/packages/ui/src/components/message.tsx
new file mode 100644
index 00000000..323091c0
--- /dev/null
+++ b/packages/ui/src/components/message.tsx
@@ -0,0 +1,91 @@
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+function MessageGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="message-group"
+ className={cn("flex min-w-0 flex-col gap-1.5", className)}
+ {...props}
+ />
+ );
+}
+
+function Message({
+ className,
+ align = "start",
+ ...props
+}: React.ComponentProps<"div"> & { align?: "start" | "end" }) {
+ return (
+ <div
+ data-slot="message"
+ data-align={align}
+ className={cn(
+ "group/message relative flex w-full min-w-0 gap-1.5 text-xs data-[align=end]:flex-row-reverse",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MessageAvatar({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="message-avatar"
+ className={cn(
+ "flex w-fit min-w-8 shrink-0 items-center justify-center self-end overflow-hidden rounded-full bg-muted group-has-data-[slot=message-footer]/message:-translate-y-8",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MessageContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="message-content"
+ className={cn(
+ "flex w-full min-w-0 flex-col gap-2 wrap-break-word group-data-[align=end]/message:*:data-slot:self-end",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MessageHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="message-header"
+ className={cn(
+ "flex max-w-full min-w-0 items-center px-2.5 text-xs font-medium text-muted-foreground group-has-data-[variant=ghost]/message:px-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function MessageFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="message-footer"
+ className={cn(
+ "flex max-w-full min-w-0 items-center px-2.5 text-xs font-medium text-muted-foreground group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Message,
+ MessageAvatar,
+ MessageContent,
+ MessageFooter,
+ MessageGroup,
+ MessageHeader,
+};
diff --git a/packages/ui/src/components/native-select.tsx b/packages/ui/src/components/native-select.tsx
new file mode 100644
index 00000000..25060e00
--- /dev/null
+++ b/packages/ui/src/components/native-select.tsx
@@ -0,0 +1,64 @@
+import { cn } from "@crm/ui/lib/utils";
+import { ChevronDownIcon } from "lucide-react";
+import type * as React from "react";
+
+type NativeSelectProps = Omit<React.ComponentProps<"select">, "size"> & {
+ size?: "sm" | "default";
+};
+
+function NativeSelect({
+ className,
+ size = "default",
+ ...props
+}: NativeSelectProps) {
+ return (
+ <div
+ className={cn(
+ "group/native-select relative w-fit has-[select:disabled]:opacity-50",
+ className,
+ )}
+ data-slot="native-select-wrapper"
+ data-size={size}
+ >
+ <select
+ data-slot="native-select"
+ data-size={size}
+ className="h-8 w-full min-w-0 appearance-none rounded-none border border-input bg-transparent py-1 pr-8 pl-2.5 text-xs transition-colors outline-none select-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 data-[size=sm]:h-7 data-[size=sm]:rounded-none data-[size=sm]:py-0.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40"
+ {...props}
+ />
+ <ChevronDownIcon
+ className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground select-none"
+ aria-hidden="true"
+ data-slot="native-select-icon"
+ />
+ </div>
+ );
+}
+
+function NativeSelectOption({
+ className,
+ ...props
+}: React.ComponentProps<"option">) {
+ return (
+ <option
+ data-slot="native-select-option"
+ className={cn("bg-[Canvas] text-[CanvasText]", className)}
+ {...props}
+ />
+ );
+}
+
+function NativeSelectOptGroup({
+ className,
+ ...props
+}: React.ComponentProps<"optgroup">) {
+ return (
+ <optgroup
+ data-slot="native-select-optgroup"
+ className={cn("bg-[Canvas] text-[CanvasText]", className)}
+ {...props}
+ />
+ );
+}
+
+export { NativeSelect, NativeSelectOptGroup, NativeSelectOption };
diff --git a/packages/ui/src/components/navigation-menu.tsx b/packages/ui/src/components/navigation-menu.tsx
new file mode 100644
index 00000000..9eb48ac6
--- /dev/null
+++ b/packages/ui/src/components/navigation-menu.tsx
@@ -0,0 +1,166 @@
+import { cn } from "@crm/ui/lib/utils";
+import { cva } from "class-variance-authority";
+import { ChevronDownIcon } from "lucide-react";
+import { NavigationMenu as NavigationMenuPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function NavigationMenu({
+ className,
+ children,
+ viewport = true,
+ ...props
+}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
+ viewport?: boolean;
+}) {
+ return (
+ <NavigationMenuPrimitive.Root
+ data-slot="navigation-menu"
+ data-viewport={viewport}
+ className={cn(
+ "group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ {viewport && <NavigationMenuViewport />}
+ </NavigationMenuPrimitive.Root>
+ );
+}
+
+function NavigationMenuList({
+ className,
+ ...props
+}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
+ return (
+ <NavigationMenuPrimitive.List
+ data-slot="navigation-menu-list"
+ className={cn(
+ "group flex flex-1 list-none items-center justify-center gap-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function NavigationMenuItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
+ return (
+ <NavigationMenuPrimitive.Item
+ data-slot="navigation-menu-item"
+ className={cn("relative", className)}
+ {...props}
+ />
+ );
+}
+
+const navigationMenuTriggerStyle = cva(
+ "group/navigation-menu-trigger inline-flex h-9 w-max items-center justify-center rounded-none px-2.5 py-1.5 text-xs font-medium transition-all outline-none hover:bg-muted focus:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50 focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-popup-open:bg-muted/50 data-popup-open:hover:bg-muted data-open:bg-muted/50 data-open:hover:bg-muted data-open:focus:bg-muted",
+);
+
+function NavigationMenuTrigger({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
+ return (
+ <NavigationMenuPrimitive.Trigger
+ data-slot="navigation-menu-trigger"
+ className={cn(navigationMenuTriggerStyle(), "group", className)}
+ {...props}
+ >
+ {children}{" "}
+ <ChevronDownIcon
+ className="relative top-px ml-1 size-3 transition duration-300 group-data-popup-open/navigation-menu-trigger:rotate-180 group-data-open/navigation-menu-trigger:rotate-180"
+ aria-hidden="true"
+ />
+ </NavigationMenuPrimitive.Trigger>
+ );
+}
+
+function NavigationMenuContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
+ return (
+ <NavigationMenuPrimitive.Content
+ data-slot="navigation-menu-content"
+ className={cn(
+ "top-0 left-0 w-full p-1 ease-[cubic-bezier(0.22,1,0.36,1)] group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-none group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:ring-1 group-data-[viewport=false]/navigation-menu:ring-foreground/10 group-data-[viewport=false]/navigation-menu:duration-300 data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 data-[motion^=from-]:animate-in data-[motion^=from-]:fade-in data-[motion^=to-]:animate-out data-[motion^=to-]:fade-out **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none md:absolute md:w-auto group-data-[viewport=false]/navigation-menu:data-open:animate-in group-data-[viewport=false]/navigation-menu:data-open:fade-in-0 group-data-[viewport=false]/navigation-menu:data-open:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-closed:animate-out group-data-[viewport=false]/navigation-menu:data-closed:fade-out-0 group-data-[viewport=false]/navigation-menu:data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function NavigationMenuViewport({
+ className,
+ ...props
+}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
+ return (
+ <div
+ className={cn(
+ "absolute top-full left-0 isolate z-50 flex justify-center",
+ )}
+ >
+ <NavigationMenuPrimitive.Viewport
+ data-slot="navigation-menu-viewport"
+ className={cn(
+ "origin-top-center relative mt-1.5 h-(--radix-navigation-menu-viewport-height) w-full overflow-hidden rounded-none bg-popover text-popover-foreground shadow ring-1 ring-foreground/10 duration-100 md:w-(--radix-navigation-menu-viewport-width) data-open:animate-in data-open:zoom-in-90 data-closed:animate-out data-closed:zoom-out-90",
+ className,
+ )}
+ {...props}
+ />
+ </div>
+ );
+}
+
+function NavigationMenuLink({
+ className,
+ ...props
+}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
+ return (
+ <NavigationMenuPrimitive.Link
+ data-slot="navigation-menu-link"
+ className={cn(
+ "flex items-center gap-2 rounded-none p-2 text-xs transition-all outline-none hover:bg-muted focus:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50 focus-visible:outline-1 in-data-[slot=navigation-menu-content]:rounded-none data-active:bg-muted/50 data-active:hover:bg-muted data-active:focus:bg-muted [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function NavigationMenuIndicator({
+ className,
+ ...props
+}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
+ return (
+ <NavigationMenuPrimitive.Indicator
+ data-slot="navigation-menu-indicator"
+ className={cn(
+ "top-full z-1 flex h-1.5 items-end justify-center overflow-hidden data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:animate-in data-[state=visible]:fade-in",
+ className,
+ )}
+ {...props}
+ >
+ <div className="relative top-[60%] h-2 w-2 rotate-45 rounded-none bg-border shadow-md" />
+ </NavigationMenuPrimitive.Indicator>
+ );
+}
+
+export {
+ NavigationMenu,
+ NavigationMenuContent,
+ NavigationMenuIndicator,
+ NavigationMenuItem,
+ NavigationMenuLink,
+ NavigationMenuList,
+ NavigationMenuTrigger,
+ NavigationMenuViewport,
+ navigationMenuTriggerStyle,
+};
diff --git a/packages/ui/src/components/numbered-pagination.tsx b/packages/ui/src/components/numbered-pagination.tsx
new file mode 100644
index 00000000..83774ec3
--- /dev/null
+++ b/packages/ui/src/components/numbered-pagination.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import {
+ Pagination,
+ PaginationContent,
+ PaginationEllipsis,
+ PaginationItem,
+ PaginationLink,
+ PaginationNext,
+ PaginationPrevious,
+} from "@crm/ui/components/pagination";
+
+type PageEntry = number | "start-ellipsis" | "end-ellipsis";
+
+/** First, last, and a window around the current page; ellipses for the rest. */
+function paginationRange(current: number, total: number): PageEntry[] {
+ if (total <= 7) {
+ return Array.from({ length: total }, (_, index) => index + 1);
+ }
+
+ const start = Math.max(2, current - 1);
+ const end = Math.min(total - 1, current + 1);
+ const entries: PageEntry[] = [1];
+
+ if (start > 2) entries.push("start-ellipsis");
+ for (let page = start; page <= end; page++) entries.push(page);
+ if (end < total - 1) entries.push("end-ellipsis");
+
+ entries.push(total);
+ return entries;
+}
+
+export function NumberedPagination({
+ currentPage,
+ totalPages,
+ onPageChange,
+}: {
+ currentPage: number;
+ totalPages: number;
+ onPageChange: (page: number) => void;
+}) {
+ if (totalPages <= 1) return null;
+
+ const goToPage = (page: number) => {
+ const next = Math.min(Math.max(page, 1), totalPages);
+ if (next !== currentPage) onPageChange(next);
+ };
+
+ return (
+ <Pagination>
+ <PaginationContent>
+ <PaginationItem>
+ <PaginationPrevious
+ href="#"
+ aria-disabled={currentPage === 1 || undefined}
+ className={
+ currentPage === 1 ? "pointer-events-none opacity-50" : undefined
+ }
+ onClick={(event) => {
+ event.preventDefault();
+ goToPage(currentPage - 1);
+ }}
+ />
+ </PaginationItem>
+ {paginationRange(currentPage, totalPages).map((entry) =>
+ entry === "start-ellipsis" || entry === "end-ellipsis" ? (
+ <PaginationItem key={entry} className="max-sm:hidden">
+ <PaginationEllipsis />
+ </PaginationItem>
+ ) : (
+ <PaginationItem key={entry} className="max-sm:hidden">
+ <PaginationLink
+ href="#"
+ isActive={entry === currentPage}
+ onClick={(event) => {
+ event.preventDefault();
+ goToPage(entry);
+ }}
+ >
+ {entry}
+ </PaginationLink>
+ </PaginationItem>
+ ),
+ )}
+ <PaginationItem>
+ <PaginationNext
+ href="#"
+ aria-disabled={currentPage === totalPages || undefined}
+ className={
+ currentPage === totalPages
+ ? "pointer-events-none opacity-50"
+ : undefined
+ }
+ onClick={(event) => {
+ event.preventDefault();
+ goToPage(currentPage + 1);
+ }}
+ />
+ </PaginationItem>
+ </PaginationContent>
+ </Pagination>
+ );
+}
diff --git a/packages/ui/src/components/pagination.tsx b/packages/ui/src/components/pagination.tsx
new file mode 100644
index 00000000..3c131d2b
--- /dev/null
+++ b/packages/ui/src/components/pagination.tsx
@@ -0,0 +1,132 @@
+import { Button } from "@crm/ui/components/button";
+
+import { cn } from "@crm/ui/lib/utils";
+import {
+ ChevronLeftIcon,
+ ChevronRightIcon,
+ MoreHorizontalIcon,
+} from "lucide-react";
+import type * as React from "react";
+
+function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
+ return (
+ <nav
+ role="navigation"
+ aria-label="pagination"
+ data-slot="pagination"
+ className={cn("mx-auto flex w-full justify-center", className)}
+ {...props}
+ />
+ );
+}
+
+function PaginationContent({
+ className,
+ ...props
+}: React.ComponentProps<"ul">) {
+ return (
+ <ul
+ data-slot="pagination-content"
+ className={cn("flex items-center gap-0.5", className)}
+ {...props}
+ />
+ );
+}
+
+function PaginationItem({ ...props }: React.ComponentProps<"li">) {
+ return <li data-slot="pagination-item" {...props} />;
+}
+
+type PaginationLinkProps = {
+ isActive?: boolean;
+} & Pick<React.ComponentProps<typeof Button>, "size"> &
+ React.ComponentProps<"a">;
+
+function PaginationLink({
+ className,
+ isActive,
+ size = "icon",
+ ...props
+}: PaginationLinkProps) {
+ return (
+ <Button
+ asChild
+ variant={isActive ? "outline" : "ghost"}
+ size={size}
+ className={cn(className)}
+ >
+ <a
+ aria-current={isActive ? "page" : undefined}
+ data-slot="pagination-link"
+ data-active={isActive}
+ {...props}
+ />
+ </Button>
+ );
+}
+
+function PaginationPrevious({
+ className,
+ text = "Previous",
+ ...props
+}: React.ComponentProps<typeof PaginationLink> & { text?: string }) {
+ return (
+ <PaginationLink
+ aria-label="Go to previous page"
+ size="default"
+ className={cn("pl-1.5!", className)}
+ {...props}
+ >
+ <ChevronLeftIcon data-icon="inline-start" />
+ <span className="hidden sm:block">{text}</span>
+ </PaginationLink>
+ );
+}
+
+function PaginationNext({
+ className,
+ text = "Next",
+ ...props
+}: React.ComponentProps<typeof PaginationLink> & { text?: string }) {
+ return (
+ <PaginationLink
+ aria-label="Go to next page"
+ size="default"
+ className={cn("pr-1.5!", className)}
+ {...props}
+ >
+ <span className="hidden sm:block">{text}</span>
+ <ChevronRightIcon data-icon="inline-end" />
+ </PaginationLink>
+ );
+}
+
+function PaginationEllipsis({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ aria-hidden
+ data-slot="pagination-ellipsis"
+ className={cn(
+ "flex size-8 items-center justify-center [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ <MoreHorizontalIcon />
+ <span className="sr-only">More pages</span>
+ </span>
+ );
+}
+
+export {
+ Pagination,
+ PaginationContent,
+ PaginationEllipsis,
+ PaginationItem,
+ PaginationLink,
+ PaginationNext,
+ PaginationPrevious,
+};
diff --git a/packages/ui/src/components/popover.tsx b/packages/ui/src/components/popover.tsx
new file mode 100644
index 00000000..3200a759
--- /dev/null
+++ b/packages/ui/src/components/popover.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { Popover as PopoverPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Popover({
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
+ return <PopoverPrimitive.Root data-slot="popover" {...props} />;
+}
+
+function PopoverTrigger({
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
+ return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
+}
+
+function PopoverContent({
+ className,
+ align = "center",
+ sideOffset = 4,
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
+ return (
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ data-slot="popover-content"
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-none bg-popover p-2.5 text-xs text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ </PopoverPrimitive.Portal>
+ );
+}
+
+function PopoverAnchor({
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
+ return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
+}
+
+function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="popover-header"
+ className={cn("flex flex-col gap-1 text-xs", className)}
+ {...props}
+ />
+ );
+}
+
+function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
+ return (
+ <div
+ data-slot="popover-title"
+ className={cn("text-sm font-medium", className)}
+ {...props}
+ />
+ );
+}
+
+function PopoverDescription({
+ className,
+ ...props
+}: React.ComponentProps<"p">) {
+ return (
+ <p
+ data-slot="popover-description"
+ className={cn("text-xs/relaxed text-muted-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Popover,
+ PopoverAnchor,
+ PopoverContent,
+ PopoverDescription,
+ PopoverHeader,
+ PopoverTitle,
+ PopoverTrigger,
+};
diff --git a/packages/ui/src/components/progress.tsx b/packages/ui/src/components/progress.tsx
new file mode 100644
index 00000000..c0aa9b6e
--- /dev/null
+++ b/packages/ui/src/components/progress.tsx
@@ -0,0 +1,42 @@
+"use client";
+
+import { type Bloom, bloomClass } from "@crm/ui/lib/dither";
+import { cn } from "@crm/ui/lib/utils";
+import { Progress as ProgressPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Progress({
+ className,
+ value,
+ bloom = "low",
+ ...props
+}: React.ComponentProps<typeof ProgressPrimitive.Root> & {
+ bloom?: Bloom;
+}) {
+ return (
+ <ProgressPrimitive.Root
+ data-slot="progress"
+ className={cn(
+ "relative flex h-1 w-full items-center overflow-hidden rounded-none bg-muted",
+ className,
+ )}
+ {...props}
+ >
+ <ProgressPrimitive.Indicator
+ data-slot="progress-indicator"
+ className={cn(
+ "size-full flex-1 bg-primary transition-all",
+ bloomClass(bloom),
+ )}
+ style={
+ {
+ transform: `translateX(-${100 - (value || 0)}%)`,
+ "--bloom-color": "var(--color-primary)",
+ } as React.CSSProperties
+ }
+ />
+ </ProgressPrimitive.Root>
+ );
+}
+
+export { Progress };
diff --git a/packages/ui/src/components/radio-group.tsx b/packages/ui/src/components/radio-group.tsx
new file mode 100644
index 00000000..b4254523
--- /dev/null
+++ b/packages/ui/src/components/radio-group.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { RadioGroup as RadioGroupPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function RadioGroup({
+ className,
+ ...props
+}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
+ return (
+ <RadioGroupPrimitive.Root
+ data-slot="radio-group"
+ className={cn("grid w-full gap-2", className)}
+ {...props}
+ />
+ );
+}
+
+function RadioGroupItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
+ return (
+ <RadioGroupPrimitive.Item
+ data-slot="radio-group-item"
+ className={cn(
+ "group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",
+ className,
+ )}
+ {...props}
+ >
+ <RadioGroupPrimitive.Indicator
+ data-slot="radio-group-indicator"
+ className="flex size-4 items-center justify-center"
+ >
+ <span className="absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground" />
+ </RadioGroupPrimitive.Indicator>
+ </RadioGroupPrimitive.Item>
+ );
+}
+
+export { RadioGroup, RadioGroupItem };
diff --git a/packages/ui/src/components/resizable.tsx b/packages/ui/src/components/resizable.tsx
new file mode 100644
index 00000000..4f79c43c
--- /dev/null
+++ b/packages/ui/src/components/resizable.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import * as ResizablePrimitive from "react-resizable-panels";
+
+function ResizablePanelGroup({
+ className,
+ ...props
+}: ResizablePrimitive.GroupProps) {
+ return (
+ <ResizablePrimitive.Group
+ data-slot="resizable-panel-group"
+ className={cn(
+ "flex h-full w-full aria-[orientation=vertical]:flex-col",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ResizablePanel({ ...props }: ResizablePrimitive.PanelProps) {
+ return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />;
+}
+
+function ResizableHandle({
+ withHandle,
+ className,
+ ...props
+}: ResizablePrimitive.SeparatorProps & {
+ withHandle?: boolean;
+}) {
+ return (
+ <ResizablePrimitive.Separator
+ data-slot="resizable-handle"
+ className={cn(
+ "relative flex w-px items-center justify-center bg-border ring-offset-background after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-hidden aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90",
+ className,
+ )}
+ {...props}
+ >
+ {withHandle && (
+ <div className="z-10 flex h-6 w-1 shrink-0 rounded-none bg-border" />
+ )}
+ </ResizablePrimitive.Separator>
+ );
+}
+
+export { ResizableHandle, ResizablePanel, ResizablePanelGroup };
diff --git a/packages/ui/src/components/scroll-area.tsx b/packages/ui/src/components/scroll-area.tsx
new file mode 100644
index 00000000..d20b380b
--- /dev/null
+++ b/packages/ui/src/components/scroll-area.tsx
@@ -0,0 +1,54 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { ScrollArea as ScrollAreaPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function ScrollArea({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
+ return (
+ <ScrollAreaPrimitive.Root
+ data-slot="scroll-area"
+ className={cn("relative", className)}
+ {...props}
+ >
+ <ScrollAreaPrimitive.Viewport
+ data-slot="scroll-area-viewport"
+ className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
+ >
+ {children}
+ </ScrollAreaPrimitive.Viewport>
+ <ScrollBar />
+ <ScrollAreaPrimitive.Corner />
+ </ScrollAreaPrimitive.Root>
+ );
+}
+
+function ScrollBar({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
+ return (
+ <ScrollAreaPrimitive.ScrollAreaScrollbar
+ data-slot="scroll-area-scrollbar"
+ data-orientation={orientation}
+ orientation={orientation}
+ className={cn(
+ "flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
+ className,
+ )}
+ {...props}
+ >
+ <ScrollAreaPrimitive.ScrollAreaThumb
+ data-slot="scroll-area-thumb"
+ className="relative flex-1 rounded-none bg-border"
+ />
+ </ScrollAreaPrimitive.ScrollAreaScrollbar>
+ );
+}
+
+export { ScrollArea, ScrollBar };
diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsx
new file mode 100644
index 00000000..9d65cb55
--- /dev/null
+++ b/packages/ui/src/components/select.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
+import { Select as SelectPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Select({
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Root>) {
+ return <SelectPrimitive.Root data-slot="select" {...props} />;
+}
+
+function SelectGroup({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Group>) {
+ return (
+ <SelectPrimitive.Group
+ data-slot="select-group"
+ className={cn("scroll-my-1", className)}
+ {...props}
+ />
+ );
+}
+
+function SelectValue({
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Value>) {
+ return <SelectPrimitive.Value data-slot="select-value" {...props} />;
+}
+
+function SelectTrigger({
+ className,
+ size = "default",
+ children,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
+ size?: "sm" | "default";
+}) {
+ return (
+ <SelectPrimitive.Trigger
+ data-slot="select-trigger"
+ data-size={size}
+ className={cn(
+ "flex w-fit items-center justify-between gap-1.5 rounded-none border border-input bg-transparent py-2 pr-2 pl-2.5 text-xs whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-none *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <SelectPrimitive.Icon asChild>
+ <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+ );
+}
+
+function SelectContent({
+ className,
+ children,
+ position = "item-aligned",
+ align = "center",
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Content>) {
+ return (
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ data-slot="select-content"
+ data-align-trigger={position === "item-aligned"}
+ className={cn(
+ "relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-none bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ position === "popper" &&
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
+ className,
+ )}
+ position={position}
+ align={align}
+ {...props}
+ >
+ <SelectScrollUpButton />
+ <SelectPrimitive.Viewport
+ data-position={position}
+ className={cn(
+ "data-[position=popper]:h-(--radix-select-trigger-height) data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)",
+ position === "popper" && "",
+ )}
+ >
+ {children}
+ </SelectPrimitive.Viewport>
+ <SelectScrollDownButton />
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+ );
+}
+
+function SelectLabel({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Label>) {
+ return (
+ <SelectPrimitive.Label
+ data-slot="select-label"
+ className={cn("px-2 py-2 text-xs text-muted-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+function SelectItem({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Item>) {
+ return (
+ <SelectPrimitive.Item
+ data-slot="select-item"
+ className={cn(
+ "relative flex w-full cursor-default items-center gap-2 rounded-none py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
+ className,
+ )}
+ {...props}
+ >
+ <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
+ <SelectPrimitive.ItemIndicator>
+ <CheckIcon className="pointer-events-none" />
+ </SelectPrimitive.ItemIndicator>
+ </span>
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ </SelectPrimitive.Item>
+ );
+}
+
+function SelectSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
+ return (
+ <SelectPrimitive.Separator
+ data-slot="select-separator"
+ className={cn("pointer-events-none -mx-1 h-px bg-border", className)}
+ {...props}
+ />
+ );
+}
+
+function SelectScrollUpButton({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
+ return (
+ <SelectPrimitive.ScrollUpButton
+ data-slot="select-scroll-up-button"
+ className={cn(
+ "z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ <ChevronUpIcon />
+ </SelectPrimitive.ScrollUpButton>
+ );
+}
+
+function SelectScrollDownButton({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
+ return (
+ <SelectPrimitive.ScrollDownButton
+ data-slot="select-scroll-down-button"
+ className={cn(
+ "z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ <ChevronDownIcon />
+ </SelectPrimitive.ScrollDownButton>
+ );
+}
+
+export {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectScrollDownButton,
+ SelectScrollUpButton,
+ SelectSeparator,
+ SelectTrigger,
+ SelectValue,
+};
diff --git a/packages/ui/src/components/separator.tsx b/packages/ui/src/components/separator.tsx
new file mode 100644
index 00000000..13933dc6
--- /dev/null
+++ b/packages/ui/src/components/separator.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { Separator as SeparatorPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Separator({
+ className,
+ orientation = "horizontal",
+ decorative = true,
+ ...props
+}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
+ return (
+ <SeparatorPrimitive.Root
+ data-slot="separator"
+ decorative={decorative}
+ orientation={orientation}
+ className={cn(
+ "shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Separator };
diff --git a/packages/ui/src/components/sheet.tsx b/packages/ui/src/components/sheet.tsx
new file mode 100644
index 00000000..94f7cd88
--- /dev/null
+++ b/packages/ui/src/components/sheet.tsx
@@ -0,0 +1,187 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { XIcon } from "lucide-react";
+import { Dialog as SheetPrimitive } from "radix-ui";
+import type * as React from "react";
+
+// Width scale for left/right sheets (desktop only — the mobile drawer is
+// full-width). Default is `sm` (forms); `lg` is the standard detail width;
+// `xl` is for content that needs the extra room. `2xl` is the record sheet —
+// a company, contact or deal with its tabs, which replaces what would
+// otherwise be a page, and so gets close to page width.
+const sheetContentVariants = cva(
+ "fixed z-50 flex flex-col bg-popover bg-clip-padding text-xs/relaxed text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10",
+ {
+ variants: {
+ size: {
+ sm: "data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",
+ lg: "data-[side=left]:sm:max-w-3xl data-[side=right]:sm:max-w-3xl",
+ xl: "data-[side=left]:sm:max-w-4xl data-[side=right]:sm:max-w-4xl",
+ "2xl":
+ "data-[side=left]:sm:max-w-5xl data-[side=right]:sm:max-w-5xl data-[side=left]:lg:w-[68vw] data-[side=right]:lg:w-[68vw]",
+ },
+ },
+ defaultVariants: {
+ size: "sm",
+ },
+ },
+);
+
+export type SheetSize = NonNullable<
+ VariantProps<typeof sheetContentVariants>["size"]
+>;
+
+function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
+ return <SheetPrimitive.Root data-slot="sheet" {...props} />;
+}
+
+function SheetTrigger({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
+ return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
+}
+
+function SheetClose({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Close>) {
+ return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
+}
+
+function SheetPortal({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
+ return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
+}
+
+function SheetOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
+ return (
+ <SheetPrimitive.Overlay
+ data-slot="sheet-overlay"
+ className={cn(
+ "fixed inset-0 z-50 bg-black/10 text-xs/relaxed duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SheetContent({
+ className,
+ children,
+ side = "right",
+ size,
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Content> & {
+ side?: "top" | "right" | "bottom" | "left";
+ size?: SheetSize;
+ showCloseButton?: boolean;
+}) {
+ return (
+ <SheetPortal>
+ <SheetOverlay />
+ <SheetPrimitive.Content
+ data-slot="sheet-content"
+ data-side={side}
+ className={cn(sheetContentVariants({ size }), className)}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <SheetPrimitive.Close data-slot="sheet-close" asChild>
+ <Button
+ variant="ghost"
+ className="absolute top-3 right-3"
+ size="icon-sm"
+ >
+ <XIcon />
+ <span className="sr-only">Close</span>
+ </Button>
+ </SheetPrimitive.Close>
+ )}
+ </SheetPrimitive.Content>
+ </SheetPortal>
+ );
+}
+
+function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-header"
+ className={cn("flex flex-col gap-0.5 p-4", className)}
+ {...props}
+ />
+ );
+}
+
+function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-footer"
+ className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ {...props}
+ />
+ );
+}
+
+// `default` is the form sheet — a line of instruction above some fields.
+// `lg` is the record sheet, where the title is the name of the thing you
+// opened and has to carry the panel the way a page heading would.
+const sheetTitleVariants = cva("font-heading font-medium text-foreground", {
+ variants: {
+ size: {
+ default: "text-sm",
+ lg: "text-lg leading-tight tracking-tight",
+ },
+ },
+ defaultVariants: {
+ size: "default",
+ },
+});
+
+function SheetTitle({
+ className,
+ size,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Title> &
+ VariantProps<typeof sheetTitleVariants>) {
+ return (
+ <SheetPrimitive.Title
+ data-slot="sheet-title"
+ className={cn(sheetTitleVariants({ size }), className)}
+ {...props}
+ />
+ );
+}
+
+function SheetDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Description>) {
+ return (
+ <SheetPrimitive.Description
+ data-slot="sheet-description"
+ className={cn("text-xs/relaxed text-muted-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ SheetTrigger,
+ sheetContentVariants,
+};
diff --git a/packages/ui/src/components/sidebar.tsx b/packages/ui/src/components/sidebar.tsx
new file mode 100644
index 00000000..63d4c2ac
--- /dev/null
+++ b/packages/ui/src/components/sidebar.tsx
@@ -0,0 +1,692 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { Input } from "@crm/ui/components/input";
+import { Separator } from "@crm/ui/components/separator";
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@crm/ui/components/sheet";
+import { Skeleton } from "@crm/ui/components/skeleton";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@crm/ui/components/tooltip";
+import { useIsMobile } from "@crm/ui/hooks/use-mobile";
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { PanelLeftIcon } from "lucide-react";
+import { Slot } from "radix-ui";
+import * as React from "react";
+
+const SIDEBAR_COOKIE_NAME = "sidebar_state";
+const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
+const SIDEBAR_WIDTH = "16rem";
+const SIDEBAR_WIDTH_MOBILE = "18rem";
+const SIDEBAR_WIDTH_ICON = "3rem";
+const SIDEBAR_KEYBOARD_SHORTCUT = "b";
+
+type SidebarContextProps = {
+ state: "expanded" | "collapsed";
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ openMobile: boolean;
+ setOpenMobile: (open: boolean) => void;
+ isMobile: boolean;
+ toggleSidebar: () => void;
+};
+
+const SidebarContext = React.createContext<SidebarContextProps | null>(null);
+
+function useSidebar() {
+ const context = React.useContext(SidebarContext);
+ if (!context) {
+ throw new Error("useSidebar must be used within a SidebarProvider.");
+ }
+
+ return context;
+}
+
+function SidebarProvider({
+ defaultOpen = true,
+ open: openProp,
+ onOpenChange: setOpenProp,
+ className,
+ style,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & {
+ defaultOpen?: boolean;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+}) {
+ const isMobile = useIsMobile();
+ const [openMobile, setOpenMobile] = React.useState(false);
+
+ const [_open, _setOpen] = React.useState(defaultOpen);
+ const open = openProp ?? _open;
+ const setOpen = React.useCallback(
+ (value: boolean | ((value: boolean) => boolean)) => {
+ const openState = typeof value === "function" ? value(open) : value;
+ if (setOpenProp) {
+ setOpenProp(openState);
+ } else {
+ _setOpen(openState);
+ }
+
+ document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
+ },
+ [setOpenProp, open],
+ );
+
+ const toggleSidebar = React.useCallback(() => {
+ return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
+ }, [isMobile, setOpen, setOpenMobile]);
+
+ React.useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (
+ event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
+ (event.metaKey || event.ctrlKey)
+ ) {
+ event.preventDefault();
+ toggleSidebar();
+ }
+ };
+
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [toggleSidebar]);
+
+ const state = open ? "expanded" : "collapsed";
+
+ const contextValue = React.useMemo<SidebarContextProps>(
+ () => ({
+ state,
+ open,
+ setOpen,
+ isMobile,
+ openMobile,
+ setOpenMobile,
+ toggleSidebar,
+ }),
+ [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
+ );
+
+ return (
+ <SidebarContext.Provider value={contextValue}>
+ <div
+ data-slot="sidebar-wrapper"
+ style={
+ {
+ "--sidebar-width": SIDEBAR_WIDTH,
+ "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
+ ...style,
+ } as React.CSSProperties
+ }
+ className={cn(
+ "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ </SidebarContext.Provider>
+ );
+}
+
+function Sidebar({
+ side = "left",
+ variant = "sidebar",
+ collapsible = "offcanvas",
+ className,
+ children,
+ dir,
+ ...props
+}: React.ComponentProps<"div"> & {
+ side?: "left" | "right";
+ variant?: "sidebar" | "floating" | "inset";
+ collapsible?: "offcanvas" | "icon" | "none";
+}) {
+ const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
+
+ if (collapsible === "none") {
+ return (
+ <div
+ data-slot="sidebar"
+ className={cn(
+ "flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+ }
+
+ if (isMobile) {
+ return (
+ <Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
+ <SheetContent
+ dir={dir}
+ data-sidebar="sidebar"
+ data-slot="sidebar"
+ data-mobile="true"
+ className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
+ style={
+ {
+ "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
+ } as React.CSSProperties
+ }
+ side={side}
+ >
+ <SheetHeader className="sr-only">
+ <SheetTitle>Sidebar</SheetTitle>
+ <SheetDescription>Displays the mobile sidebar.</SheetDescription>
+ </SheetHeader>
+ <div className="flex h-full w-full flex-col">{children}</div>
+ </SheetContent>
+ </Sheet>
+ );
+ }
+
+ return (
+ <div
+ className="group peer hidden text-sidebar-foreground md:block"
+ data-state={state}
+ data-collapsible={state === "collapsed" ? collapsible : ""}
+ data-variant={variant}
+ data-side={side}
+ data-slot="sidebar"
+ >
+ {/* This is what handles the sidebar gap on desktop */}
+ <div
+ data-slot="sidebar-gap"
+ className={cn(
+ "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
+ "group-data-[collapsible=offcanvas]:w-0",
+ "group-data-[side=right]:rotate-180",
+ variant === "floating" || variant === "inset"
+ ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
+ )}
+ />
+ <div
+ data-slot="sidebar-container"
+ data-side={side}
+ className={cn(
+ "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",
+ variant === "floating" || variant === "inset"
+ ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
+ className,
+ )}
+ {...props}
+ >
+ <div
+ data-sidebar="sidebar"
+ data-slot="sidebar-inner"
+ className="flex size-full flex-col bg-sidebar group-data-[variant=floating]:rounded-none group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border"
+ >
+ {children}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function SidebarTrigger({
+ className,
+ onClick,
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ const { toggleSidebar } = useSidebar();
+
+ return (
+ <Button
+ data-sidebar="trigger"
+ data-slot="sidebar-trigger"
+ variant="ghost"
+ size="icon-sm"
+ className={cn(className)}
+ onClick={(event) => {
+ onClick?.(event);
+ toggleSidebar();
+ }}
+ {...props}
+ >
+ <PanelLeftIcon />
+ <span className="sr-only">Toggle Sidebar</span>
+ </Button>
+ );
+}
+
+function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
+ const { toggleSidebar } = useSidebar();
+
+ return (
+ <button
+ data-sidebar="rail"
+ data-slot="sidebar-rail"
+ aria-label="Toggle Sidebar"
+ tabIndex={-1}
+ onClick={toggleSidebar}
+ title="Toggle Sidebar"
+ className={cn(
+ "absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
+ "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
+ "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
+ "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
+ "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
+ "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
+ return (
+ <main
+ data-slot="sidebar-inset"
+ className={cn(
+ "relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-none md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SidebarInput({
+ className,
+ ...props
+}: React.ComponentProps<typeof Input>) {
+ return (
+ <Input
+ data-slot="sidebar-input"
+ data-sidebar="input"
+ className={cn("h-8 w-full bg-background shadow-none", className)}
+ {...props}
+ />
+ );
+}
+
+function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-header"
+ data-sidebar="header"
+ className={cn("flex flex-col gap-2 p-2", className)}
+ {...props}
+ />
+ );
+}
+
+function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-footer"
+ data-sidebar="footer"
+ className={cn("flex flex-col gap-2 p-2", className)}
+ {...props}
+ />
+ );
+}
+
+function SidebarSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return (
+ <Separator
+ data-slot="sidebar-separator"
+ data-sidebar="separator"
+ className={cn("mx-2 w-auto bg-sidebar-border", className)}
+ {...props}
+ />
+ );
+}
+
+function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-content"
+ data-sidebar="content"
+ className={cn(
+ "no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-group"
+ data-sidebar="group"
+ className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
+ {...props}
+ />
+ );
+}
+
+function SidebarGroupLabel({
+ className,
+ asChild = false,
+ ...props
+}: React.ComponentProps<"div"> & { asChild?: boolean }) {
+ const Comp = asChild ? Slot.Root : "div";
+
+ return (
+ <Comp
+ data-slot="sidebar-group-label"
+ data-sidebar="group-label"
+ className={cn(
+ "flex h-8 shrink-0 items-center rounded-none px-2 text-xs text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SidebarGroupAction({
+ className,
+ asChild = false,
+ ...props
+}: React.ComponentProps<"button"> & { asChild?: boolean }) {
+ const Comp = asChild ? Slot.Root : "button";
+
+ return (
+ <Comp
+ data-slot="sidebar-group-action"
+ data-sidebar="group-action"
+ className={cn(
+ "absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-none p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SidebarGroupContent({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-group-content"
+ data-sidebar="group-content"
+ className={cn("w-full text-xs", className)}
+ {...props}
+ />
+ );
+}
+
+function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
+ return (
+ <ul
+ data-slot="sidebar-menu"
+ data-sidebar="menu"
+ className={cn("flex w-full min-w-0 flex-col gap-0", className)}
+ {...props}
+ />
+ );
+}
+
+function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="sidebar-menu-item"
+ data-sidebar="menu-item"
+ className={cn("group/menu-item relative", className)}
+ {...props}
+ />
+ );
+}
+
+const sidebarMenuButtonVariants = cva(
+ "peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-none p-2 text-left text-xs ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",
+ {
+ variants: {
+ variant: {
+ default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
+ outline:
+ "bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
+ },
+ size: {
+ default: "h-8 text-xs",
+ sm: "h-7 text-xs",
+ lg: "h-12 text-xs group-data-[collapsible=icon]:p-0!",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+function SidebarMenuButton({
+ asChild = false,
+ isActive = false,
+ variant = "default",
+ size = "default",
+ tooltip,
+ className,
+ ...props
+}: React.ComponentProps<"button"> & {
+ asChild?: boolean;
+ isActive?: boolean;
+ tooltip?: string | React.ComponentProps<typeof TooltipContent>;
+} & VariantProps<typeof sidebarMenuButtonVariants>) {
+ const Comp = asChild ? Slot.Root : "button";
+ const { isMobile, state } = useSidebar();
+
+ const button = (
+ <Comp
+ data-slot="sidebar-menu-button"
+ data-sidebar="menu-button"
+ data-size={size}
+ data-active={isActive}
+ className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
+ {...props}
+ />
+ );
+
+ if (!tooltip) {
+ return button;
+ }
+
+ if (typeof tooltip === "string") {
+ tooltip = {
+ children: tooltip,
+ };
+ }
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>{button}</TooltipTrigger>
+ <TooltipContent
+ side="right"
+ align="center"
+ hidden={state !== "collapsed" || isMobile}
+ {...tooltip}
+ />
+ </Tooltip>
+ );
+}
+
+function SidebarMenuAction({
+ className,
+ asChild = false,
+ showOnHover = false,
+ ...props
+}: React.ComponentProps<"button"> & {
+ asChild?: boolean;
+ showOnHover?: boolean;
+}) {
+ const Comp = asChild ? Slot.Root : "button";
+
+ return (
+ <Comp
+ data-slot="sidebar-menu-action"
+ data-sidebar="menu-action"
+ className={cn(
+ "absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-none p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
+ showOnHover &&
+ "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground aria-expanded:opacity-100 md:opacity-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SidebarMenuBadge({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-menu-badge"
+ data-sidebar="menu-badge"
+ className={cn(
+ "pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-none px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 peer-data-active/menu-button:text-sidebar-accent-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SidebarMenuSkeleton({
+ className,
+ showIcon = false,
+ ...props
+}: React.ComponentProps<"div"> & {
+ showIcon?: boolean;
+}) {
+ const [width] = React.useState(() => {
+ return `${Math.floor(Math.random() * 40) + 50}%`;
+ });
+
+ return (
+ <div
+ data-slot="sidebar-menu-skeleton"
+ data-sidebar="menu-skeleton"
+ className={cn("flex h-8 items-center gap-2 rounded-none px-2", className)}
+ {...props}
+ >
+ {showIcon && (
+ <Skeleton
+ className="size-4 rounded-none"
+ data-sidebar="menu-skeleton-icon"
+ />
+ )}
+ <Skeleton
+ className="h-4 max-w-(--skeleton-width) flex-1"
+ data-sidebar="menu-skeleton-text"
+ style={
+ {
+ "--skeleton-width": width,
+ } as React.CSSProperties
+ }
+ />
+ </div>
+ );
+}
+
+function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
+ return (
+ <ul
+ data-slot="sidebar-menu-sub"
+ data-sidebar="menu-sub"
+ className={cn(
+ "mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5 group-data-[collapsible=icon]:hidden",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SidebarMenuSubItem({
+ className,
+ ...props
+}: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="sidebar-menu-sub-item"
+ data-sidebar="menu-sub-item"
+ className={cn("group/menu-sub-item relative", className)}
+ {...props}
+ />
+ );
+}
+
+function SidebarMenuSubButton({
+ asChild = false,
+ size = "md",
+ isActive = false,
+ className,
+ ...props
+}: React.ComponentProps<"a"> & {
+ asChild?: boolean;
+ size?: "sm" | "md";
+ isActive?: boolean;
+}) {
+ const Comp = asChild ? Slot.Root : "a";
+
+ return (
+ <Comp
+ data-slot="sidebar-menu-sub-button"
+ data-sidebar="menu-sub-button"
+ data-size={size}
+ data-active={isActive}
+ className={cn(
+ "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-none px-2 text-sidebar-foreground ring-sidebar-ring outline-hidden group-data-[collapsible=icon]:hidden hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-xs data-[size=sm]:text-xs data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Sidebar,
+ SidebarContent,
+ SidebarFooter,
+ SidebarGroup,
+ SidebarGroupAction,
+ SidebarGroupContent,
+ SidebarGroupLabel,
+ SidebarHeader,
+ SidebarInput,
+ SidebarInset,
+ SidebarMenu,
+ SidebarMenuAction,
+ SidebarMenuBadge,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ SidebarMenuSkeleton,
+ SidebarMenuSub,
+ SidebarMenuSubButton,
+ SidebarMenuSubItem,
+ SidebarProvider,
+ SidebarRail,
+ SidebarSeparator,
+ SidebarTrigger,
+ useSidebar,
+};
diff --git a/packages/ui/src/components/simple-table.tsx b/packages/ui/src/components/simple-table.tsx
new file mode 100644
index 00000000..494bbdb6
--- /dev/null
+++ b/packages/ui/src/components/simple-table.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import {
+ Table,
+ TableBody,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@crm/ui/components/table";
+import {
+ ROW_ACCENT,
+ ROW_ACCENT_EXPANDABLE,
+} from "@crm/ui/lib/row-accent";
+import { cn } from "@crm/ui/lib/utils";
+import type { ComponentProps, ReactNode } from "react";
+
+export type SimpleTableColumn = {
+ header?: ReactNode;
+ srLabel?: string;
+ width?: string;
+ align?: "left" | "right" | "center";
+ className?: string;
+};
+
+const ALIGN_CLASS = {
+ left: "",
+ right: "text-right",
+ center: "text-center",
+} as const;
+
+export function SimpleTable({
+ columns,
+ children,
+ variant = "default",
+ className,
+ containerClassName,
+ headerClassName,
+ headerRowClassName,
+ headerHeight,
+}: {
+ columns: SimpleTableColumn[];
+ children: ReactNode;
+ /**
+ * `panel` fills the remaining height of a sheet tab and pins the header
+ * while the rows scroll under it. Everywhere else the table is one block in
+ * a column of blocks and scrolls with the page.
+ */
+ variant?: "default" | "panel";
+ className?: string;
+ containerClassName?: string;
+ headerClassName?: string;
+ headerRowClassName?: string;
+ headerHeight?: string;
+}) {
+ const panel = variant === "panel";
+
+ return (
+ <Table
+ className={cn("w-full", panel && "table-fixed", className)}
+ containerClassName={cn(
+ panel && "min-h-0 flex-1 overflow-x-hidden overflow-y-auto",
+ containerClassName,
+ )}
+ >
+ <TableHeader
+ className={cn(
+ panel && "sticky top-0 z-10 bg-popover [&_th]:bg-popover",
+ headerClassName,
+ )}
+ >
+ <TableRow className={cn("hover:bg-transparent", headerRowClassName)}>
+ {columns.map((column, index) => (
+ <TableHead
+ key={index}
+ aria-label={column.header ? undefined : column.srLabel}
+ className={cn(
+ headerHeight ?? (panel ? "h-9" : "h-11"),
+ "px-3 font-normal text-muted-foreground",
+ column.width,
+ ALIGN_CLASS[column.align ?? "left"],
+ column.className,
+ )}
+ >
+ {column.header}
+ </TableHead>
+ ))}
+ </TableRow>
+ </TableHeader>
+ <TableBody>{children}</TableBody>
+ </Table>
+ );
+}
+
+export function SimpleTableRow({
+ clickable,
+ expandable,
+ className,
+ ...props
+}: ComponentProps<typeof TableRow> & {
+ clickable?: boolean;
+ expandable?: boolean;
+}) {
+ return (
+ <TableRow
+ className={cn(
+ "hover:bg-transparent",
+ clickable && (expandable ? ROW_ACCENT_EXPANDABLE : ROW_ACCENT),
+ className,
+ )}
+ {...props}
+ />
+ );
+}
diff --git a/packages/ui/src/components/skeleton.tsx b/packages/ui/src/components/skeleton.tsx
new file mode 100644
index 00000000..26fc1a8c
--- /dev/null
+++ b/packages/ui/src/components/skeleton.tsx
@@ -0,0 +1,13 @@
+import { cn } from "@crm/ui/lib/utils";
+
+function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="skeleton"
+ className={cn("animate-pulse rounded-none bg-muted", className)}
+ {...props}
+ />
+ );
+}
+
+export { Skeleton };
diff --git a/packages/ui/src/components/slider.tsx b/packages/ui/src/components/slider.tsx
new file mode 100644
index 00000000..c2895a23
--- /dev/null
+++ b/packages/ui/src/components/slider.tsx
@@ -0,0 +1,58 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { Slider as SliderPrimitive } from "radix-ui";
+import * as React from "react";
+
+function Slider({
+ className,
+ defaultValue,
+ value,
+ min = 0,
+ max = 100,
+ ...props
+}: React.ComponentProps<typeof SliderPrimitive.Root>) {
+ const _values = React.useMemo(
+ () =>
+ Array.isArray(value)
+ ? value
+ : Array.isArray(defaultValue)
+ ? defaultValue
+ : [min, max],
+ [value, defaultValue, min, max],
+ );
+
+ return (
+ <SliderPrimitive.Root
+ data-slot="slider"
+ defaultValue={defaultValue}
+ value={value}
+ min={min}
+ max={max}
+ className={cn(
+ "relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-vertical:h-full data-vertical:min-h-40 data-vertical:w-auto data-vertical:flex-col",
+ className,
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track
+ data-slot="slider-track"
+ className="relative grow overflow-hidden rounded-none bg-muted data-horizontal:h-1 data-horizontal:w-full data-vertical:h-full data-vertical:w-1"
+ >
+ <SliderPrimitive.Range
+ data-slot="slider-range"
+ className="absolute bg-primary select-none data-horizontal:h-full data-vertical:w-full"
+ />
+ </SliderPrimitive.Track>
+ {Array.from({ length: _values.length }, (_, index) => (
+ <SliderPrimitive.Thumb
+ data-slot="slider-thumb"
+ key={index}
+ className="relative block size-3 shrink-0 rounded-none border border-ring bg-white ring-ring/50 transition-[color,box-shadow] select-none after:absolute after:-inset-2 hover:ring-1 focus-visible:ring-1 focus-visible:outline-hidden active:ring-1 disabled:pointer-events-none disabled:opacity-50"
+ />
+ ))}
+ </SliderPrimitive.Root>
+ );
+}
+
+export { Slider };
diff --git a/packages/ui/src/components/sonner.tsx b/packages/ui/src/components/sonner.tsx
new file mode 100644
index 00000000..e37dcdea
--- /dev/null
+++ b/packages/ui/src/components/sonner.tsx
@@ -0,0 +1,46 @@
+"use client";
+
+import {
+ CircleCheckIcon,
+ InfoIcon,
+ Loader2Icon,
+ OctagonXIcon,
+ TriangleAlertIcon,
+} from "lucide-react";
+import { useTheme } from "next-themes";
+import { Toaster as Sonner, type ToasterProps } from "sonner";
+
+const Toaster = ({ ...props }: ToasterProps) => {
+ const { theme = "system" } = useTheme();
+
+ return (
+ <Sonner
+ theme={theme as ToasterProps["theme"]}
+ position="bottom-left"
+ className="toaster group"
+ icons={{
+ success: <CircleCheckIcon className="size-4" />,
+ info: <InfoIcon className="size-4" />,
+ warning: <TriangleAlertIcon className="size-4" />,
+ error: <OctagonXIcon className="size-4" />,
+ loading: <Loader2Icon className="size-4 animate-spin" />,
+ }}
+ style={
+ {
+ "--normal-bg": "var(--popover)",
+ "--normal-text": "var(--popover-foreground)",
+ "--normal-border": "var(--border)",
+ "--border-radius": "var(--radius)",
+ } as React.CSSProperties
+ }
+ toastOptions={{
+ classNames: {
+ toast: "cn-toast",
+ },
+ }}
+ {...props}
+ />
+ );
+};
+
+export { Toaster };
diff --git a/packages/ui/src/components/spinner.tsx b/packages/ui/src/components/spinner.tsx
new file mode 100644
index 00000000..77eed8fd
--- /dev/null
+++ b/packages/ui/src/components/spinner.tsx
@@ -0,0 +1,16 @@
+import { cn } from "@crm/ui/lib/utils";
+import { Loader2Icon } from "lucide-react";
+
+function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
+ return (
+ <Loader2Icon
+ data-slot="spinner"
+ role="status"
+ aria-label="Loading"
+ className={cn("size-4 animate-spin", className)}
+ {...props}
+ />
+ );
+}
+
+export { Spinner };
diff --git a/packages/ui/src/components/stat-card.tsx b/packages/ui/src/components/stat-card.tsx
new file mode 100644
index 00000000..e03b898f
--- /dev/null
+++ b/packages/ui/src/components/stat-card.tsx
@@ -0,0 +1,109 @@
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+type TrendDirection = "up" | "down" | "neutral";
+
+type StatDelta = {
+ /** Pre-formatted change, e.g. "+12%" or "+3". */
+ value: string;
+ /** Drives the color + arrow. Defaults to inferring from a leading sign. */
+ direction?: TrendDirection;
+ /** Trailing context, e.g. "vs. last month". */
+ label?: string;
+};
+
+const TREND_COLOR: Record<TrendDirection, string> = {
+ up: "text-success",
+ down: "text-destructive",
+ neutral: "text-muted-foreground",
+};
+
+const TREND_GLYPH: Record<TrendDirection, string> = {
+ up: "↑",
+ down: "↓",
+ neutral: "→",
+};
+
+function inferDirection(value: string): TrendDirection {
+ if (value.trim().startsWith("-")) return "down";
+ if (value.trim().startsWith("+")) return "up";
+ return "neutral";
+}
+
+function StatDeltaText({
+ delta,
+ className,
+}: {
+ delta: StatDelta;
+ className?: string;
+}) {
+ const direction = delta.direction ?? inferDirection(delta.value);
+ return (
+ <span className={cn("inline-flex items-baseline gap-1.5", className)}>
+ <span
+ className={cn(
+ "inline-flex items-baseline gap-0.5 font-medium text-xs tabular-nums",
+ TREND_COLOR[direction],
+ )}
+ >
+ {direction !== "neutral" ? (
+ <span aria-hidden>{TREND_GLYPH[direction]}</span>
+ ) : null}
+ {delta.value}
+ </span>
+ {delta.label ? (
+ <span className="text-muted-foreground text-xs">{delta.label}</span>
+ ) : null}
+ </span>
+ );
+}
+
+/**
+ * A single KPI — label, headline value, optional trend delta, and an optional
+ * slot (`children`) for a sparkline. Intentionally borderless: drop several into
+ * a {@link StatGroup} so they read as one divider-separated strip rather than a
+ * row of competing boxes. Per the dashboard guidelines, KPIs carry no icons.
+ */
+function StatCard({
+ label,
+ value,
+ delta,
+ description,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"div">, "title"> & {
+ label?: React.ReactNode;
+ value: React.ReactNode;
+ delta?: StatDelta;
+ description?: React.ReactNode;
+}) {
+ return (
+ <div
+ data-slot="stat-card"
+ className={cn("flex flex-col gap-2.5 p-4 md:p-6", className)}
+ {...props}
+ >
+ {label != null ? (
+ <span className="truncate text-sm font-medium text-muted-foreground">
+ {label}
+ </span>
+ ) : null}
+ <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1">
+ <span className="font-medium text-3xl tracking-tight tabular-nums">
+ {value}
+ </span>
+ {delta ? <StatDeltaText delta={delta} /> : null}
+ </div>
+ {description ? (
+ <p className="text-pretty text-muted-foreground text-xs/relaxed">
+ {description}
+ </p>
+ ) : null}
+ {children}
+ </div>
+ );
+}
+
+export type { StatDelta, TrendDirection };
+export { StatCard, StatDeltaText };
diff --git a/packages/ui/src/components/status-indicator.tsx b/packages/ui/src/components/status-indicator.tsx
new file mode 100644
index 00000000..cc7b420c
--- /dev/null
+++ b/packages/ui/src/components/status-indicator.tsx
@@ -0,0 +1,113 @@
+import { Spinner } from "@crm/ui/components/spinner";
+import { type Bloom, bloomClass } from "@crm/ui/lib/dither";
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+/**
+ * The five states anything in this app can be in.
+ *
+ * Named for meaning rather than colour so a status reads the same everywhere:
+ * "the agent failed" and "the deal was lost" are both `error`, and neither
+ * caller gets to pick a shade.
+ */
+export type StatusTone = "neutral" | "info" | "success" | "warning" | "error";
+
+const TONE_COLOR: Record<StatusTone, string> = {
+ neutral: "var(--color-muted-foreground)",
+ info: "var(--color-info)",
+ success: "var(--color-success)",
+ warning: "var(--color-warning)",
+ error: "var(--color-destructive)",
+};
+
+function IndicatorDot({
+ tone = "neutral",
+ color,
+ pulse = false,
+ bloom = "low",
+ className,
+ style,
+ ...props
+}: React.ComponentProps<"span"> & {
+ tone?: StatusTone;
+ /** An explicit colour, for scales the tones do not cover. */
+ color?: string;
+ pulse?: boolean;
+ bloom?: Bloom;
+}) {
+ const resolved = color ?? TONE_COLOR[tone];
+
+ return (
+ <span
+ data-slot="indicator-dot"
+ data-tone={tone}
+ className={cn(
+ "inline-block size-1.5 shrink-0",
+ pulse && "animate-pulse",
+ bloomClass(bloom),
+ className,
+ )}
+ style={
+ {
+ backgroundColor: resolved,
+ "--bloom-color": resolved,
+ ...style,
+ } as React.CSSProperties
+ }
+ {...props}
+ />
+ );
+}
+
+/**
+ * A dot and a word — the only way this app shows a status.
+ *
+ * Deliberately not a badge: a table of pill-shaped chips in five colours is a
+ * table you read the chips of instead of the rows. A dot carries the same
+ * meaning at a tenth of the ink, and a column of them lines up.
+ */
+function StatusIndicator({
+ tone = "neutral",
+ color,
+ label,
+ pulse = false,
+ /** In-flight work: a spinner replaces the dot, as nothing is settled yet. */
+ busy = false,
+ bloom = "low",
+ className,
+ ...props
+}: Omit<React.ComponentProps<"span">, "color"> & {
+ tone?: StatusTone;
+ color?: string;
+ label: React.ReactNode;
+ pulse?: boolean;
+ busy?: boolean;
+ bloom?: Bloom;
+}) {
+ return (
+ <span
+ data-slot="status-indicator"
+ data-tone={tone}
+ className={cn(
+ "inline-flex min-w-0 items-center gap-2 text-muted-foreground",
+ className,
+ )}
+ {...props}
+ >
+ {busy ? (
+ <Spinner className="size-3 shrink-0" />
+ ) : (
+ <IndicatorDot
+ tone={tone}
+ color={color}
+ pulse={pulse}
+ bloom={bloom}
+ aria-hidden="true"
+ />
+ )}
+ <span className="truncate">{label}</span>
+ </span>
+ );
+}
+
+export { IndicatorDot, StatusIndicator, TONE_COLOR };
diff --git a/packages/ui/src/components/switch.tsx b/packages/ui/src/components/switch.tsx
new file mode 100644
index 00000000..1df25c8b
--- /dev/null
+++ b/packages/ui/src/components/switch.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { Switch as SwitchPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Switch({
+ className,
+ size = "default",
+ ...props
+}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
+ size?: "sm" | "default";
+}) {
+ return (
+ <SwitchPrimitive.Root
+ data-slot="switch"
+ data-size={size}
+ className={cn(
+ "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
+ className,
+ )}
+ {...props}
+ >
+ <SwitchPrimitive.Thumb
+ data-slot="switch-thumb"
+ className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
+ />
+ </SwitchPrimitive.Root>
+ );
+}
+
+export { Switch };
diff --git a/packages/ui/src/components/table-pagination.tsx b/packages/ui/src/components/table-pagination.tsx
new file mode 100644
index 00000000..75a7f3ea
--- /dev/null
+++ b/packages/ui/src/components/table-pagination.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+import ChevronLeft from "@carbon/icons-react/es/ChevronLeft";
+import ChevronRight from "@carbon/icons-react/es/ChevronRight";
+import { Button } from "@crm/ui/components/button";
+import { Spinner } from "@crm/ui/components/spinner";
+import type { ReactNode } from "react";
+
+const numberFormat = new Intl.NumberFormat();
+
+export function TablePagination({
+ page,
+ totalPages,
+ pageSize,
+ total,
+ onPageChange,
+ loading = false,
+ meta,
+}: {
+ page: number;
+ totalPages: number;
+ pageSize: number;
+ total: number;
+ onPageChange: (page: number) => void;
+ loading?: boolean;
+ meta?: ReactNode;
+}) {
+ const rangeStart = total === 0 ? 0 : (page - 1) * pageSize + 1;
+ const rangeEnd = Math.min(page * pageSize, total);
+
+ return (
+ <div className="flex shrink-0 flex-wrap items-center justify-between gap-3">
+ <span className="flex items-center gap-2 text-muted-foreground text-xs tabular-nums">
+ {loading && <Spinner />}
+ {meta ??
+ (total === 0
+ ? "No results"
+ : `Showing ${numberFormat.format(rangeStart)}–${numberFormat.format(
+ rangeEnd,
+ )} of ${numberFormat.format(total)}`)}
+ </span>
+ {totalPages > 1 && (
+ <div className="flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={page <= 1}
+ onClick={() => onPageChange(Math.max(1, page - 1))}
+ >
+ <ChevronLeft data-icon="inline-start" />
+ Previous
+ </Button>
+ <span className="text-muted-foreground text-xs tabular-nums">
+ {page} / {totalPages}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={page >= totalPages}
+ onClick={() => onPageChange(page + 1)}
+ >
+ Next
+ <ChevronRight data-icon="inline-end" />
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/table.tsx b/packages/ui/src/components/table.tsx
new file mode 100644
index 00000000..da828181
--- /dev/null
+++ b/packages/ui/src/components/table.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+function Table({
+ className,
+ containerClassName,
+ ...props
+}: React.ComponentProps<"table"> & { containerClassName?: string }) {
+ return (
+ <div
+ data-slot="table-container"
+ className={cn("relative w-full overflow-x-auto", containerClassName)}
+ >
+ <table
+ data-slot="table"
+ className={cn("w-full caption-bottom text-xs", className)}
+ {...props}
+ />
+ </div>
+ );
+}
+
+function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
+ return (
+ <thead
+ data-slot="table-header"
+ className={cn("[&_tr]:border-b", className)}
+ {...props}
+ />
+ );
+}
+
+function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
+ return (
+ <tbody
+ data-slot="table-body"
+ className={cn("[&_tr:last-child]:border-0", className)}
+ {...props}
+ />
+ );
+}
+
+function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
+ return (
+ <tfoot
+ data-slot="table-footer"
+ className={cn(
+ "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
+ return (
+ <tr
+ data-slot="table-row"
+ className={cn(
+ "border-b transition-colors has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TableHead({ className, ...props }: React.ComponentProps<"th">) {
+ return (
+ <th
+ data-slot="table-head"
+ className={cn(
+ "h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TableCell({ className, ...props }: React.ComponentProps<"td">) {
+ return (
+ <td
+ data-slot="table-cell"
+ className={cn(
+ "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TableCaption({
+ className,
+ ...props
+}: React.ComponentProps<"caption">) {
+ return (
+ <caption
+ data-slot="table-caption"
+ className={cn("mt-4 text-xs text-muted-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Table,
+ TableBody,
+ TableCaption,
+ TableCell,
+ TableFooter,
+ TableHead,
+ TableHeader,
+ TableRow,
+};
diff --git a/packages/ui/src/components/tabs.tsx b/packages/ui/src/components/tabs.tsx
new file mode 100644
index 00000000..1161a43b
--- /dev/null
+++ b/packages/ui/src/components/tabs.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { Tabs as TabsPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Tabs({
+ className,
+ orientation = "horizontal",
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.Root>) {
+ return (
+ <TabsPrimitive.Root
+ data-slot="tabs"
+ data-orientation={orientation}
+ className={cn(
+ "group/tabs flex gap-2 data-horizontal:flex-col",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+const tabsListVariants = cva(
+ "group/tabs-list inline-flex w-fit items-center justify-center rounded-none p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
+ {
+ variants: {
+ variant: {
+ default: "bg-muted",
+ line: "gap-1 bg-transparent",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+function TabsList({
+ className,
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.List> &
+ VariantProps<typeof tabsListVariants>) {
+ return (
+ <TabsPrimitive.List
+ data-slot="tabs-list"
+ data-variant={variant}
+ className={cn(tabsListVariants({ variant }), className)}
+ {...props}
+ />
+ );
+}
+
+function TabsTrigger({
+ className,
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
+ return (
+ <TabsPrimitive.Trigger
+ data-slot="tabs-trigger"
+ className={cn(
+ "relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-none border border-transparent px-1.5 py-0.5 text-xs font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start group-data-vertical/tabs:py-[calc(--spacing(1.25))] hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ "group-data-[variant=line]/tabs-list:px-0 group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
+ "data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
+ "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TabsContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.Content>) {
+ return (
+ <TabsPrimitive.Content
+ data-slot="tabs-content"
+ className={cn("flex-1 text-xs/relaxed outline-none", className)}
+ {...props}
+ />
+ );
+}
+
+export { Tabs, TabsContent, TabsList, TabsTrigger, tabsListVariants };
diff --git a/packages/ui/src/components/textarea.tsx b/packages/ui/src/components/textarea.tsx
new file mode 100644
index 00000000..97c624e8
--- /dev/null
+++ b/packages/ui/src/components/textarea.tsx
@@ -0,0 +1,17 @@
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
+ return (
+ <textarea
+ data-slot="textarea"
+ className={cn(
+ "flex field-sizing-content min-h-16 w-full rounded-none border border-input bg-transparent px-2.5 py-2 text-xs transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 md:text-xs dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Textarea };
diff --git a/packages/ui/src/components/toggle-group.tsx b/packages/ui/src/components/toggle-group.tsx
new file mode 100644
index 00000000..6324a3ff
--- /dev/null
+++ b/packages/ui/src/components/toggle-group.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { toggleVariants } from "@crm/ui/components/toggle";
+import { cn } from "@crm/ui/lib/utils";
+import type { VariantProps } from "class-variance-authority";
+import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui";
+import * as React from "react";
+
+const ToggleGroupContext = React.createContext<
+ VariantProps<typeof toggleVariants> & {
+ spacing?: number;
+ orientation?: "horizontal" | "vertical";
+ }
+>({
+ size: "default",
+ variant: "default",
+ spacing: 2,
+ orientation: "horizontal",
+});
+
+function ToggleGroup({
+ className,
+ variant,
+ size,
+ spacing = 2,
+ orientation = "horizontal",
+ children,
+ ...props
+}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
+ VariantProps<typeof toggleVariants> & {
+ spacing?: number;
+ orientation?: "horizontal" | "vertical";
+ }) {
+ return (
+ <ToggleGroupPrimitive.Root
+ data-slot="toggle-group"
+ data-variant={variant}
+ data-size={size}
+ data-spacing={spacing}
+ data-orientation={orientation}
+ style={{ "--gap": spacing } as React.CSSProperties}
+ className={cn(
+ "group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-none data-[size=sm]:rounded-none data-vertical:flex-col data-vertical:items-stretch",
+ className,
+ )}
+ {...props}
+ >
+ <ToggleGroupContext.Provider
+ value={{ variant, size, spacing, orientation }}
+ >
+ {children}
+ </ToggleGroupContext.Provider>
+ </ToggleGroupPrimitive.Root>
+ );
+}
+
+function ToggleGroupItem({
+ className,
+ children,
+ variant = "default",
+ size = "default",
+ ...props
+}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
+ VariantProps<typeof toggleVariants>) {
+ const context = React.useContext(ToggleGroupContext);
+
+ return (
+ <ToggleGroupPrimitive.Item
+ data-slot="toggle-group-item"
+ data-variant={context.variant || variant}
+ data-size={context.size || size}
+ data-spacing={context.spacing}
+ className={cn(
+ "shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-none group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-none group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-none group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-none group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",
+ toggleVariants({
+ variant: context.variant || variant,
+ size: context.size || size,
+ }),
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </ToggleGroupPrimitive.Item>
+ );
+}
+
+export { ToggleGroup, ToggleGroupItem };
diff --git a/packages/ui/src/components/toggle.tsx b/packages/ui/src/components/toggle.tsx
new file mode 100644
index 00000000..5c024c5e
--- /dev/null
+++ b/packages/ui/src/components/toggle.tsx
@@ -0,0 +1,46 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { cva, type VariantProps } from "class-variance-authority";
+import { Toggle as TogglePrimitive } from "radix-ui";
+import type * as React from "react";
+
+const toggleVariants = cva(
+ "group/toggle inline-flex items-center justify-center gap-1 rounded-none text-xs font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ outline: "border border-input bg-transparent hover:bg-muted",
+ },
+ size: {
+ default:
+ "h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
+ sm: "h-7 min-w-7 rounded-none px-2.5 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5",
+ lg: "h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+function Toggle({
+ className,
+ variant = "default",
+ size = "default",
+ ...props
+}: React.ComponentProps<typeof TogglePrimitive.Root> &
+ VariantProps<typeof toggleVariants>) {
+ return (
+ <TogglePrimitive.Root
+ data-slot="toggle"
+ className={cn(toggleVariants({ variant, size, className }))}
+ {...props}
+ />
+ );
+}
+
+export { Toggle, toggleVariants };
diff --git a/packages/ui/src/components/tooltip.tsx b/packages/ui/src/components/tooltip.tsx
new file mode 100644
index 00000000..787b0341
--- /dev/null
+++ b/packages/ui/src/components/tooltip.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { Tooltip as TooltipPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function TooltipProvider({
+ delayDuration = 0,
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
+ return (
+ <TooltipPrimitive.Provider
+ data-slot="tooltip-provider"
+ delayDuration={delayDuration}
+ {...props}
+ />
+ );
+}
+
+function Tooltip({
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
+ return <TooltipPrimitive.Root data-slot="tooltip" {...props} />;
+}
+
+function TooltipTrigger({
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
+ return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
+}
+
+function TooltipContent({
+ className,
+ sideOffset = 0,
+ children,
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
+ return (
+ <TooltipPrimitive.Portal>
+ <TooltipPrimitive.Content
+ data-slot="tooltip-content"
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-none bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-none data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-none bg-foreground fill-foreground" />
+ </TooltipPrimitive.Content>
+ </TooltipPrimitive.Portal>
+ );
+}
+
+export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };
diff --git a/packages/ui/src/hooks/.gitkeep b/packages/ui/src/hooks/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/packages/ui/src/hooks/use-mobile.ts b/packages/ui/src/hooks/use-mobile.ts
new file mode 100644
index 00000000..0a892310
--- /dev/null
+++ b/packages/ui/src/hooks/use-mobile.ts
@@ -0,0 +1,21 @@
+import * as React from "react";
+
+const MOBILE_BREAKPOINT = 768;
+
+export function useIsMobile() {
+ const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
+ undefined,
+ );
+
+ React.useEffect(() => {
+ const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
+ const onChange = () => {
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ };
+ mql.addEventListener("change", onChange);
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ return () => mql.removeEventListener("change", onChange);
+ }, []);
+
+ return !!isMobile;
+}
diff --git a/packages/ui/src/hooks/use-mount-effect.ts b/packages/ui/src/hooks/use-mount-effect.ts
new file mode 100644
index 00000000..6ff23d17
--- /dev/null
+++ b/packages/ui/src/hooks/use-mount-effect.ts
@@ -0,0 +1,7 @@
+import * as React from "react";
+
+// biome-ignore lint/suspicious/noConfusingVoidType: matches React's own EffectCallback signature.
+export function useMountEffect(effect: () => void | (() => void)): void {
+ // biome-ignore lint/correctness/useExhaustiveDependencies: running exactly once on mount is the entire purpose of this hook.
+ React.useEffect(effect, []);
+}
diff --git a/packages/ui/src/lib/dither.ts b/packages/ui/src/lib/dither.ts
new file mode 100644
index 00000000..8fb7b9a6
--- /dev/null
+++ b/packages/ui/src/lib/dither.ts
@@ -0,0 +1,18 @@
+export type Bloom = "off" | "low" | "high" | "aura";
+
+const BLOOM_CLASS: Record<Bloom, string> = {
+ off: "",
+ low: "bloom-low",
+ high: "bloom-high",
+ aura: "bloom-aura",
+};
+
+export function bloomClass(bloom: Bloom = "off"): string {
+ return BLOOM_CLASS[bloom];
+}
+
+export const DITHER_CLASS = "dither";
+
+export function bloomColorForBgClass(bgClass: string): string {
+ return `var(--color-${bgClass.replace(/^bg-/, "")})`;
+}
diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.ts
new file mode 100644
index 00000000..ec82b929
--- /dev/null
+++ b/packages/ui/src/lib/format.ts
@@ -0,0 +1,75 @@
+/**
+ * Formatting shared by every module surface.
+ *
+ * `formatCount` existed three times over — identically — in
+ * `code-security/cs-ui`, `cloud-security/cloud-ui` and `people/people-ui`.
+ *
+ * `relativeTimeFromIso` was defined in `code-security/cs-ui` and imported
+ * across module boundaries by People. It is deliberately NOT merged with the
+ * epoch-milliseconds `relativeTime` in `apps/app/lib/format-date`: they take
+ * different inputs and disagree on the empty case ("—" vs "Never"), so folding
+ * them together would silently change copy in one module or the other. Both
+ * names are kept so the difference is visible at the call site.
+ *
+ * `formatMoney` moved here from `components/admin/admin-ui`, which is now needed
+ * by the People upgrade surfaces too. It is deliberately NOT merged with the
+ * billing page's local `formatMoney`: that one always renders two decimals
+ * (invoice amounts), this one drops them for whole dollars. Folding them
+ * together would silently change billing copy.
+ */
+
+export function formatCount(count: number, noun: string): string {
+ return `${count} ${count === 1 ? noun : `${noun}s`}`;
+}
+
+const WELL_FORMED_CURRENCY_CODE = /^[A-Za-z]{3}$/;
+
+export function displayCurrencyCode(currency: string): string {
+ return WELL_FORMED_CURRENCY_CODE.test(currency)
+ ? currency.toUpperCase()
+ : "USD";
+}
+
+export function formatMoney(cents: number, currency = "usd"): string {
+ return new Intl.NumberFormat(undefined, {
+ style: "currency",
+ currency: displayCurrencyCode(currency),
+ minimumFractionDigits: cents % 100 === 0 ? 0 : 2,
+ }).format(cents / 100);
+}
+
+export function relativeTimeFromIso(iso: string | null | undefined): string {
+ if (!iso) return "—";
+ const then = new Date(iso).getTime();
+ if (!Number.isFinite(then)) return "—";
+ const diff = Date.now() - then;
+ const abs = Math.abs(diff);
+ const min = 60_000;
+ const hour = 60 * min;
+ const day = 24 * hour;
+ if (abs < min) return "just now";
+ const distance =
+ abs < hour
+ ? `${Math.round(abs / min)}m`
+ : abs < day
+ ? `${Math.round(abs / hour)}h`
+ : abs < 30 * day
+ ? `${Math.round(abs / day)}d`
+ : null;
+ if (distance === null) {
+ return new Date(iso).toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ });
+ }
+ return diff < 0 ? `in ${distance}` : `${distance} ago`;
+}
+
+export function initialsFromName(name: string | null | undefined): string {
+ const parts = (name ?? "").split(/\s+/).filter(Boolean);
+ const first = parts[0];
+ if (!first) return "?";
+ if (parts.length === 1) return first.slice(0, 2).toUpperCase();
+ const last = parts[parts.length - 1] ?? first;
+ return (first.slice(0, 1) + last.slice(0, 1)).toUpperCase();
+}
diff --git a/packages/ui/src/lib/row-accent.ts b/packages/ui/src/lib/row-accent.ts
new file mode 100644
index 00000000..ed70bcde
--- /dev/null
+++ b/packages/ui/src/lib/row-accent.ts
@@ -0,0 +1,28 @@
+// NOTE: every class below must be written out as a literal string. Tailwind's
+// scanner only generates CSS for class names it finds verbatim in source — it
+// cannot see dynamically built/interpolated ones, so no template helpers here.
+
+const BAR = [
+ "[&>td:first-child]:relative",
+ "[&>td:first-child]:before:pointer-events-none [&>td:first-child]:before:absolute",
+ "[&>td:first-child]:before:inset-y-0 [&>td:first-child]:before:left-0 [&>td:first-child]:before:w-0.5",
+ "[&>td:first-child]:before:bg-foreground [&>td:first-child]:before:opacity-0",
+ "[&:hover>td:first-child]:before:opacity-100",
+].join(" ");
+
+// Content-first rows: slide the first cell's text right on hover.
+export const ROW_ACCENT = [
+ "cursor-pointer",
+ BAR,
+ "[&>td:first-child]:transition-[padding] [&>td:first-child]:duration-200 [&>td:first-child]:ease-out",
+ "[&:hover>td:first-child]:pl-5",
+].join(" ");
+
+// Rows with a leading icon/expand column (a chevron isn't "the text"): keep the
+// bar on the first cell but slide the second cell — the first real content.
+export const ROW_ACCENT_EXPANDABLE = [
+ "cursor-pointer",
+ BAR,
+ "[&>td:nth-child(2)]:transition-[padding] [&>td:nth-child(2)]:duration-200 [&>td:nth-child(2)]:ease-out",
+ "[&:hover>td:nth-child(2)]:pl-5",
+].join(" ");
diff --git a/packages/ui/src/lib/table-query.ts b/packages/ui/src/lib/table-query.ts
new file mode 100644
index 00000000..645c80d0
--- /dev/null
+++ b/packages/ui/src/lib/table-query.ts
@@ -0,0 +1,29 @@
+export type SortDirection = "asc" | "desc";
+
+/**
+ * The contract between a list page's URL state and `DataTable`.
+ *
+ * The table renders the controls and reads the current values; it never owns
+ * them. The implementation lives in the app (`useTableQuery`) because routing
+ * is not the design system's business — but the shape belongs next to the
+ * component that consumes it, so the two cannot drift.
+ */
+export type TableQueryState = {
+ q: string;
+ sort: string;
+ dir: SortDirection;
+ page: number;
+ pageSize: number;
+ /** `"all"` when no tab is selected. */
+ tab: string;
+ tabId?: string;
+ /** Facet id → selected value, `"all"` when unfiltered. */
+ filters: Record<string, string>;
+ setSearch: (value: string) => void;
+ toggleSort: (id: string) => void;
+ setSort: (id: string) => void;
+ setDir: (dir: SortDirection) => void;
+ setPage: (page: number) => void;
+ setTab: (value: string) => void;
+ setFilter: (id: string, value: string) => void;
+};
diff --git a/packages/ui/src/lib/utils.ts b/packages/ui/src/lib/utils.ts
new file mode 100644
index 00000000..ac680b30
--- /dev/null
+++ b/packages/ui/src/lib/utils.ts
@@ -0,0 +1,6 @@
+import { type ClassValue, clsx } from "clsx";
+import { twMerge } from "tailwind-merge";
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs));
+}
diff --git a/packages/ui/src/styles/globals.css b/packages/ui/src/styles/globals.css
new file mode 100644
index 00000000..29a7a232
--- /dev/null
+++ b/packages/ui/src/styles/globals.css
@@ -0,0 +1,908 @@
+@import "tailwindcss";
+@import "tw-animate-css";
+@import "shadcn/tailwind.css";
+
+/*
+ * Scan this package's own source so Tailwind generates classes used by the
+ * shared components. The path resolves the same whether this file is read in
+ * place (packages/ui/src/styles) or through the workspace symlink
+ * (node_modules/@crm/ui/src/styles). Consuming apps scan their own files
+ * via Tailwind's automatic content detection.
+ */
+@source "../../**/*.{ts,tsx}";
+
+@custom-variant dark (&:is(.dark *));
+
+:root {
+ --background: oklch(1 0 0);
+ --foreground: oklch(0.145 0 0);
+ --card: oklch(1 0 0);
+ --card-foreground: oklch(0.145 0 0);
+ --popover: oklch(1 0 0);
+ --popover-foreground: oklch(0.145 0 0);
+ --primary: oklch(0.205 0 0);
+ --primary-foreground: oklch(0.985 0 0);
+ --secondary: oklch(0.97 0 0);
+ --secondary-foreground: oklch(0.205 0 0);
+ --muted: oklch(0.97 0 0);
+ --muted-foreground: oklch(0.556 0 0);
+ --accent: oklch(0.97 0 0);
+ --accent-foreground: oklch(0.205 0 0);
+ --destructive: oklch(0.577 0.245 27.325);
+ --destructive-foreground: #ffffff;
+ --success: oklch(0.55 0.13 150);
+ --success-foreground: #ffffff;
+ --warning: oklch(0.62 0.14 65);
+ --warning-foreground: #ffffff;
+ --info: oklch(0.55 0.16 255);
+ --info-foreground: #ffffff;
+ --border: oklch(0.922 0 0);
+ --input: oklch(0.922 0 0);
+ --ring: oklch(0.708 0 0);
+ --chart-1: oklch(0.879 0.169 91.605);
+ --chart-2: oklch(0.769 0.188 70.08);
+ --chart-3: oklch(0.666 0.179 58.318);
+ --chart-4: oklch(0.555 0.163 48.998);
+ --chart-5: oklch(0.473 0.137 46.201);
+ --severity-critical: var(--destructive);
+ --severity-high: oklch(0.646 0.222 41.116);
+ --severity-medium: oklch(0.681 0.162 75.834);
+ --severity-low: var(--muted-foreground);
+ --severity-info: oklch(0.71 0.01 286);
+ --severity-unknown: oklch(0.75 0 0);
+ --sidebar: oklch(0.985 0 0);
+ --sidebar-foreground: oklch(0.145 0 0);
+ --sidebar-primary: oklch(0.205 0 0);
+ --sidebar-primary-foreground: oklch(0.985 0 0);
+ --sidebar-accent: oklch(0.97 0 0);
+ --sidebar-accent-foreground: oklch(0.205 0 0);
+ --sidebar-border: oklch(0.922 0 0);
+ --sidebar-ring: oklch(0.708 0 0);
+ --font-sans: var(--font-geist-sans, "Geist", sans-serif);
+ --font-mono: var(--font-geist-mono, "Geist Mono", monospace);
+ --radius: 0.625rem;
+ --shadow-x: 0px;
+ --shadow-y: 1px;
+ --shadow-blur: 2px;
+ --shadow-spread: 0px;
+ --shadow-opacity: 0.08;
+ --shadow-color: hsl(0 0% 0%);
+ --shadow-2xs: 0px 1px 2px 0px hsl(0 0% 0% / 0.04);
+ --shadow-xs: 0px 1px 2px 0px hsl(0 0% 0% / 0.04);
+ --shadow-sm: 0px 1px 2px 0px hsl(0 0% 0% / 0.06);
+ --shadow: 0px 1px 2px 0px hsl(0 0% 0% / 0.06);
+ --shadow-md: 0px 2px 4px -1px hsl(0 0% 0% / 0.08);
+ --shadow-lg: 0px 4px 8px -2px hsl(0 0% 0% / 0.08);
+ --shadow-xl: 0px 8px 16px -4px hsl(0 0% 0% / 0.08);
+ --shadow-2xl: 0px 16px 32px -8px hsl(0 0% 0% / 0.12);
+ --tracking-normal: 0em;
+ --spacing: 0.25rem;
+}
+
+.dark {
+ --background: oklch(0.145 0 0);
+ --foreground: oklch(0.985 0 0);
+ --card: oklch(0.205 0 0);
+ --card-foreground: oklch(0.985 0 0);
+ --popover: oklch(0.205 0 0);
+ --popover-foreground: oklch(0.985 0 0);
+ --primary: oklch(0.922 0 0);
+ --primary-foreground: oklch(0.205 0 0);
+ --secondary: oklch(0.269 0 0);
+ --secondary-foreground: oklch(0.985 0 0);
+ --muted: oklch(0.269 0 0);
+ --muted-foreground: oklch(0.708 0 0);
+ --accent: oklch(0.269 0 0);
+ --accent-foreground: oklch(0.985 0 0);
+ --destructive: oklch(0.704 0.191 22.216);
+ --destructive-foreground: #ffffff;
+ --success: oklch(0.72 0.16 155);
+ --success-foreground: oklch(0.205 0 0);
+ --warning: oklch(0.8 0.15 75);
+ --warning-foreground: oklch(0.205 0 0);
+ --info: oklch(0.7 0.15 250);
+ --info-foreground: oklch(0.205 0 0);
+ --border: oklch(1 0 0 / 10%);
+ --input: oklch(1 0 0 / 15%);
+ --ring: oklch(0.556 0 0);
+ --chart-1: oklch(0.879 0.169 91.605);
+ --chart-2: oklch(0.769 0.188 70.08);
+ --chart-3: oklch(0.666 0.179 58.318);
+ --chart-4: oklch(0.555 0.163 48.998);
+ --chart-5: oklch(0.473 0.137 46.201);
+ --severity-critical: oklch(0.637 0.237 25.331);
+ --severity-high: oklch(0.705 0.213 47.604);
+ --severity-medium: var(--chart-2);
+ --severity-low: var(--muted-foreground);
+ --severity-info: oklch(0.71 0.01 286);
+ --severity-unknown: oklch(0.5 0 0);
+ --sidebar: oklch(0.205 0 0);
+ --sidebar-foreground: oklch(0.985 0 0);
+ --sidebar-primary: oklch(0.922 0 0);
+ --sidebar-primary-foreground: oklch(0.205 0 0);
+ --sidebar-accent: oklch(0.269 0 0);
+ --sidebar-accent-foreground: oklch(0.985 0 0);
+ --sidebar-border: oklch(1 0 0 / 10%);
+ --sidebar-ring: oklch(0.556 0 0);
+ --font-sans: var(--font-geist-sans, "Geist", sans-serif);
+ --font-mono: var(--font-geist-mono, "Geist Mono", monospace);
+ --radius: 0.75rem;
+ --shadow-x: 0px;
+ --shadow-y: 1px;
+ --shadow-blur: 2px;
+ --shadow-spread: 0px;
+ --shadow-opacity: 0.08;
+ --shadow-color: hsl(0 0% 0%);
+ --shadow-2xs: 0px 1px 2px 0px hsl(0 0% 0% / 0.04);
+ --shadow-xs: 0px 1px 2px 0px hsl(0 0% 0% / 0.04);
+ --shadow-sm: 0px 1px 2px 0px hsl(0 0% 0% / 0.06);
+ --shadow: 0px 1px 2px 0px hsl(0 0% 0% / 0.06);
+ --shadow-md: 0px 2px 4px -1px hsl(0 0% 0% / 0.08);
+ --shadow-lg: 0px 4px 8px -2px hsl(0 0% 0% / 0.08);
+ --shadow-xl: 0px 8px 16px -4px hsl(0 0% 0% / 0.08);
+ --shadow-2xl: 0px 16px 32px -8px hsl(0 0% 0% / 0.12);
+}
+
+@theme inline {
+ --color-background: var(--background);
+ --color-foreground: var(--foreground);
+ --color-card: var(--card);
+ --color-card-foreground: var(--card-foreground);
+ --color-popover: var(--popover);
+ --color-popover-foreground: var(--popover-foreground);
+ --color-primary: var(--primary);
+ --color-primary-foreground: var(--primary-foreground);
+ --color-secondary: var(--secondary);
+ --color-secondary-foreground: var(--secondary-foreground);
+ --color-muted: var(--muted);
+ --color-muted-foreground: var(--muted-foreground);
+ --color-accent: var(--accent);
+ --color-accent-foreground: var(--accent-foreground);
+ --color-destructive: var(--destructive);
+ --color-destructive-foreground: var(--destructive-foreground);
+ --color-success: var(--success);
+ --color-success-foreground: var(--success-foreground);
+ --color-warning: var(--warning);
+ --color-warning-foreground: var(--warning-foreground);
+ --color-info: var(--info);
+ --color-info-foreground: var(--info-foreground);
+ --color-border: var(--border);
+ --color-input: var(--input);
+ --color-ring: var(--ring);
+ --color-chart-1: var(--chart-1);
+ --color-chart-2: var(--chart-2);
+ --color-chart-3: var(--chart-3);
+ --color-chart-4: var(--chart-4);
+ --color-chart-5: var(--chart-5);
+ --color-severity-critical: var(--severity-critical);
+ --color-severity-high: var(--severity-high);
+ --color-severity-medium: var(--severity-medium);
+ --color-severity-low: var(--severity-low);
+ --color-severity-info: var(--severity-info);
+ --color-severity-unknown: var(--severity-unknown);
+ --color-sidebar: var(--sidebar);
+ --color-sidebar-foreground: var(--sidebar-foreground);
+ --color-sidebar-primary: var(--sidebar-primary);
+ --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
+ --color-sidebar-accent: var(--sidebar-accent);
+ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
+ --color-sidebar-border: var(--sidebar-border);
+ --color-sidebar-ring: var(--sidebar-ring);
+
+ --font-sans: var(--font-sans);
+ --font-mono: var(--font-mono);
+ --radius-sm: 6px;
+ --radius-md: 8px;
+ --radius-lg: var(--radius);
+ --radius-xl: 16px;
+
+ --shadow-2xs: var(--shadow-2xs);
+ --shadow-xs: var(--shadow-xs);
+ --shadow-sm: var(--shadow-sm);
+ --shadow: var(--shadow);
+ --shadow-md: var(--shadow-md);
+ --shadow-lg: var(--shadow-lg);
+ --shadow-xl: var(--shadow-xl);
+ --shadow-2xl: var(--shadow-2xl);
+ --font-heading: var(--font-sans);
+ --radius-2xl: calc(var(--radius) * 1.8);
+ --radius-3xl: calc(var(--radius) * 2.2);
+ --radius-4xl: calc(var(--radius) * 2.6);
+}
+
+@layer base {
+ * {
+ @apply border-border outline-ring/50;
+ }
+ body {
+ @apply bg-background text-foreground font-sans;
+ }
+
+ /*
+ * Modern, theme-aware scrollbars. Thin, transparent track, with a thumb
+ * drawn from the design tokens so it follows light/dark automatically.
+ * Firefox uses the standard properties; WebKit/Chromium uses the
+ * ::-webkit-scrollbar pseudo-elements. `.no-scrollbar` still wins because
+ * it sets `display: none` on the pseudo-element.
+ */
+ * {
+ scrollbar-width: thin;
+ scrollbar-color: var(--border) transparent;
+ }
+ *::-webkit-scrollbar {
+ width: 10px;
+ height: 10px;
+ }
+ *::-webkit-scrollbar-track {
+ background: transparent;
+ }
+ *::-webkit-scrollbar-thumb {
+ background-color: var(--border);
+ border: 2px solid transparent;
+ border-radius: 9999px;
+ background-clip: padding-box;
+ }
+ *::-webkit-scrollbar-thumb:hover {
+ background-color: var(--muted-foreground);
+ }
+ *::-webkit-scrollbar-corner {
+ background: transparent;
+ }
+}
+
+/*
+ * Dither + bloom — the chart aesthetic (see dashboard-chart.tsx), ported to
+ * plain HTML surfaces (status/severity indicators, meters, progress bars).
+ *
+ * `.dither` overlays an ordered two-tone dot texture (a light dot + an offset
+ * dark dot per 4px tile, matching the chart's SVG <pattern>) on top of any
+ * filled element, adapting to the fill beneath it. `.bloom-*` adds a soft
+ * colored halo via box-shadow; set `--bloom-color` on the element (defaults to
+ * currentColor). Both are theme-independent.
+ */
+:root {
+ --dither-pattern: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='4' height='4'%3E%3Crect width='1.4' height='1.4' fill='%23ffffff' fill-opacity='.55'/%3E%3Crect x='2' y='2' width='1.4' height='1.4' fill='%23000000' fill-opacity='.5'/%3E%3C/svg%3E");
+}
+
+@layer utilities {
+ .dither {
+ position: relative;
+ }
+ .dither::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ background-image: var(--dither-pattern);
+ background-size: var(--dither-size, 4px) var(--dither-size, 4px);
+ background-repeat: repeat;
+ }
+
+ .bloom-low {
+ box-shadow: 0 0 4px var(--bloom-color, currentColor);
+ }
+ .bloom-high {
+ box-shadow: 0 0 7px var(--bloom-color, currentColor);
+ }
+ .bloom-aura {
+ box-shadow:
+ 0 0 4px var(--bloom-color, currentColor),
+ 0 0 10px var(--bloom-color, currentColor);
+ }
+}
+
+/*
+ * Icon motion — expressive, per-icon hover animation for our Carbon glyphs
+ * (see components/icon.tsx). The transform lands on the <svg> itself, so the
+ * actual icon geometry moves rather than a wrapping box. A glyph animates when
+ * hovered directly or when its nearest interactive ancestor (button, link, menu
+ * item) or an opt-in `.icon-hover` container is hovered. Settle motions read
+ * from `--cds-hover`; looping/keyframe motions override it while hovered. All of
+ * it is gated behind `prefers-reduced-motion` so it disappears for users who ask
+ * for less movement.
+ */
+@layer utilities {
+ .cds-icon {
+ transform-origin: center;
+ }
+
+ @media (prefers-reduced-motion: no-preference) {
+ .cds-icon {
+ transition: transform 240ms cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+
+ .cds-icon[data-motion="pop"] {
+ --cds-hover: scale(1.14);
+ }
+ .cds-icon[data-motion="scale"] {
+ --cds-hover: scale(1.1);
+ }
+ .cds-icon[data-motion="lift"] {
+ --cds-hover: translateY(-2px) scale(1.06);
+ }
+ .cds-icon[data-motion="turn"] {
+ --cds-hover: rotate(90deg);
+ }
+ .cds-icon[data-motion="rotate"] {
+ --cds-hover: rotate(-12deg);
+ }
+ .cds-icon[data-motion="flip"] {
+ --cds-hover: rotateY(180deg);
+ }
+ .cds-icon[data-motion="nudge-right"] {
+ --cds-hover: translateX(3px);
+ }
+ .cds-icon[data-motion="nudge-left"] {
+ --cds-hover: translateX(-3px);
+ }
+ .cds-icon[data-motion="nudge-up"] {
+ --cds-hover: translateY(-3px);
+ }
+ .cds-icon[data-motion="nudge-down"] {
+ --cds-hover: translateY(3px);
+ }
+ .cds-icon[data-motion="launch"] {
+ --cds-hover: translate(2px, -2px);
+ }
+
+ :where(
+ .cds-icon:hover,
+ :where(
+ button,
+ a,
+ [role="button"],
+ [role="menuitem"],
+ [data-slot="dropdown-menu-item"],
+ [data-slot="command-item"],
+ [data-slot="sidebar-menu-button"],
+ .icon-hover
+ ):hover
+ .cds-icon
+ ) {
+ transform: var(--cds-hover, none);
+
+ &[data-motion="spin"] {
+ animation: cds-spin 1.1s linear infinite;
+ }
+ &[data-motion="wiggle"] {
+ animation: cds-wiggle 0.5s ease-in-out;
+ }
+ &[data-motion="swing"] {
+ animation: cds-swing 0.6s ease-in-out;
+ transform-origin: top center;
+ }
+ &[data-motion="bounce"] {
+ animation: cds-bounce 0.6s ease;
+ }
+ &[data-motion="pulse"] {
+ animation: cds-pulse 0.9s ease-in-out infinite;
+ }
+ }
+ }
+}
+
+@keyframes cds-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+@keyframes cds-wiggle {
+ 0%,
+ 100% {
+ transform: rotate(0);
+ }
+ 20% {
+ transform: rotate(-9deg);
+ }
+ 40% {
+ transform: rotate(7deg);
+ }
+ 60% {
+ transform: rotate(-5deg);
+ }
+ 80% {
+ transform: rotate(3deg);
+ }
+}
+@keyframes cds-swing {
+ 0%,
+ 100% {
+ transform: rotate(0);
+ }
+ 25% {
+ transform: rotate(12deg);
+ }
+ 50% {
+ transform: rotate(-8deg);
+ }
+ 75% {
+ transform: rotate(4deg);
+ }
+}
+@keyframes cds-bounce {
+ 0%,
+ 100% {
+ transform: translateY(0);
+ }
+ 30% {
+ transform: translateY(-3px);
+ }
+ 55% {
+ transform: translateY(1px);
+ }
+ 75% {
+ transform: translateY(-1px);
+ }
+}
+@keyframes cds-pulse {
+ 0%,
+ 100% {
+ transform: scale(1);
+ }
+ 50% {
+ transform: scale(1.12);
+ }
+}
+
+/*
+ * View transitions. Opt-in: the old snapshot is always hidden (so nothing
+ * ghosts or doubles), and the new view appears instantly unless a transition
+ * type opts into motion. Persistent chrome (header, icon rail) and the page
+ * background never move. Hierarchical navigation (list -> detail) slides
+ * forward/back; lateral navigation (rail menus) fades the new content in.
+ */
+:root {
+ --duration-exit: 150ms;
+ --duration-enter: 210ms;
+ --duration-move: 400ms;
+}
+
+@keyframes vt-fade {
+ from {
+ filter: blur(3px);
+ opacity: 0;
+ }
+ to {
+ filter: blur(0);
+ opacity: 1;
+ }
+}
+
+@keyframes vt-slide {
+ from {
+ translate: var(--slide-offset);
+ }
+ to {
+ translate: 0;
+ }
+}
+
+@keyframes vt-rise {
+ from {
+ transform: translateY(12px);
+ }
+ to {
+ transform: translateY(0);
+ }
+}
+
+::view-transition-group(*),
+::view-transition-new(*) {
+ animation: none;
+}
+
+::view-transition-old(*) {
+ animation: none;
+ opacity: 0;
+}
+
+::view-transition-group(app-header),
+::view-transition-group(app-rail) {
+ z-index: 100;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ ::view-transition-new(.nav-lateral) {
+ animation:
+ var(--duration-enter) ease-out both vt-fade,
+ var(--duration-enter) ease-out both vt-rise;
+ }
+
+ ::view-transition-old(.nav-forward) {
+ --slide-offset: -60px;
+ animation:
+ var(--duration-exit) ease-in both vt-fade reverse,
+ var(--duration-move) ease-in-out both vt-slide reverse;
+ }
+ ::view-transition-new(.nav-forward) {
+ --slide-offset: 60px;
+ animation:
+ var(--duration-enter) ease-out var(--duration-exit) both vt-fade,
+ var(--duration-move) ease-in-out both vt-slide;
+ }
+
+ ::view-transition-old(.nav-back) {
+ --slide-offset: 60px;
+ animation:
+ var(--duration-exit) ease-in both vt-fade reverse,
+ var(--duration-move) ease-in-out both vt-slide reverse;
+ }
+ ::view-transition-new(.nav-back) {
+ --slide-offset: -60px;
+ animation:
+ var(--duration-enter) ease-out var(--duration-exit) both vt-fade,
+ var(--duration-move) ease-in-out both vt-slide;
+ }
+}
+
+/*
+ * Underline-on-hover links. Used by <LineHoverLink>, which picks a variant via
+ * the `link-hover--*` modifier; the base class carries the shared geometry.
+ */
+.link-hover {
+ cursor: pointer;
+ position: relative;
+ display: inline-flex;
+ width: fit-content;
+ white-space: nowrap;
+ color: currentColor;
+ text-decoration: none;
+ outline: none;
+}
+
+.link-hover::before,
+.link-hover::after {
+ position: absolute;
+ left: 0;
+ top: 100%;
+ width: 100%;
+ height: 1px;
+ background: currentColor;
+ pointer-events: none;
+}
+
+.link-hover::before {
+ content: "";
+}
+
+.link-hover:focus-visible {
+ border-radius: 0;
+ outline: 2px solid color-mix(in srgb, currentColor 45%, transparent);
+ outline-offset: 0.25rem;
+}
+
+.link-hover--slide::before {
+ transform: scale3d(0, 1, 1);
+ transform-origin: 100% 50%;
+ transition: transform 0.3s ease;
+}
+
+.link-hover--slide:hover::before,
+.link-hover--slide:focus-visible::before {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 0% 50%;
+}
+
+.link-hover--double::before {
+ transform: scale3d(0, 1, 1);
+ transform-origin: 100% 50%;
+ transition: transform 0.3s cubic-bezier(0.7, 0, 0.2, 1);
+}
+
+.link-hover--double:hover::before,
+.link-hover--double:focus-visible::before {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 0% 50%;
+ transition-timing-function: cubic-bezier(0.4, 1, 0.8, 1);
+}
+
+.link-hover--double::after {
+ content: "";
+ top: calc(100% + 4px);
+ transform: scale3d(0, 1, 1);
+ transform-origin: 0% 50%;
+ transition: transform 0.3s cubic-bezier(0.7, 0, 0.2, 1);
+}
+
+.link-hover--double:hover::after,
+.link-hover--double:focus-visible::after {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 100% 50%;
+ transition-timing-function: cubic-bezier(0.4, 1, 0.8, 1);
+}
+
+.link-hover--grow::before {
+ transform: scale3d(0, 1, 1);
+ transform-origin: 100% 50%;
+ transition: transform 0.3s cubic-bezier(0.2, 1, 0.8, 1);
+}
+
+.link-hover--grow:hover::before,
+.link-hover--grow:focus-visible::before {
+ transform: scale3d(1, 2, 1);
+ transform-origin: 0% 50%;
+ transition-timing-function: cubic-bezier(0.7, 0, 0.2, 1);
+}
+
+.link-hover--grow::after {
+ content: "";
+ top: calc(100% + 4px);
+ transform: scale3d(0, 1, 1);
+ transform-origin: 100% 50%;
+ transition: transform 0.4s 0.1s cubic-bezier(0.2, 1, 0.8, 1);
+}
+
+.link-hover--grow:hover::after,
+.link-hover--grow:focus-visible::after {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 0% 50%;
+}
+
+.link-hover--strike {
+ padding-inline: 0.625rem;
+}
+
+.link-hover--strike::before {
+ top: 50%;
+ height: 2px;
+ transform: scale3d(0, 1, 1);
+ transform-origin: 100% 50%;
+ transition: transform 0.3s cubic-bezier(0.4, 1, 0.8, 1);
+}
+
+.link-hover--strike:hover::before,
+.link-hover--strike:focus-visible::before {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 0% 50%;
+}
+
+.link-hover--strike span {
+ display: inline-block;
+ transition: transform 0.3s cubic-bezier(0.4, 1, 0.8, 1);
+}
+
+.link-hover--strike:hover span,
+.link-hover--strike:focus-visible span {
+ transform: scale3d(1.08, 1.08, 1);
+}
+
+.link-hover--fade::before,
+.link-hover--fade::after {
+ opacity: 0;
+ transform: translate3d(0, 3px, 0);
+ transform-origin: 50% 0%;
+ transition:
+ transform 0.3s cubic-bezier(0.2, 1, 0.8, 1),
+ opacity 0.3s cubic-bezier(0.2, 1, 0.8, 1);
+}
+
+.link-hover--fade::after {
+ content: "";
+ left: 15%;
+ top: calc(100% + 4px);
+ width: 70%;
+}
+
+.link-hover--fade:hover::before,
+.link-hover--fade:hover::after,
+.link-hover--fade:focus-visible::before,
+.link-hover--fade:focus-visible::after {
+ opacity: 1;
+ transform: translate3d(0, 0, 0);
+}
+
+.link-hover--fade::before,
+.link-hover--fade:hover::after,
+.link-hover--fade:focus-visible::after {
+ transition-delay: 0.1s;
+}
+
+.link-hover--pulse::before {
+ top: 100%;
+ height: 10px;
+ opacity: 0;
+}
+
+.link-hover--pulse:hover::before,
+.link-hover--pulse:focus-visible::before {
+ opacity: 1;
+ animation: line-hover-line-up 0.3s ease forwards;
+}
+
+.link-hover--pulse::after {
+ content: "";
+ opacity: 0;
+ transition: opacity 0.3s;
+}
+
+.link-hover--pulse:hover::after,
+.link-hover--pulse:focus-visible::after {
+ opacity: 1;
+ transition-delay: 0.3s;
+}
+
+.link-hover--swap::before {
+ transform: scale3d(0, 1, 1);
+ transform-origin: 0% 50%;
+ transition: transform 0.3s ease;
+}
+
+.link-hover--swap:hover::before,
+.link-hover--swap:focus-visible::before {
+ transform: scale3d(1, 1, 1);
+}
+
+.link-hover--swap::after {
+ content: "";
+ top: calc(100% + 4px);
+ transform-origin: 100% 50%;
+ transition: transform 0.3s ease;
+}
+
+.link-hover--swap:hover::after,
+.link-hover--swap:focus-visible::after {
+ transform: scale3d(0, 1, 1);
+}
+
+.link-hover--sweep {
+ padding-inline: 0.25rem;
+}
+
+.link-hover--sweep::before {
+ top: 0;
+ height: 100%;
+ background: color-mix(in srgb, currentColor 12%, transparent);
+ opacity: 0;
+}
+
+.link-hover--sweep:hover::before,
+.link-hover--sweep:focus-visible::before {
+ opacity: 1;
+ animation: line-hover-cover-up 0.3s ease forwards;
+}
+
+.link-hover--sweep::after {
+ content: "";
+ transition: opacity 0.3s ease;
+}
+
+.link-hover--sweep:hover::after,
+.link-hover--sweep:focus-visible::after {
+ opacity: 0;
+}
+
+.link-hover--bounce::before {
+ height: 7px;
+ border-radius: 999px;
+ transform: scale3d(1, 1, 1);
+ transition:
+ transform 0.2s,
+ opacity 0.2s;
+ transition-timing-function: cubic-bezier(0.2, 0.57, 0.67, 1.53);
+}
+
+.link-hover--bounce:hover::before,
+.link-hover--bounce:focus-visible::before {
+ opacity: 1;
+ transform: scale3d(1.18, 0.1, 1);
+ transition-duration: 0.4s;
+ transition-timing-function: cubic-bezier(0.8, 0, 0.1, 1);
+}
+
+.link-hover--bounce span {
+ display: inline-block;
+ transform: translate3d(0, -4px, 0);
+ transition: transform 0.2s 0.05s cubic-bezier(0.2, 0.57, 0.67, 1.53);
+}
+
+.link-hover--bounce:hover span,
+.link-hover--bounce:focus-visible span {
+ transform: translate3d(0, 0, 0);
+ transition-delay: 0s;
+ transition-duration: 0.4s;
+ transition-timing-function: cubic-bezier(0.8, 0, 0.1, 1);
+}
+
+.link-hover__graphic {
+ position: absolute;
+ left: 0;
+ top: 0;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1px;
+ pointer-events: none;
+}
+
+.link-hover__graphic--stroke path {
+ stroke-dasharray: 1;
+ stroke-dashoffset: 1;
+}
+
+.link-hover:hover .link-hover__graphic--stroke path,
+.link-hover:focus-visible .link-hover__graphic--stroke path {
+ stroke-dashoffset: 0;
+}
+
+.link-hover--arc::before,
+.link-hover--scribble::before {
+ display: none;
+}
+
+.link-hover__graphic--arc {
+ left: -23%;
+ top: 73%;
+}
+
+.link-hover__graphic--arc path {
+ transition: stroke-dashoffset 0.4s cubic-bezier(0.7, 0, 0.3, 1);
+}
+
+.link-hover:hover .link-hover__graphic--arc path,
+.link-hover:focus-visible .link-hover__graphic--arc path {
+ transition-duration: 0.3s;
+ transition-timing-function: cubic-bezier(0.8, 1, 0.7, 1);
+}
+
+.link-hover__graphic--scribble {
+ top: 100%;
+}
+
+.link-hover__graphic--scribble path {
+ transition: stroke-dashoffset 0.6s cubic-bezier(0.7, 0, 0.3, 1);
+}
+
+.link-hover:hover .link-hover__graphic--scribble path,
+.link-hover:focus-visible .link-hover__graphic--scribble path {
+ transition-duration: 0.3s;
+ transition-timing-function: cubic-bezier(0.8, 1, 0.7, 1);
+}
+
+@keyframes line-hover-line-up {
+ 0% {
+ transform: scale3d(1, 0.045, 1);
+ transform-origin: 50% 100%;
+ }
+ 50% {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 50% 100%;
+ }
+ 51% {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 50% 0%;
+ }
+ 100% {
+ transform: scale3d(1, 0.045, 1);
+ transform-origin: 50% 0%;
+ }
+}
+
+@keyframes line-hover-cover-up {
+ 0% {
+ transform: scale3d(1, 0.045, 1);
+ transform-origin: 50% 100%;
+ }
+ 50% {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 50% 100%;
+ }
+ 51% {
+ transform: scale3d(1, 1, 1);
+ transform-origin: 50% 0%;
+ }
+ 100% {
+ transform: scale3d(1, 0.045, 1);
+ transform-origin: 50% 0%;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .link-hover,
+ .link-hover *,
+ .link-hover::before,
+ .link-hover::after {
+ /* biome-ignore lint/complexity/noImportantStyles: reduced-motion reset must override animation declarations */
+ animation: none !important;
+ /* biome-ignore lint/complexity/noImportantStyles: reduced-motion reset must override transition declarations */
+ transition-duration: 0.01ms !important;
+ }
+}
diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json
index ed023ce4..b0cd750a 100644
--- a/packages/ui/tsconfig.json
+++ b/packages/ui/tsconfig.json
@@ -1,9 +1,6 @@
{
- "extends": "@repo/typescript-config/react-library.json",
- "compilerOptions": {
- "outDir": "dist",
- "strictNullChecks": true
- },
- "include": ["src"],
- "exclude": ["node_modules", "dist"]
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "@crm/typescript-config/react-library.json",
+ "include": ["src"],
+ "exclude": ["node_modules"]
}
diff --git a/skills-lock.json b/skills-lock.json
new file mode 100644
index 00000000..a9c4d196
--- /dev/null
+++ b/skills-lock.json
@@ -0,0 +1,83 @@
+{
+ "version": 1,
+ "skills": {
+ "better-auth-best-practices": {
+ "source": "better-auth/skills",
+ "sourceType": "github",
+ "skillPath": "better-auth/best-practices/SKILL.md",
+ "computedHash": "61ba0ef64ed2e7c424401cc848ca33dd6d790a720c44727717dc0c5cba5fc122"
+ },
+ "eve": {
+ "source": "vercel/eve",
+ "sourceType": "github",
+ "skillPath": "skills/eve/SKILL.md",
+ "computedHash": "4833349453c45c606f79202e495b7bbc42ea380f329f3beee36b9927763f19ef"
+ },
+ "nestjs-best-practices": {
+ "source": "kadajett/agent-nestjs-skills",
+ "sourceType": "github",
+ "skillPath": "skills/nestjs-best-practices/SKILL.md",
+ "computedHash": "58f8a630637be3acce1f118c747d68160346ada8a43d76cb52a5b4c4edaa2d37"
+ },
+ "no-use-effect": {
+ "source": "factory-ai/factory-plugins",
+ "sourceType": "github",
+ "skillPath": "plugins/typescript/skills/no-use-effect/SKILL.md",
+ "computedHash": "3c4d9c9a65312482569bf3ad27d149c5c339567b52009f90ac29d212beee3766"
+ },
+ "nuqs": {
+ "source": "pproenca/dot-skills",
+ "sourceType": "github",
+ "skillPath": "skills/.curated/nuqs/SKILL.md",
+ "computedHash": "5811f3b4c6f981aa75647ffb879d6e98429535ff830df219a04f4c9a884658a6"
+ },
+ "prisma-database-setup": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-database-setup/SKILL.md",
+ "computedHash": "6a991a2530a6da7131e3fc71c353e8278702d0146b8b6e1d2fdfc2d3d0a21bd2"
+ },
+ "shadcn": {
+ "source": "shadcn/ui",
+ "sourceType": "github",
+ "skillPath": "skills/shadcn/SKILL.md",
+ "computedHash": "c1a68ee06a668aced9ab2b5fbdea5f989864123794eb2e056b339a072dbb7f10"
+ },
+ "skill-creator": {
+ "source": "anthropics/skills",
+ "sourceType": "github",
+ "skillPath": "skills/skill-creator/SKILL.md",
+ "computedHash": "5ea13a6d9f0d4bb694405d79acd00cadec0d21bb138c4dd10fcf3c500cb835c2"
+ },
+ "turborepo": {
+ "source": "vercel/turborepo",
+ "sourceType": "github",
+ "skillPath": "skills/turborepo/SKILL.md",
+ "computedHash": "f4b990564b013482af64f72ba2dd28f2e244283a1fdcf23e469b9bcf942c1212"
+ },
+ "typescript-advanced-types": {
+ "source": "wshobson/agents",
+ "sourceType": "github",
+ "skillPath": "plugins/javascript-typescript/skills/typescript-advanced-types/SKILL.md",
+ "computedHash": "8cbf2bf600f392d7260e476e3202932a876e2281cda3b15a8b6a5a43f383252d"
+ },
+ "vercel-composition-patterns": {
+ "source": "vercel-labs/agent-skills",
+ "sourceType": "github",
+ "skillPath": "skills/composition-patterns/SKILL.md",
+ "computedHash": "575757e3e25761c8c562d6e395d29f0b76c98b1273c0bd72d88e6ab1bc9c7d42"
+ },
+ "vercel-react-best-practices": {
+ "source": "vercel-labs/agent-skills",
+ "sourceType": "github",
+ "skillPath": "skills/react-best-practices/SKILL.md",
+ "computedHash": "ca7b0c0c6e5f2750043f7f0cd72d16ac4e2abc48f9b5500d047a4b77a2506212"
+ },
+ "web-design-guidelines": {
+ "source": "vercel-labs/agent-skills",
+ "sourceType": "github",
+ "skillPath": "skills/web-design-guidelines/SKILL.md",
+ "computedHash": "f3bc47f890f42a44db1007ab390709ec368e4b8c089baee6b0007182236ac474"
+ }
+ }
+}
diff --git a/turbo.json b/turbo.json
index 6bde2596..b775eeab 100644
--- a/turbo.json
+++ b/turbo.json
@@ -1,21 +1,28 @@
{
- "$schema": "https://turborepo.dev/schema.json",
- "ui": "tui",
- "tasks": {
- "build": {
- "dependsOn": ["^build"],
- "inputs": ["$TURBO_DEFAULT$", ".env*"],
- "outputs": [".next/**", "!.next/cache/**", "!.next/dev/**"]
- },
- "lint": {
- "dependsOn": ["^lint"]
- },
- "check-types": {
- "dependsOn": ["^check-types"]
- },
- "dev": {
- "cache": false,
- "persistent": true
- }
- }
+ "$schema": "https://turborepo.dev/schema.json",
+ "ui": "tui",
+ "globalEnv": ["NODE_ENV"],
+ "tasks": {
+ "topo": {
+ "dependsOn": ["^topo"]
+ },
+ "build": {
+ "dependsOn": ["^build"],
+ "inputs": ["$TURBO_DEFAULT$", ".env*"],
+ "outputs": [".next/**", "!.next/cache/**", "!.next/dev/**", "dist/**"]
+ },
+ "lint": {
+ "dependsOn": ["topo"]
+ },
+ "check-types": {
+ "dependsOn": ["topo", "^build"]
+ },
+ "test": {
+ "dependsOn": ["topo", "^build"]
+ },
+ "dev": {
+ "cache": false,
+ "persistent": true
+ }
+ }
}