AI Context Documentation

Learn how to create AI-optimized documentation that helps coding assistants understand and work with your realm templates effectively.

Why AI Context Matters

Making your realms work seamlessly with AI coding assistants

Better Understanding

AI assistants can quickly grasp your project structure and make informed suggestions

Faster Development

Developers spend less time explaining context and more time building features

Consistent Results

Well-documented patterns lead to more consistent and maintainable code

AI Context Files

Standard documentation files that AI assistants can easily parse

00-CORE.md
essential

Project overview, architecture, and key concepts

Gives AI assistants the big picture of your project

Project Overview
Architecture
Key Technologies
Getting Started
01-AUTH.md
high

Authentication system documentation

Explains how users sign up, log in, and manage sessions

Auth Flow
Providers
Session Management
Security
02-DATABASE.md
high

Database schema and data models

Documents data structure and relationships

Schema
Models
Relationships
Migrations
03-API.md
medium

API endpoints and business logic

Details available endpoints and their functionality

Endpoints
Request/Response
Error Handling
Rate Limiting
04-FEATURES.md
medium

Feature-specific implementation details

Explains how major features work and can be extended

Feature List
Implementation
Configuration
Extension Points
README.md
essential

Index of all AI context files

Helps AI assistants navigate the documentation

File Index
Quick Reference
Common Tasks
Location Options
AI context files can be placed in either:
  • .realmkit/ai-context/ (recommended)
  • ai-context/ (alternative)

Documentation Examples

00-CORE.md Example

Project overview and architecture documentation

# Project Core Overview

## Project Description
A modern SaaS starter template built with Next.js 14, featuring authentication, 
payments, and a complete admin dashboard. Designed for rapid development of 
subscription-based applications.

## Architecture Overview
- **Frontend**: Next.js 14 with App Router
- **Backend**: API Routes with TypeScript
- **Database**: PostgreSQL with Prisma ORM
- **Authentication**: NextAuth.js with multiple providers
- **Payments**: Stripe for subscriptions and one-time payments
- **Styling**: Tailwind CSS with shadcn/ui components

## Key Directories
```
src/
├── app/                 # Next.js app router pages
├── components/          # Reusable UI components
├── lib/                 # Utility functions and configurations
├── types/               # TypeScript type definitions
└── hooks/               # Custom React hooks
```

## Core Concepts

### Feature Flags
The application uses feature flags to enable/disable functionality:
- `FEATURE_PAYMENTS`: Enable Stripe integration
- `FEATURE_ANALYTICS`: Enable analytics tracking
- `FEATURE_ADMIN`: Enable admin dashboard

### Database Schema
Primary entities:
- **User**: Authentication and profile data
- **Subscription**: Payment and billing information
- **Organization**: Multi-tenant support
- **AuditLog**: Activity tracking

## Getting Started
1. Copy `.env.example` to `.env.local`
2. Set up database: `npm run db:setup`
3. Start development: `npm run dev`

## Common Tasks
- Adding new features: See `04-FEATURES.md`
- Database changes: See `02-DATABASE.md`
- Authentication setup: See `01-AUTH.md`

01-AUTH.md Example

Authentication system documentation

# Authentication System

## Overview
Multi-provider authentication using NextAuth.js with support for email/password,
OAuth providers (Google, GitHub), and magic links.

## Authentication Flow
1. User initiates sign-in
2. Provider validates credentials
3. Session created with JWT
4. User redirected to dashboard

## Providers Configuration
```typescript
// lib/auth.ts
export const authOptions: NextAuthOptions = {
  providers: [
    EmailProvider({
      server: process.env.EMAIL_SERVER,
      from: process.env.EMAIL_FROM,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    GitHubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!,
    }),
  ],
  // ...
}
```

## Session Management
- Sessions stored in database via Prisma adapter
- JWT tokens for stateless authentication
- Automatic session refresh
- Secure logout with token cleanup

## Protected Routes
Use the `useSession` hook or `getServerSession` for protection:

```typescript
// Client-side protection
const { data: session, status } = useSession()
if (status === "loading") return <Loading />
if (!session) return <SignIn />

// Server-side protection
const session = await getServerSession(authOptions)
if (!session) {
  redirect('/auth/signin')
}
```

## User Roles and Permissions
- **user**: Basic authenticated user
- **admin**: Full system access
- **moderator**: Limited admin access

Roles stored in user.role field and checked via middleware.

README.md Example

AI context index and navigation

# AI Context Documentation Index

This directory contains structured documentation designed to help AI assistants 
understand and work with this codebase effectively.

## File Overview

### 📋 Core Documentation
- **00-CORE.md** - Project overview, architecture, and key concepts
- **README.md** - This index file

### 🔐 Authentication & Security  
- **01-AUTH.md** - Authentication system, providers, and session management

### 🗄️ Data & Database
- **02-DATABASE.md** - Database schema, models, and relationships

### 🔌 API & Integration
- **03-API.md** - API endpoints, request/response formats, and integrations

### ⚡ Features & Functionality
- **04-FEATURES.md** - Feature implementations and configuration

## Quick Reference

### Common File Patterns
- Components: `src/components/[category]/ComponentName.tsx`
- Pages: `src/app/[route]/page.tsx`
- API Routes: `src/app/api/[endpoint]/route.ts`
- Types: `src/types/[domain].ts`

### Key Configuration Files
- `next.config.js` - Next.js configuration
- `tailwind.config.ts` - Styling configuration  
- `prisma/schema.prisma` - Database schema
- `.env.local` - Environment variables

### Common Development Tasks
1. **Adding a new page**: Create in `src/app/[route]/page.tsx`
2. **Creating components**: Add to `src/components/[category]/`
3. **Database changes**: Modify `schema.prisma` and run migrations
4. **API endpoints**: Create in `src/app/api/[endpoint]/route.ts`

## AI Assistant Guidelines
When working with this codebase:
1. Always check the relevant context file first
2. Follow existing patterns and conventions
3. Update documentation when making changes
4. Test changes thoroughly before committing

Best Practices

Be Specific and Clear

Use precise language and concrete examples

  • Include actual code snippets
  • Provide specific file paths
  • Use clear section headers
  • Explain "why" not just "what"

Keep It Current

Update documentation when code changes

  • Document new features immediately
  • Remove outdated information
  • Update examples to match current code
  • Version your documentation

Think Like an AI

Structure content for AI comprehension

  • Use consistent formatting
  • Include context and relationships
  • Provide multiple examples
  • Explain edge cases and gotchas

Focus on Intent

Explain the purpose behind implementations

  • Document design decisions
  • Explain trade-offs made
  • Include alternative approaches
  • Describe future considerations

Content Guidelines

What to include in each type of documentation

Essential Elements

  • Clear project overview
  • Architecture diagrams or descriptions
  • Key file and directory structure
  • Common development tasks
  • Code examples and patterns

Advanced Topics

  • Design decisions and rationale
  • Extension points and customization
  • Testing strategies and examples
  • Performance considerations
  • Deployment and production setup

Tools and Automation

Streamline AI context documentation creation and maintenance

RealmKit CLI Support

# Generate AI context template
realmkit docs init

# Update context from code analysis  
realmkit docs sync

# Validate documentation completeness
realmkit docs validate

The RealmKit CLI can help generate, maintain, and validate your AI context documentation.

Documentation Linting

realmkit docs lint --fix

Automatically check for common documentation issues and inconsistencies.