description: Comprehensive guide for AI agents working with the Izri codebase version: 1.0.0 lastUpdated: 2025-01-10 tags: [ai-agent, guide, documentation, best-practices] status: approved priority: high author: Team relatedDocs:
- ./QUICK_START.md
- ../../.ai/rules/repo.md
- ../../.ai/rules/coding-patterns.md
- ../../.ai/rules/architecture.md
- ../../.ai/rules/workflows.md
- ../../.ai/rules/ai-agent-config.md
AI Agent Guide
Comprehensive guide for AI agents working with the Izri codebase
π Table of Contents
- Overview
- Quick Start for AI Agents
- Codebase Understanding
- Common Tasks
- Patterns and Conventions
- Best Practices
- Examples
- Resources
Overview
Quick Summary
- Understand Izriβs monorepo and AI-agent responsibilities
- Locate the right context quickly using the provided table
- Follow recommended workflows for safe, consistent updates
Purpose
This guide helps AI agents understand and interact effectively with the Izri codebase. It provides:
- Context-aware understanding of the monorepo structure
- Task-specific guidance for common development operations
- Pattern recognition for consistent code generation
- Integration examples for various development scenarios
Scope
AI agents can assist with:
- β Code generation and refactoring
- β Bug fixing and debugging
- β Test writing and test analysis
- β Documentation generation and updates
- β Code review and improvement suggestions
- β Architecture analysis and recommendations
Quick Start for AI Agents
1. Understand the Context
Repository Type: Turborepo monorepo
Primary Languages: TypeScript, Python
Package Manager: pnpm
Key Technologies: React Router, Hono, tRPC, Drizzle ORM, FastAPI
2. Key Locations
.ai/rules/ # AI-specific context and rules
docs/ # Human and AI documentation
apps/
web/ # React Router frontend
api/ # Hono + tRPC backend
packages/
database/ # Drizzle ORM and schema
trpc/ # tRPC router definitions
auth/ # Authentication logic
ai-service/ # Python FastAPI service
3. Essential Context Files
Before working on any task, review these files:
| File | Purpose | When to Read |
|---|---|---|
.ai/rules/repo.md |
Repository overview and structure | Always (first thing) |
.ai/rules/coding-patterns.md |
Coding conventions and patterns | Before code generation |
.ai/rules/architecture.md |
System architecture details | Before architectural changes |
.ai/rules/workflows.md |
Development workflows | Before complex tasks |
4. Mental Model
User Request
β
Read Context (.ai/rules/)
β
Understand Requirements
β
Check Relevant Documentation (docs/)
β
Review Existing Code Patterns
β
Generate/Modify Code
β
Verify Against Patterns
β
Provide Response
Codebase Understanding
Architecture Overview
Monorepo Structure: Turborepo with shared packages
βββββββββββββββββββββββββββββββββββββββββββ
β User Interface β
β (React Router Frontend) β
β apps/web (port 5173) β
ββββββββββββββββ¬βββββββββββββββββββββββββββ
β tRPC + React Query
β
ββββββββββββββββΌβββββββββββββββββββββββββββ
β API Gateway β
β (Hono + tRPC Backend) β
β apps/api (port 4000) β
ββββ¬ββββββββββ¬ββββββββββ¬βββββββββββββββββββ
β β β
β β βββββββββββββββββββ
β β β
β β ββββββΌβββββ
β β β AI β
β β β Service β
β β β(FastAPI)β
β β βββββββββββ
β β
β ββββββΌβββββ ββββββββββββ
β βDatabase β β Redis β
β βPackage β β Cache β
β ββββββ¬βββββ ββββββββββββ
β β
β ββββββΌβββββββββ
β β PostgreSQL β
β β (Drizzle) β
β βββββββββββββββ
β
ββββΊ Auth Package
Data Flow
- User Action β Frontend component
- Component β tRPC query/mutation (React Query)
- tRPC Client β API server (HTTP)
- API Server β tRPC router handler
- Handler β Database package (Drizzle ORM)
- Drizzle β PostgreSQL database
- Response β Back through the chain
Package Dependencies
apps/web β depends on β packages/trpc (client)
apps/api β depends on β packages/trpc (server)
β packages/database
β packages/auth
packages/trpc β depends on β packages/shared
packages/database β depends on β packages/shared
Common Tasks
Task 1: Adding a New Feature
Process
- Understand the feature requirements
- Identify affected layers:
- Frontend? β
apps/web/ - Backend API? β
apps/api/orpackages/trpc/ - Database? β
packages/database/src/schema.ts - AI? β
packages/ai-service/
- Frontend? β
- Review similar existing features
- Generate code following patterns
- Suggest tests
Example Flow: Add "Test Suite Comments" Feature
// 1. Database Schema (packages/database/src/schema.ts)
export const testComments = pgTable('test_comments', {
id: varchar('id', { length: 191 }).primaryKey(), // ULID stored as varchar
testId: varchar('test_id', { length: 191 }).references(() => tests.id).notNull(),
userId: varchar('user_id', { length: 191 }).references(() => users.id).notNull(),
content: text('content').notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
});
// 2. tRPC Router (packages/trpc/src/routers/testComments.ts)
import { ulid } from 'ulid';
export const testCommentsRouter = router({
create: protectedProcedure
.input(z.object({
testId: z.string().ulid(), // ULID validation
content: z.string().min(1),
}))
.mutation(async ({ ctx, input }) => {
return await ctx.db.insert(testComments).values({
id: ulid(), // Generate ULID for new comment
testId: input.testId,
userId: ctx.user.id,
content: input.content,
}).returning();
}),
list: protectedProcedure
.input(z.object({ testId: z.string().ulid() })) // ULID validation
.query(async ({ ctx, input }) => {
return await ctx.db
.select()
.from(testComments)
.where(eq(testComments.testId, input.testId));
}),
});
// 3. Frontend Hook (apps/web/app/hooks/useTestComments.ts)
export function useTestComments(testId: string) {
return trpc.testComments.list.useQuery({ testId });
}
export function useCreateTestComment() {
const utils = trpc.useUtils();
return trpc.testComments.create.useMutation({
onSuccess: () => {
utils.testComments.list.invalidate();
},
});
}
// 4. React Component (apps/web/app/components/TestComments.tsx)
export function TestComments({ testId }: { testId: string }) {
const { data: comments } = useTestComments(testId);
const createComment = useCreateTestComment();
// Component implementation...
}
Task 2: Fixing Bugs
Process
- Analyze the error message and stack trace
- Identify the affected component/module
- Review related code in context
- Understand the expected vs actual behavior
- Propose fix with explanation
- Suggest tests to prevent regression
Example: Database Query Error
// β Problem: Type error in database query
const project = await db.select().from(projects).where(eq(projects.id, id));
// Error: Type 'Project[]' is not assignable to type 'Project'
// β
Solution: Use .limit(1) or access first element
const projects = await db
.select()
.from(projects)
.where(eq(projects.id, id))
.limit(1);
const project = projects[0];
// Or use helper function
const project = await db.query.projects.findFirst({
where: eq(projects.id, id),
});
Task 3: Writing Tests
Process
- Identify the unit/feature to test
- Review existing test patterns
- Generate test cases covering:
- Happy path
- Edge cases
- Error conditions
- Follow testing conventions
Example: Testing tRPC Procedure
// packages/trpc/src/routers/__tests__/projects.test.ts
import { describe, it, expect } from 'vitest';
import { createTestContext } from '../../test-utils';
import { appRouter } from '../../root';
describe('projects router', () => {
describe('create', () => {
it('should create a new project', async () => {
const ctx = await createTestContext({ authenticated: true });
const caller = appRouter.createCaller(ctx);
const project = await caller.projects.create({
name: 'Test Project',
description: 'A test project',
});
expect(project).toMatchObject({
name: 'Test Project',
description: 'A test project',
userId: ctx.user.id,
});
});
it('should fail when not authenticated', async () => {
const ctx = await createTestContext({ authenticated: false });
const caller = appRouter.createCaller(ctx);
await expect(
caller.projects.create({
name: 'Test Project',
description: 'A test project',
})
).rejects.toThrow('UNAUTHORIZED');
});
});
});
Task 4: Generating Documentation
Process
- Identify what needs documentation
- Review existing documentation structure
- Follow documentation patterns
- Include:
- Purpose and overview
- Usage examples
- API reference (if applicable)
- Related links
Example: Component Documentation
/**
* TestComments Component
*
* Displays and manages comments for a test case. Allows authenticated users
* to view existing comments and add new ones.
*
* @example
* ```tsx
* <TestComments testId="01ARZ3NDEKTSV4RRFFQ69G5FAV" />
* ```
*
* @param {Object} props - Component props
* @param {string} props.testId - ULID of the test to show comments for
*
* @requires Authentication - User must be logged in to view/add comments
*
* @see {@link useTestComments} - Hook for fetching comments
* @see {@link useCreateTestComment} - Hook for creating comments
*/
export function TestComments({ testId }: TestCommentsProps) {
// Implementation...
}
Task 5: Code Review and Improvements
Process
- Analyze code structure and patterns
- Check for:
- Code consistency with existing patterns
- Potential bugs or edge cases
- Performance considerations
- Type safety
- Error handling
- Suggest improvements with reasoning
Example: Review Suggestions
// Original Code
async function getProject(id: string) {
const project = await db.select().from(projects).where(eq(projects.id, id));
return project[0];
}
// Review Comments:
// 1. Missing error handling for not found
// 2. No input validation
// 3. Should use findFirst for clarity
// 4. Missing return type annotation
// Suggested Improvement
async function getProject(id: string): Promise<Project> {
// Validate input
if (!id || !isValidUuid(id)) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'Invalid project ID',
});
}
// Use more semantic query method
const project = await db.query.projects.findFirst({
where: eq(projects.id, id),
});
// Handle not found
if (!project) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Project not found',
});
}
return project;
}
Patterns and Conventions
File Naming
| Type | Pattern | Example |
|---|---|---|
| React Component | PascalCase | TestComments.tsx |
| Hook | camelCase with "use" prefix | useTestComments.ts |
| Utility | camelCase | formatDate.ts |
| Type/Interface | PascalCase | TestComment.ts |
| Router | camelCase with "Router" suffix | testCommentsRouter.ts |
Code Organization
apps/web/app/
βββ components/ # Reusable UI components
β βββ ui/ # Base UI components (shadcn/ui)
β βββ features/ # Feature-specific components
βββ hooks/ # Custom React hooks
βββ lib/ # Utility functions
βββ routes/ # React Router routes
βββ types/ # TypeScript type definitions
apps/api/src/
βββ routers/ # tRPC route handlers
βββ middleware/ # Hono middleware
βββ lib/ # Utilities and helpers
βββ types/ # Type definitions
packages/database/src/
βββ schema.ts # Drizzle schema definitions
βββ migrations/ # SQL migrations
βββ seed.ts # Database seeding
TypeScript Patterns
Zod Schema + TypeScript Types
// Define Zod schema for validation
export const createProjectSchema = z.object({
name: z.string().min(1).max(255),
description: z.string().optional(),
githubUrl: z.string().url().optional(),
});
// Infer TypeScript type from schema
export type CreateProjectInput = z.infer<typeof createProjectSchema>;
Database Types from Schema
// Drizzle automatically generates types
import { projects } from '@izri/database/schema';
import type { InferSelectModel, InferInsertModel } from 'drizzle-orm';
// Type for SELECT queries
export type Project = InferSelectModel<typeof projects>;
// Type for INSERT operations
export type NewProject = InferInsertModel<typeof projects>;
Error Handling
// Use TRPCError for API errors
import { TRPCError } from '@trpc/server';
throw new TRPCError({
code: 'NOT_FOUND', // BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, etc.
message: 'Project not found',
cause: originalError, // Optional: include original error
});
Frontend State Management
// Use tRPC + React Query for server state
const { data, isLoading, error } = trpc.projects.list.useQuery();
// Use React hooks for local UI state
const [isOpen, setIsOpen] = useState(false);
// Use React Router for URL state
const [searchParams] = useSearchParams();
const page = searchParams.get('page') || '1';
Best Practices
For Code Generation
Always review existing patterns first
- Look at similar features in the codebase
- Match naming conventions
- Follow file structure patterns
Generate complete, working code
- Include all necessary imports
- Add proper error handling
- Include TypeScript types
Consider the full stack
- Database schema changes?
- API endpoint needed?
- Frontend component required?
- Think through all layers
Type safety first
- Use Zod for runtime validation
- Leverage TypeScript type inference
- Avoid
anytypes
For Bug Fixing
Understand the root cause
- Don't just fix symptoms
- Trace the issue through the stack
- Identify why it happened
Consider edge cases
- What if data is null/undefined?
- What if the user is not authenticated?
- What if concurrent operations occur?
Suggest preventive measures
- Add validation
- Improve error handling
- Recommend tests
For Testing
Follow existing test patterns
- Use the same test utilities
- Match assertion styles
- Follow file naming conventions
Test behavior, not implementation
- Focus on inputs and outputs
- Test user-facing functionality
- Avoid testing internal details
Cover critical paths
- Happy path
- Error conditions
- Edge cases
- Authentication/authorization
For Documentation
Be practical and actionable
- Include code examples
- Show actual usage
- Explain the "why"
Keep it current
- Update when code changes
- Mark deprecated features
- Include version information
Structure for discoverability
- Use clear headings
- Include table of contents
- Cross-reference related docs
Examples
Example 1: Full Stack Feature
See examples/full-stack-feature.md
Example 2: Database Migration
See examples/database-migration.md
Example 3: tRPC Endpoint
Example 4: React Component
See examples/react-component.md
Resources
AI Context Files
| File | Description |
|---|---|
.ai/rules/repo.md |
Repository structure and overview |
.ai/rules/coding-patterns.md |
Coding conventions and patterns |
.ai/rules/architecture.md |
System architecture details |
.ai/rules/workflows.md |
Development workflows |
Documentation
| Section | Link |
|---|---|
| Getting Started | docs/getting-started/ |
| Architecture | docs/architecture/ |
| Frontend | docs/frontend/ |
| Backend | docs/backend/ |
| API Reference | docs/api-reference/ |
External Documentation
Version History
| Version | Date | Changes |
|---|---|---|
| 1.0.0 | 2025-01-10 | Initial AI agent guide |
Next Steps: Review the detailed coding patterns and explore the examples to understand common implementation patterns.