Implementation Notes - Go Game with AT Protocol#
Overview#
This document provides technical details about the implementation and what needs to be completed for full AT Protocol integration.
What's Implemented#
1. Project Structure ✅#
The SvelteKit application is fully structured with:
- Routes for home page, game pages, and API endpoints
- Server-side rendering and data loading
- Component organization
- Database setup with Kysely
2. Custom Lexicons ✅#
Three custom AT Protocol lexicons are defined in /lexicons:
- boo.sky.go.game: Game records with players, board size, status
- boo.sky.go.move: Move records with coordinates, captures, and timestamps
- boo.sky.go.pass: Pass action records
These lexicons follow AT Protocol standards and can be used to publish records to the network.
3. Database Schema ✅#
SQLite database with three main tables:
games: Local cache of game recordsmoves: Local cache of move recordspasses: Local cache of pass records
The database uses AT Protocol URIs as primary keys to maintain consistency with the network.
4. Game Logic ✅#
The Wgo.js library is integrated for:
- Board rendering using SVGBoard
- Move validation using Game class
- Capture calculation
- Stone placement and removal
5. UI Components ✅#
- Home Page: Login form, game creation, and game listing
- Game Page: Interactive board, move history, player info
- Board Component: Reusable Wgo.js wrapper with click handling
What Needs Completion#
1. OAuth Authentication ⚠️#
Current State:
- OAuth routes exist (
/auth/login,/auth/callback,/auth/logout) - Session management structure is in place
- OAuth client returns null (placeholder)
To Complete:
-
Set up proper NodeOAuthClient configuration:
import { NodeOAuthClient } from '@atproto/oauth-client-node'; const client = await NodeOAuthClient.fromClientId({ clientId: `${PUBLIC_BASE_URL}/oauth-client-metadata.json`, stateStore: new StateStore(), // Implement state persistence sessionStore: new SessionStore(), // Implement session persistence }); -
Update
oauth-client-metadata.jsonwith production URLs -
Implement proper session encryption (currently using base64 encoding)
-
Handle OAuth flows:
- Login initiation with
client.authorize(handle) - Callback handling with
client.callback(params) - Session restoration with
client.restore(did)
- Login initiation with
2. AT Protocol Record Creation ⚠️#
Current State:
- Records are created in local database
- AT URIs are generated correctly
- Agent creation is commented out
To Complete:
-
Create authenticated AtpAgent instances:
const oauthSession = await client.restore(session.did); const agent = oauthSession.agent; -
Create records in AT Protocol:
await agent.com.atproto.repo.createRecord({ repo: session.did, collection: 'boo.sky.go.game', rkey: generatedTid, record: gameRecord, }); -
Update records for game state changes (joining, completion)
-
Handle record creation errors and retries
3. Firehose Subscription ⚠️#
Current State:
- Placeholder functions exist in
src/lib/server/firehose.ts - Database update logic is outlined
To Complete:
-
Install firehose dependencies:
npm install @atproto/sync -
Set up WebSocket connection:
import { Firehose } from '@atproto/sync'; const firehose = new Firehose({ service: 'wss://bsky.network', filterCollections: [ 'boo.sky.go.game', 'boo.sky.go.move', 'boo.sky.go.pass' ] }); -
Handle commit events:
firehose.on('commit', async (evt) => { // Parse CAR blocks // Update local database // Emit real-time updates to clients }); -
Implement error handling and reconnection logic
4. Real-time Updates ⚠️#
Current State:
- Game page reloads after each move
- No live updates when opponent moves
To Complete:
-
Set up Server-Sent Events or WebSocket connection:
// In +server.ts export const GET: RequestHandler = async ({ params }) => { const stream = new ReadableStream({ start(controller) { // Subscribe to game updates // Send SSE events on changes } }); return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', } }); }; -
Connect from client:
const eventSource = new EventSource(`/api/games/${gameId}/stream`); eventSource.onmessage = (event) => { const data = JSON.parse(event.data); // Update board with new move }; -
Emit events from firehose when moves are detected
Development Workflow#
Running the Application#
-
Install dependencies:
npm install -
Set up environment variables:
cp .env.example .env # Edit .env with your values -
Start development server:
npm run dev -
Access at http://localhost:5173
Testing Without OAuth#
For development, you can bypass OAuth by:
- Manually creating session cookies
- Using test DIDs (e.g.,
did:plc:test123) - Testing game logic with local database only
Type Checking#
Run type checking:
npm run check
Note: Some errors related to Node version (<18) may appear but don't affect functionality.
Production Considerations#
Security#
- Use proper session encryption (not base64)
- Implement CSRF protection
- Validate all inputs server-side
- Use HTTPS for all production traffic
- Store secrets in environment variables
Performance#
- Add database indexes for frequently queried fields
- Implement pagination for game lists
- Cache game state in memory
- Use connection pooling for database
Reliability#
- Add error boundaries in UI
- Implement retry logic for AT Protocol calls
- Add logging and monitoring
- Handle network disconnections gracefully
Scalability#
- Consider moving to PostgreSQL for larger scale
- Implement horizontal scaling for API servers
- Use Redis for session storage
- Add CDN for static assets
Testing Strategy#
Unit Tests#
- Move validation logic
- TID generation
- Session management
- Database queries
Integration Tests#
- OAuth flow end-to-end
- Game creation and joining
- Move recording
- Firehose event handling
E2E Tests#
- Full game playthrough
- Multiple players simultaneously
- Pass and game completion
- Error scenarios
Deployment#
Environment Setup#
- Set production environment variables
- Use production OAuth client ID
- Configure production database
- Set up SSL certificates
Build Process#
npm run build
Running in Production#
node build/index.js
Or use a process manager like PM2:
pm2 start build/index.js --name go-game
Future Enhancements#
Game Features#
- Automatic territory scoring
- Time controls (byo-yomi, Fischer)
- Undo/redo functionality
- Game analysis tools
- SGF import/export
Social Features#
- Game chat using AT Protocol
- Spectator mode
- Game reviews and comments
- Tournament organization
- Player profiles and stats
Technical Improvements#
- Progressive Web App (PWA)
- Offline play capability
- Mobile app (React Native)
- Game AI integration
- Multiple board themes
Resources#
Support#
For questions about:
- AT Protocol: https://github.com/bluesky-social/atproto
- Wgo.js: https://github.com/waltheri/wgo.js
- SvelteKit: https://github.com/sveltejs/kit