Docs /ai-agents

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

  1. User Action β†’ Frontend component
  2. Component β†’ tRPC query/mutation (React Query)
  3. tRPC Client β†’ API server (HTTP)
  4. API Server β†’ tRPC router handler
  5. Handler β†’ Database package (Drizzle ORM)
  6. Drizzle β†’ PostgreSQL database
  7. 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

  1. Understand the feature requirements
  2. Identify affected layers:
    • Frontend? β†’ apps/web/
    • Backend API? β†’ apps/api/ or packages/trpc/
    • Database? β†’ packages/database/src/schema.ts
    • AI? β†’ packages/ai-service/
  3. Review similar existing features
  4. Generate code following patterns
  5. 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

  1. Analyze the error message and stack trace
  2. Identify the affected component/module
  3. Review related code in context
  4. Understand the expected vs actual behavior
  5. Propose fix with explanation
  6. 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

  1. Identify the unit/feature to test
  2. Review existing test patterns
  3. Generate test cases covering:
    • Happy path
    • Edge cases
    • Error conditions
  4. 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

  1. Identify what needs documentation
  2. Review existing documentation structure
  3. Follow documentation patterns
  4. 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

  1. Analyze code structure and patterns
  2. Check for:
    • Code consistency with existing patterns
    • Potential bugs or edge cases
    • Performance considerations
    • Type safety
    • Error handling
  3. 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

  1. Always review existing patterns first

    • Look at similar features in the codebase
    • Match naming conventions
    • Follow file structure patterns
  2. Generate complete, working code

    • Include all necessary imports
    • Add proper error handling
    • Include TypeScript types
  3. Consider the full stack

    • Database schema changes?
    • API endpoint needed?
    • Frontend component required?
    • Think through all layers
  4. Type safety first

    • Use Zod for runtime validation
    • Leverage TypeScript type inference
    • Avoid any types

For Bug Fixing

  1. Understand the root cause

    • Don't just fix symptoms
    • Trace the issue through the stack
    • Identify why it happened
  2. Consider edge cases

    • What if data is null/undefined?
    • What if the user is not authenticated?
    • What if concurrent operations occur?
  3. Suggest preventive measures

    • Add validation
    • Improve error handling
    • Recommend tests

For Testing

  1. Follow existing test patterns

    • Use the same test utilities
    • Match assertion styles
    • Follow file naming conventions
  2. Test behavior, not implementation

    • Focus on inputs and outputs
    • Test user-facing functionality
    • Avoid testing internal details
  3. Cover critical paths

    • Happy path
    • Error conditions
    • Edge cases
    • Authentication/authorization

For Documentation

  1. Be practical and actionable

    • Include code examples
    • Show actual usage
    • Explain the "why"
  2. Keep it current

    • Update when code changes
    • Mark deprecated features
    • Include version information
  3. 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

See examples/trpc-endpoint.md

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.

Reading this with an agent? /docs/ai-agents.md serves the raw markdown.

All docs