You are an expert in TypeScript, Node.js, Next.js 15 App Router, React 19 RC, Shadcn UI, Radix UI, Tailwind CSS, tRPC, Drizzle ORM, NextAuth.js v5, and the HRIStudio platform architecture. ## Project Overview HRIStudio is a production-ready web-based platform for managing Wizard of Oz (WoZ) studies in Human-Robot Interaction research. The platform provides researchers with standardized tools for designing experiments, executing trials, and analyzing data while ensuring reproducibility and scientific rigor. ## Technology Stack - **Framework**: Next.js 15 with App Router and React 19 RC - **Language**: TypeScript (strict mode) - 100% type safety throughout - **Database**: PostgreSQL with Drizzle ORM for type-safe operations - **Authentication**: NextAuth.js v5 with database sessions and JWT - **API**: tRPC for end-to-end type-safe client-server communication - **UI**: Tailwind CSS + shadcn/ui (built on Radix UI primitives) - **Storage**: Cloudflare R2 (S3-compatible) for media files - **Deployment**: Vercel serverless platform with Edge Runtime - **Package Manager**: Bun exclusively (never npm, yarn, or pnpm) - **Real-time**: WebSocket with Edge Runtime compatibility ## Architecture & Key Concepts - **Hierarchical Structure**: Study → Experiment → Trial → Step → Action - **Role-Based Access**: Administrator, Researcher, Wizard, Observer (4 distinct roles) - **Real-time Trial Execution**: Live wizard control with comprehensive data capture - **Plugin System**: Extensible robot platform integration (RESTful, ROS2, custom) - **Visual Experiment Designer**: Drag-and-drop protocol creation interface - **Unified Form Experiences**: 73% code reduction through standardized patterns - **Enterprise DataTables**: Advanced filtering, pagination, export capabilities ## Documentation & Quick Reference ALWAYS check documentation before implementing. Key files: - `docs/quick-reference.md` - 5-minute setup, essential commands, common patterns - `docs/project-overview.md` - Complete feature overview and system architecture - `docs/implementation-details.md` - Architecture decisions, achievements, patterns - `docs/database-schema.md` - Complete PostgreSQL schema with 31 tables - `docs/api-routes.md` - Comprehensive tRPC API reference (11 routers) - `docs/project-status.md` - Current completion status (98% complete, production ready) ## File Organization & Key Locations ``` src/ ├── app/ # Next.js App Router pages │ ├── (auth)/ # Authentication pages (signin, signup) │ ├── (dashboard)/ # Main application pages │ │ ├── studies/ # Study management pages │ │ ├── experiments/ # Experiment design pages │ │ ├── participants/ # Participant management │ │ ├── trials/ # Trial execution and monitoring │ │ └── admin/ # Admin dashboard │ └── api/ # API routes and webhooks ├── components/ # UI components │ ├── ui/ # shadcn/ui base components │ │ ├── entity-form.tsx # Unified form component (KEY) │ │ └── data-table.tsx # Unified table component (KEY) │ ├── studies/ # Study-specific components │ ├── experiments/ # Experiment components & designer │ ├── participants/ # Participant management components │ └── trials/ # Trial execution components ├── server/ # Backend code │ ├── api/routers/ # tRPC routers (11 total) │ │ ├── auth.ts # Authentication & sessions │ │ ├── studies.ts # Study CRUD & team management │ │ ├── experiments.ts # Protocol design & validation │ │ ├── participants.ts # Participant management │ │ ├── trials.ts # Trial execution & monitoring │ │ └── admin.ts # System administration │ ├── auth/ # NextAuth.js v5 configuration │ └── db/ # Database schema and setup │ └── schema.ts # Complete Drizzle schema (31 tables) ├── lib/ # Utilities and configurations └── hooks/ # Custom React hooks ``` ## Database Schema (Key Tables) 31 tables total - see `docs/database-schema.md` for complete reference: - **users** - Authentication & profiles with role-based access - **studies** - Research project containers with team collaboration - **experiments** - Protocol templates with visual designer data - **participants** - Study participants with demographics & consent - **trials** - Experiment instances with execution tracking - **trial_events** - Comprehensive event logging for data capture - **robots** - Available platforms with plugin integration - **study_members** - Team collaboration with role assignments ## Development Environment - **Setup**: `bun install` → `bun db:push` → `bun db:seed` → `bun dev` - **Default Login**: `sean@soconnor.dev` / `password123` (Administrator) - **Seed Data**: 3 studies, 8 participants, 5 experiments, 7 trials (realistic scenarios) - **Commands**: Use `bun` exclusively for all operations ## Code Patterns & Standards ### Entity Forms (Unified Pattern) ALL entity creators/editors use the unified `EntityForm` component: ```typescript // Standard form implementation pattern export function EntityForm({ mode, entityId }: EntityFormProps) { const form = useForm({ resolver: zodResolver(entitySchema), defaultValues: { /* ... */ } }); return ( } > {/* Form fields */} ); } ``` ### Data Tables (Unified Pattern) ALL entity lists use the unified `DataTable` component: ```typescript ``` ### tRPC API Patterns ```typescript // Router organization by domain export const entityRouter = createTRPCRouter({ getAll: protectedProcedure .input(z.object({ search: z.string().optional() })) .query(async ({ ctx, input }) => { /* ... */ }), create: protectedProcedure .input(createEntitySchema) .mutation(async ({ ctx, input }) => { /* ... */ }), }); ``` ### Authentication & Authorization ```typescript // Role-based procedure protection export const adminProcedure = protectedProcedure.use(({ ctx, next }) => { if (ctx.session.user.role !== "administrator") { throw new TRPCError({ code: "FORBIDDEN" }); } return next(); }); ``` ## Key Implementation Rules ### Required Patterns - Use unified `EntityForm` for ALL entity creators/editors (Studies, Experiments, Participants, Trials) - Use unified `DataTable` for ALL entity lists with consistent column patterns - All entity operations are full pages, NEVER modals or dialogs - Follow the established file naming: PascalCase for components, camelCase for utilities - Use Server Components by default, minimize 'use client' directives - Implement proper loading states and error boundaries for all async operations ### TypeScript Standards - 100% type safety - NO `any` types allowed in production code - Use Zod schemas for input validation, infer types from schemas - Define explicit return types for all functions - Use const assertions for literal types: `const roles = ["admin", "user"] as const` - Prefer interfaces over types for component props ### Database Operations - Use Drizzle ORM exclusively with type-safe queries - Implement soft deletes with `deleted_at` timestamps - Add `created_at` and `updated_at` to all tables - Use transactions for multi-table operations - Create indexes for foreign keys and frequently queried fields ### Security & Performance - Validate ALL inputs on both client and server with Zod - Implement role-based authorization at route and resource level - Use optimistic updates for better UX with proper error handling - Minimize database queries with efficient joins and proper indexing - Follow WCAG 2.1 AA accessibility standards throughout ## Development Commands - `bun install` - Install dependencies - `bun dev` - Start development server (ONLY when actively developing) - `bun build` - Build for production - `bun typecheck` - Run TypeScript validation - `bun lint` - Run ESLint with autofix - `bun db:push` - Push schema changes (use instead of migrations in dev) - `bun db:seed` - Populate database with realistic test data ## Development Restrictions - NEVER run `bun dev` or development servers during implementation assistance - NEVER run `bun db:studio` during development sessions - Use ONLY `bun typecheck`, `bun build`, `bun lint` for verification - Use `bun db:push` for schema changes, not migrations in development ## Current Status - **Production Ready**: 98% complete, ready for immediate deployment - **Current Work**: Experiment designer enhancement with advanced visual programming - **Next Phase**: Enhanced step configuration modals and workflow validation - **Deployment**: Configured for Vercel with Cloudflare R2 and PostgreSQL ## Robot Integration - Plugin-based architecture supporting RESTful APIs, ROS2 (via rosbridge), and custom protocols - WebSocket communication for real-time robot control during trials - Type-safe action definitions with parameter schemas and validation - See `docs/ros2-integration.md` for complete integration guide Follow Next.js 15 best practices for Data Fetching, Rendering, and Routing. Always reference the comprehensive documentation in the `docs/` folder before implementing new features.