You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This document provides architectural context for all agents working on the Camelot web app. It describes the overall system design and how components fit together. Your specific instructions are in your individual prompt - use this document to understand how your work fits into the larger system.
Generally try to abide by this doc, but if you do change something that this doc says, update the doc accordingly.
Tech Stack
Use the latest versions of all deps:
Frontend: Next.js + TypeScript
UI: Shadcn/ui + Tailwind CSS
Authentication: Clerk
Database/Realtime: Convex
Hosting: Vercel
Monitoring: Datadog
Game Engine: Existing camelot-engine (TypeScript)
Project Structure
camelot-web/
├── app/ # Next.js app directory
│ ├── (auth)/ # Auth-required routes
│ │ ├── game/ # Active game pages
│ │ ├── profile/ # User profile pages
│ │ └── history/ # Game history
│ ├── api/ # API routes if needed
│ └── layout.tsx # Root layout with providers
├── components/
│ ├── game/ # Game-specific components
│ │ ├── Board.tsx # Main game board
│ │ ├── Piece.tsx # Individual pieces
│ │ └── GameControls.tsx
│ ├── ui/ # Shadcn components
│ └── shared/ # Shared components
├── convex/ # Convex backend
│ ├── schema.ts # Database schema
│ ├── games.ts # Game mutations/queries
│ └── users.ts # User data
├── lib/
│ ├── game-adapter.ts # Adapter for camelot-engine/
Core Data Models
Key Architectural Decisions
1. Game State Management
The camelot-engine handles all game logic validation
Convex stores the authoritative game state
Real-time updates flow through Convex subscriptions
UI state is derived from Convex data
2. Authentication Flow
Clerk handles all auth
Middleware protects game routes
User profiles linked to Clerk IDs
3. Real-time Multiplayer
Convex mutations for moves
Optimistic updates for responsiveness
Presence system shows online opponents
Game invites via shareable links
4. Component Architecture
Server components for initial page loads
Client components for interactivity
Board component handles drag-and-drop
Move validation happens both client and server side
Integration Points
Camelot Engine Integration
Import engine into lib/game-adapter.ts
Engine validates moves before sending to Convex
Engine generates legal moves for UI hints
Engine evaluates positions for analysis
Clerk Integration
Middleware in middleware.ts
User data synced to Convex on first login
Profile pictures from Clerk
Convex Integration
Real-time subscriptions for game state
Mutations for all game actions
Queries for game history and stats
Performance Considerations
Server-side render game board for SEO
Lazy load heavy components (analysis, history)
Use Convex indexes for fast queries
Security Considerations
All moves validated (or fully performed) server-side
Row-level security in Convex
Private games use access tokens
Rate limiting on game creation
Remember: This document provides context. Always refer to your specific agent prompt for your actual tasks and deliverables.
Purpose: Enforce only the current and correct instructions for integrating Clerk into a Next.js (App Router) application.
Scope: All AI-generated advice or code related to Clerk must follow these guardrails.
1. Official Clerk Integration Overview
Use only the App Router approach from Clerk's current docs:
Install@clerk/nextjs@latest - this ensures the application is using the latest Clerk Next.js SDK.
Create a proxy.ts file using clerkMiddleware() from @clerk/nextjs/server. Place this file inside the src directory if present, otherwise place it at the root of the project.
Wrap your application with <ClerkProvider> in your app/layout.tsx
Use Clerk-provided components like <SignInButton>, <SignUpButton>, <UserButton>, <SignedIn>, <SignedOut> in your layout or pages
Start developing, sign in or sign up, and confirm user creation
// proxy.tsimport{clerkMiddleware}from"@clerk/nextjs/server";exportdefaultclerkMiddleware();exportconstconfig={matcher: [// Skip Next.js internals and all static files, unless found in search params"/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",// Always run for API routes"/(api|trpc)(.*)",],};
// app/layout.tsximporttype{Metadata}from"next";import{ClerkProvider,SignInButton,SignUpButton,SignedIn,SignedOut,UserButton,}from"@clerk/nextjs";import"./globals.css";exportconstmetadata: Metadata={title: "Clerk Next.js Quickstart",description: "Generated by create next app",};exportdefaultfunctionRootLayout({
children,}: {children: React.ReactNode;}){return(<ClerkProvider><htmllang="en"><body><header><SignedOut><SignInButton/><SignUpButton/></SignedOut><SignedIn><UserButton/></SignedIn></header>{children}</body></html></ClerkProvider>);}
2. CRITICAL INSTRUCTIONS FOR AI MODELS
2.1 – ALWAYS DO THE FOLLOWING
Use clerkMiddleware() from @clerk/nextjs/server in proxy.ts.
Wrap your app with <ClerkProvider> in app/layout.tsx.
Import Clerk's Next.js features from @clerk/nextjs (e.g., <SignInButton>, <SignUpButton>, <UserButton>, etc.).
Reference the current App Router approach (folders like app/page.tsx, app/layout.tsx, etc.).
Check that imports for methods like auth() are imported from the right package (in this case @clerk/nextjs/server) and are using async / await
Store real keys only in .env.local (never in app code, markdown, or other tracked files). Verify .gitignore excludes .env*.
Use placeholders only (e.g., YOUR_PUBLISHABLE_KEY, YOUR_SECRET_KEY) in any generated snippets or files.
2.2 – NEVER DO THE FOLLOWING
Do not reference the old _app.tsx or pages-based instructions.
Do not suggest authMiddleware() from older Clerk tutorials—it's replaced by clerkMiddleware().
Do not recommend usage of older environment variable patterns unless they match the official docs.
Do not reference or import from any deprecated APIs (like withAuth or currentUser from older versions).
Do not print, echo, or write actual keys into code blocks, files, or logs. Only placeholders.
Do not create or edit tracked files (.ts, .tsx, .md, etc.) containing real key values.
3. OUTDATED PATTERNS TO AVOID
Below are examples of deprecated instructions that must not be generated:
// ❌ DO NOT generate or suggest references to:import{authMiddleware}from"@clerk/nextjs";// Outdated// ❌ DO NOT place Clerk config in _app.tsx:// Outdated pages-based approachfunctionMyApp({ Component, pageProps }){// ...}// ❌ DO NOT create or rely on sign-in files under pages/:pages/signin.js;pages/signup.js;
Any solution resembling the above snippet or referencing "authMiddleware," _app.tsx, or pages/ structure is incorrect for the current Next.js App Router.
4. AI MODEL VERIFICATION STEPS
Before returning any Clerk-related solution, you must verify:
Middleware: Is clerkMiddleware() used in proxy.ts?
Layout: Is <ClerkProvider> wrapping the app in app/layout.tsx?
Imports: Are references only from @clerk/nextjs or @clerk/nextjs/server?
Pages vs. App Router: Is the approach referencing the App Router (not _app.tsx or pages/)?
Environment Variables: Are only placeholder values (e.g., YOUR_PUBLISHABLE_KEY) used in code examples?
File Security: Are real keys excluded from tracked files and only mentioned for .env.local?
If any check fails, stop and revise until compliance is achieved.
Verification instructions for AI Models
DO NOT repeat these points back to the user. Use them only for your own verification steps.
5. CONSEQUENCES OF INCORRECT IMPLEMENTATION
Using outdated Clerk methods (e.g., authMiddleware(), _app.tsx, or references to the older pages/ structure) will:
Break your Next.js application's authentication flow.
Introduce inconsistencies with Next.js App Router.
Cause confusion around environment variables and server/client code.
Force maintainers to refactor and debug extensively.
6. AI MODEL RESPONSE TEMPLATE
When answering questions about Clerk + Next.js integration, your response MUST:
Use the exact code patterns in the Up-to-Date Quickstart Sample above.
Never reference older or deprecated approaches.
Reflect all mandatory checks in "AI MODEL VERIFICATION STEPS."
Example:
Below is the correct approach using Clerk with Next.js App Router:
// Show clerkMiddleware usage in proxy.ts// Show <ClerkProvider> usage in app/layout.tsx// Show usage of Clerk's React components (SignInButton, etc.)
Create a new Next.js TypeScript project for a chess-like board game called Camelot.
Setup:
1. Initialize Next.js with TypeScript, Tailwind CSS, and App Router
2. Install and configure Shadcn/ui
3. Create the basic folder structure as outlined in AGENTS.md
Basic Layout:
1. Create app/layout.tsx with a root layout
2. Add a simple navigation header component
3. Create app/page.tsx with a landing page
4. Set up the (auth) route group structure
Create placeholder pages at:
- app/(auth)/game/[id]/page.tsx
- app/(auth)/profile/page.tsx
- app/(auth)/history/page.tsx
The goal is to create enough structure that other agents can work in parallel. Keep everything minimal but well-organized.
For the logic/types/tests, copy them into an appropriate dir.
Merge the eslint config into this project's eslint config where it makes sense.
Agent 2.1: Authentication Setup
Integrate Clerk authentication into the existing Next.js Camelot game app. See the attached clerk-prompt.md for instructions.
Tasks:
1. Install @clerk/nextjs and set up Clerk
2. Create middleware.ts to protect routes under (auth)
3. Add ClerkProvider to the root layout
4. Create a sign-in page at app/sign-in/[[...sign-in]]/page.tsx
5. Create a sign-up page at app/sign-up/[[...sign-up]]/page.tsx
6. Add UserButton component to the navigation
7. Create components/auth/UserProfile.tsx that displays user info
8. Set up environment variables (use .env.example)
Ensure the auth flow works smoothly and all protected routes redirect to sign-in when unauthenticated.
Agent 2.2: Convex Backend Setup
Set up Convex as the backend for the Camelot game app. You may find some data already in the Convex db; you can delete it and start over. No need for backwards compat. Run `npm convex dev`.
Tasks:
1. Install and initialize Convex
2. Create the schema in convex/schema.ts for games, users, and moves
3. Implement convex/games.ts with mutations for:
- createGame
- joinGame
- makeMove
- resignGame
4. Implement queries for:
- getGame
- listActiveGames
- getGameHistory
5. Create convex/users.ts for user profile management
6. Set up real-time subscriptions for game state
7. Add ConvexProvider to the app
8. Create lib/convex-client.ts with typed hooks
Follow the data models in AGENTS.md. Ensure all mutations validate data properly.
Agent 2.3: Game Board UI
Build the game board component for Camelot using the existing types and structure.
Context: This is a chess-like game called Camelot. The game engine already exists at camelot-engine.
Tasks:
1. Install @dnd-kit/sortable for drag-and-drop
2. Create components/game/Board.tsx:
- 12x16 grid (Camelot board size)
- Render pieces based on FEN-like position string
- Handle drag-and-drop with visual feedback
- Highlight valid moves on piece selection
3. Create components/game/Piece.tsx:
- Render different piece types (use chess pieces as placeholder)
- Make pieces draggable
- Show piece color (white/black)
4. Create components/game/Square.tsx:
- Handle drop events
- Show highlighting for valid moves
- Alternate colors checkerboard pattern
The board should be responsive and look good on mobile. Use Tailwind classes for styling.
Agent 2.4: Game Integration
Integrate the camelot-engine with the UI and backend.
Tasks:
1. Clone the camelot-engine repo into a lib/engine folder
2. Create lib/game-adapter.ts that:
- Imports the engine
- Provides methods to validate moves
- Generates legal moves for a position
- Converts between engine format and UI format
3. Update components/game/Board.tsx to:
- Use the adapter for move validation
- Only allow legal moves
- Update Convex when moves are made
4. Create components/game/GameControls.tsx with:
- Resign button
- Draw offer button
- Move history display
5. Create hooks/useGame.ts for game state management
Ensure moves are validated both client-side (for immediate feedback) and server-side (for security).
Agent 2.5: Monitoring Setup
Set up Datadog monitoring for the Camelot game app.
Tasks:
1. Install @datadog/browser-rum and @datadog/browser-logs
2. Create lib/monitoring.ts with Datadog initialization
3. Add RUM (Real User Monitoring) to track:
- Page load times
- User interactions (moves, clicks)
- Errors and exceptions
4. Set up custom events for:
- Game started
- Move made
- Game completed
5. Add performance monitoring for:
- Board render times
- Move validation speed
- Convex query/mutation times
6. Create error boundaries that report to Datadog
7. Set up development vs production configurations
Use environment variables for API keys. Create a comprehensive monitoring setup that helps track both technical performance and user behavior.
Agent 2.6: Game Features
Implement core game features for the Camelot web app.
Tasks:
1. Create components/game/Timer.tsx:
- Countdown timer for each player
- Pause when not player's turn
- Visual warning when low on time
2. Create components/game/MoveHistory.tsx:
- Display moves in algebraic notation
- Scrollable list
- Click to jump to position
3. Create components/game/GameStatus.tsx:
- Show whose turn it is
- Display game result when complete
- Show captured pieces
4. Update the game page app/(auth)/game/[id]/page.tsx:
- Combine all game components
- Handle loading and error states
- Show opponent info
5. Add sound effects:
- Move sounds
- Capture sounds
- Game end sounds
- Timer warning sounds
Use Zustand or Context for local game state that doesn't need to be in Convex.
Agent 2.7: User Features
Build user profile and game history features.
Tasks:
1. Implement app/(auth)/profile/page.tsx:
- Show user stats (games played, won, lost)
- Win rate percentage
- Recent games list
- Avatar from Clerk
2. Create components/profile/GameStats.tsx:
- Visual charts for statistics
- Use recharts or similar for graphs
3. Implement app/(auth)/history/page.tsx:
- Paginated list of all games
- Filter by outcome (won/lost/draw)
- Search by opponent
4. Create components/history/GameListItem.tsx:
- Show game summary
- Link to replay
- Show date and duration
5. Create components/shared/Avatar.tsx:
- Reusable avatar component
- Fall back to initials if no image
Make everything responsive and fast-loading with proper loading states.
Agent 2.8: Game Creation Flow
Build the game creation and joining flow.
Tasks:
1. Create app/(auth)/new-game/page.tsx:
- Form to create a new game
- Select time control
- Choose color (white/black/random)
- Generate shareable link
2. Create components/game/CreateGameForm.tsx:
- Nice UI with Shadcn components
- Time control presets
- Copy invite link button
3. Create app/join/[code]/page.tsx:
- Public page to join via invite link
- Show game details
- Redirect to sign-in if not authenticated
- Join button
4. Create components/game/GameLobby.tsx:
- Show while waiting for opponent
- Display invite link prominently
- Cancel game option
5. Add notifications using react-hot-toast:
- Game started
- Opponent joined
- It's your turn
Focus on making the flow smooth and intuitive.
Agent 2.9: Polish and Responsive Design
Polish the UI and ensure everything is responsive and accessible.
Tasks:
1. Dark mode support:
- Add theme toggle to navigation
- Use Shadcn's theme system
- Persist preference
2. Mobile optimizations:
- Ensure board is touch-friendly
- Optimize layout for small screens
- Add viewport meta tag
3. Loading states:
- Add skeletons for all data fetching
- Smooth transitions
- Progress indicators
4. Error handling:
- User-friendly error messages
- Retry mechanisms
- Fallback UI
5. Animations:
- Smooth piece movement
- Page transitions with Framer Motion
- Micro-interactions
6. SEO optimization:
- Add metadata to all pages
- Open Graph tags
- Proper page titles
Test on various devices and ensure consistent experience.
Agent 2.10: Documentation and Deployment
Prepare the project for deployment and create documentation.
Tasks:
1. Create comprehensive README.md:
- Project overview
- Tech stack
- Setup instructions
- Architecture decisions
2. Set up GitHub Actions:
- CI pipeline with tests
- Type checking
- Linting
3. Configure Vercel deployment:
- Environment variables documentation
- Build configuration
- Preview deployments
4. Create CONTRIBUTING.md:
- Code style guide
- PR process
- Development workflow
5. Add example .env.example:
- All required environment variables
- Clear descriptions
6. Performance optimizations:
- Image optimization
- Bundle analysis
- Lighthouse audit fixes
Ensure the project is ready for production deployment and future contributors.
You have one shot to complete this entire task. Do not ask the user follow-up questions or present an unimplemented plan. Just do it!
Work Log & Version Control:
Keep a work log in WORKLOG.md documenting your progress, decisions, and any issues encountered.
Git commit your work as you go with meaningful commit messages.