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 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. It's specification and related paper can be found at docs/paper.md (READ THIS), as well as the docs folder.

## 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<EntityFormData>({
    resolver: zodResolver(entitySchema),
    defaultValues: { /* ... */ }
  });

  return (
    <EntityForm
      mode={mode}
      entityName="Entity"
      form={form}
      onSubmit={handleSubmit}
      sidebar={<NextSteps />}
    >
      {/* Form fields */}
    </EntityForm>
  );
}
```

### Data Tables (Unified Pattern)
ALL entity lists use the unified `DataTable` component:
```typescript
<DataTable
  columns={entityColumns}
  data={entities}
  searchKey="name"
  onExport={handleExport}
  showColumnToggle
/>
```

### 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
- NEVER use emojis - use Lucide icons exclusively for all visual elements
- Maximize component reusability - create shared patterns and abstractions
- ALL entity view pages must follow consistent patterns and layouts

### 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

## UI/UX Standards
- **Icons**: Use Lucide icons exclusively - NO emojis in codebase or responses
- **Reusability**: Maximize component reuse through shared patterns and abstractions
- **Entity Views**: All entity view pages (studies, experiments, participants, trials) must follow consistent patterns
- **Page Structure**: Use global page headers, breadcrumbs, and consistent layout patterns
- **Visual Consistency**: Maintain consistent spacing, typography, and interaction patterns

## 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
- **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.

## Documentation Guidelines
- **Location**: ALL documentation must be in `docs/` folder - NEVER create markdown files in root
- **Structure**: Use existing documentation organization and file naming conventions
- **Cross-References**: Always link to related documentation files using relative paths
- **Updates**: When adding features, update relevant docs files (don't create new ones unless necessary)
- **Completeness**: Document all new features, APIs, components, and architectural changes
- **Format**: Use consistent markdown formatting with proper headers, code blocks, and lists
- **Status Tracking**: Update `docs/work_in_progress.md` for active development
- **Integration**: Ensure new docs integrate with existing quick-reference and overview files

## Plugin System Documentation Standards
- **Core Blocks**: Document in `docs/core-blocks-system.md` (to be created)
- **Robot Plugins**: Use existing `docs/plugin-system-implementation-guide.md`
- **Repository Structure**: Document all plugin repositories in dedicated sections
- **Block Definitions**: Include JSON schema examples and validation rules
- **Loading Process**: Document async loading, error handling, and fallback systems

## Response Guidelines
- Keep responses concise and minimal
- No emojis or excessive formatting
- Focus on essential information only
- Prioritize code fixes over explanations
- Use bullet points for lists, not checkmarks
- Respond with requested format (edits, diagnostics, etc.)
- Avoid verbose summaries unless explicitly requested
