---
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](#overview)
- [Quick Start for AI Agents](#quick-start-for-ai-agents)
- [Codebase Understanding](#codebase-understanding)
- [Common Tasks](#common-tasks)
- [Patterns and Conventions](#patterns-and-conventions)
- [Best Practices](#best-practices)
- [Examples](#examples)
- [Resources](#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

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

```typescript
// 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

```typescript
// ❌ 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

```typescript
// 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

```typescript
/**
 * 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

```typescript
// 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

```typescript
// 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

```typescript
// 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

```typescript
// 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

```typescript
// 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](./examples/full-stack-feature.md)

### Example 2: Database Migration

See [examples/database-migration.md](./examples/database-migration.md)

### Example 3: tRPC Endpoint

See [examples/trpc-endpoint.md](./examples/trpc-endpoint.md)

### Example 4: React Component

See [examples/react-component.md](./examples/react-component.md)

---

## Resources

### AI Context Files

| File | Description |
|------|-------------|
| [`.ai/rules/repo.md`](../../.ai/rules/repo.md) | Repository structure and overview |
| [`.ai/rules/coding-patterns.md`](../../.ai/rules/coding-patterns.md) | Coding conventions and patterns |
| [`.ai/rules/architecture.md`](../../.ai/rules/architecture.md) | System architecture details |
| [`.ai/rules/workflows.md`](../../.ai/rules/workflows.md) | Development workflows |

### Documentation

| Section | Link |
|---------|------|
| Getting Started | [docs/getting-started/](../getting-started/README.md) |
| Architecture | [docs/architecture/](../architecture/README.md) |
| Frontend | [docs/frontend/](../frontend/README.md) |
| Backend | [docs/backend/](../backend/README.md) |
| API Reference | [docs/api-reference/](../api-reference/README.md) |

### External Documentation

- [Turborepo](https://turbo.build/repo/docs)
- [React Router v7](https://reactrouter.com)
- [tRPC](https://trpc.io/docs)
- [Drizzle ORM](https://orm.drizzle.team/docs/overview)
- [Hono](https://hono.dev/)
- [Shadcn UI](https://ui.shadcn.com/)

---

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 1.0.0 | 2025-01-10 | Initial AI agent guide |

---

**Next Steps**: Review the detailed [coding patterns](../../.ai/rules/coding-patterns.md) and explore the [examples](./examples/) to understand common implementation patterns.