---
description: Quick start guide for AI agents working with Izri
version: 1.0.0
lastUpdated: 2025-01-10
tags: [ai-agent, quick-start, reference, cheatsheet]
priority: high
---

# AI Agent Quick Start Guide

**For AI agents**: This is your TL;DR guide to get productive quickly with the Izri codebase.

---

## 🚀 First Steps (Load These First)

1. **Essential Context Files** (Always load before any task):
   ```
   .ai/rules/repo.md              # Repository structure
   .ai/rules/coding-patterns.md   # Coding conventions
   .ai/rules/architecture.md      # System design
   .ai/rules/workflows.md         # Development workflows
   .ai/rules/ai-agent-config.md   # AI agent guidelines
   ```

2. **Quick Reference**:
   ```
   docs/QUICK_REFERENCE.md        # Human quick reference
   docs/ai-agents/QUICK_START.md  # This file (AI quick reference)
   ```

---

## 📂 File Locations Cheat Sheet

| Need to... | Look in... |
|------------|------------|
| Add database table | `packages/database/src/schema.ts` |
| Create API endpoint | `packages/trpc/src/routers/*.ts` |
| Add frontend component | `apps/web/app/components/features/*.tsx` |
| Create custom hook | `apps/web/app/hooks/*.ts` |
| Add validation | `packages/shared/src/validation/*.ts` |
| Write tests | `*/__tests__/*.test.ts` |
| Update docs | `docs/**/*.md` |

---

## 🎯 Common Task Templates

### Task: Add New Feature

```
Step 1: Database Schema
  → packages/database/src/schema.ts

Step 2: Validation Schemas
  → packages/shared/src/validation/

Step 3: tRPC Router
  → packages/trpc/src/routers/

Step 4: Frontend Hook
  → apps/web/app/hooks/

Step 5: React Component
  → apps/web/app/components/features/

Step 6: Tests
  → All above folders + __tests__/
```

### Task: Fix Bug

```
Step 1: Identify Location
  → Read error stack trace
  
Step 2: Understand Context
  → Load relevant code files
  
Step 3: Propose Fix
  → Show before/after code
  
Step 4: Add Test
  → Prevent regression
```

### Task: Write Tests

```
Step 1: Identify Test Type
  → Unit (single function)
  → Integration (tRPC endpoint)
  → Component (React component)

Step 2: Create Test File
  → */__tests__/*.test.ts(x)

Step 3: Follow Pattern
  → Use existing tests as template
```

---

## 💻 Code Templates

### tRPC Query

```typescript
export const router = router({
  getById: protectedProcedure
    .input(z.object({ id: z.string().ulid() })) // ULID validation
    .query(async ({ ctx, input }) => {
      const item = await ctx.db.query.table.findFirst({
        where: eq(table.id, input.id),
      });
      
      if (!item) throw new TRPCError({ code: 'NOT_FOUND' });
      if (item.userId !== ctx.user.id) throw new TRPCError({ code: 'FORBIDDEN' });
      
      return item;
    }),
});
```

### tRPC Mutation

```typescript
export const router = router({
  create: protectedProcedure
    .input(createSchema)
    .mutation(async ({ ctx, input }) => {
      const [item] = await ctx.db
        .insert(table)
        .values({ ...input, userId: ctx.user.id })
        .returning();
      
      return item;
    }),
});
```

### React Component

```typescript
interface ComponentProps {
  data: Type;
  onAction?: (id: string) => void;
}

export function Component({ data, onAction }: ComponentProps) {
  const { data: queryData, isLoading } = trpc.router.query.useQuery({ id: data.id });
  const mutation = trpc.router.mutation.useMutation();
  
  if (isLoading) return <div>Loading...</div>;
  
  return <div>{/* Component JSX */}</div>;
}
```

### Custom Hook

```typescript
export function useData(id: string) {
  return trpc.router.getById.useQuery(
    { id },
    { enabled: !!id }
  );
}

export function useCreateData() {
  const utils = trpc.useUtils();
  return trpc.router.create.useMutation({
    onSuccess: () => {
      utils.router.list.invalidate();
    },
  });
}
```

---

## 🔍 Quick Debugging

### TypeScript Error?
```
1. Check import paths (use @izri/* for packages)
2. Verify types are exported from schema
3. Check if file is in tsconfig include paths
```

### tRPC Error?
```
1. Verify input schema (Zod validation)
2. Check authorization (user.id checks)
3. Confirm database query syntax
```

### React Error?
```
1. Check props interface
2. Verify hook dependencies array
3. Ensure proper conditional rendering
```

### Database Error?
```
1. Run migrations (pnpm db:migrate)
2. Check schema matches database
3. Verify foreign key relationships
```

---

## 🧪 Testing Quick Reference

### Test Structure (AAA Pattern)

```typescript
it('should do something', async () => {
  // Arrange
  const ctx = await createTestContext({ authenticated: true });
  const caller = appRouter.createCaller(ctx);
  
  // Act
  const result = await caller.router.action(input);
  
  // Assert
  expect(result).toMatchObject({ expected: 'value' });
});
```

### Common Test Assertions

```typescript
expect(value).toBe(expected)           // Exact equality
expect(value).toEqual(expected)        // Deep equality
expect(value).toMatchObject({ })       // Partial match
expect(value).toHaveLength(n)          // Array/string length
expect(fn).toThrow('message')          // Function throws
expect(fn).toHaveBeenCalledWith(args)  // Mock called with args
```

---

## ⚡ Commands Cheat Sheet

```bash
# Development
pnpm install          # Install dependencies
pnpm dev              # Start all dev servers
pnpm dev:web          # Start only frontend
pnpm dev:api          # Start only backend

# Database
pnpm db:generate      # Generate migration
pnpm db:migrate       # Apply migrations
pnpm db:studio        # Open Drizzle Studio
pnpm db:seed          # Seed database

# Testing
pnpm test             # Run all tests
pnpm test:watch       # Run tests in watch mode
pnpm test:trpc        # Run tRPC tests only

# Building
pnpm build            # Build all packages
pnpm typecheck        # Check TypeScript
pnpm lint             # Run linter
pnpm format           # Format code

# Docker
pnpm docker:up        # Start services
pnpm docker:down      # Stop services
pnpm docker:logs      # View logs
```

---

## 🎨 Styling Quick Reference

### Tailwind Classes (Common Patterns)

```tsx
// Layout
<div className="flex items-center justify-between gap-4">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div className="container mx-auto px-4 py-8">

// Spacing
className="p-4"    // padding all sides
className="px-4"   // padding horizontal
className="py-4"   // padding vertical
className="space-y-4"  // vertical spacing between children

// Typography
className="text-lg font-semibold text-gray-900"
className="text-sm text-gray-500"

// Interactive
className="hover:bg-gray-100 cursor-pointer transition-colors"
```

### Shadcn UI Components

```tsx
import { Button } from '~/components/ui/button';
import { Input } from '~/components/ui/input';
import { Card, CardHeader, CardTitle, CardContent } from '~/components/ui/card';
import { Dialog, DialogContent, DialogTitle } from '~/components/ui/dialog';
```

---

## ⚠️ Common Pitfalls to Avoid

| ❌ Don't | ✅ Do |
|---------|------|
| `const project = await db.select()...` | `const [project] = await db.select()...` |
| `throw new Error('message')` | `throw new TRPCError({ code: 'NOT_FOUND' })` |
| `input: z.string()` | `input: z.object({ id: z.string().ulid() })` |
| `export default function Component` | `export function Component` |
| `const [data, setData] = useState<any>()` | `const [data, setData] = useState<Type>()` |
| Key={index} | Key={item.id} |

---

## 📊 Decision Tree

### "Which file should I modify?"

```
Need to change data structure?
  → packages/database/src/schema.ts

Need to add API logic?
  → packages/trpc/src/routers/*.ts

Need to add frontend logic?
  → apps/web/app/hooks/*.ts

Need to add UI?
  → apps/web/app/components/features/*.tsx

Need to add validation?
  → packages/shared/src/validation/*.ts

Need to add tests?
  → */__tests__/*.test.ts(x)
```

### "Should I ask before proceeding?"

```
Is this a breaking change?          → YES, ASK
Does this affect security?          → YES, ASK
Does this change core architecture? → YES, ASK
Am I less than 80% confident?       → YES, ASK
Is this a simple bug fix?           → NO, PROCEED
Is this following existing patterns?→ NO, PROCEED
```

---

## 🔗 Quick Links

### Essential Documentation
- [Full AI Agent Guide](./README.md)
- [Repository Overview](./../.ai/rules/repo.md)
- [Architecture](./../.ai/rules/architecture.md)
- [Coding Patterns](./../.ai/rules/coding-patterns.md)
- [Workflows](./../.ai/rules/workflows.md)

### Example Code
- [Full Stack Feature](./examples/full-stack-feature.md)
- [Database Migration](./examples/database-migration.md)
- [tRPC Endpoint](./examples/trpc-endpoint.md)
- [React Component](./examples/react-component.md)

### External Docs
- [tRPC](https://trpc.io/docs)
- [Drizzle ORM](https://orm.drizzle.team/docs/overview)
- [React Router v7](https://reactrouter.com)
- [Shadcn UI](https://ui.shadcn.com/)
- [Zod](https://zod.dev/)

---

## 📝 Response Format Template

When responding to user requests:

```markdown
## Analysis
[Brief understanding of the task]

## Proposed Solution
[High-level approach]

## Implementation

### Step 1: [Component]
File: `path/to/file.ts`
```typescript
// Code here
```

### Step 2: [Next Component]
File: `path/to/file.ts`
```typescript
// Code here
```

## Testing
[Test strategy]

## Questions
[Any clarifications needed]
```

---

## 🎓 Learning Resources

**First Time with This Stack?**

1. Start with: [Full Stack Feature Example](./examples/full-stack-feature.md)
2. Study: [Coding Patterns](./../.ai/rules/coding-patterns.md)
3. Review: [Architecture](./../.ai/rules/architecture.md)
4. Practice: Pick a simple feature and implement it

**Need to Deep Dive?**

- Frontend → [docs/frontend/](../frontend/)
- Backend → [docs/backend/](../backend/)
- Database → [docs/packages/database-package.md](../packages/database-package.md)
- Testing → [docs/development/testing.md](../development/testing.md)

---

## 🚦 Status Indicators

Use these in your responses:

- ✅ **High Confidence**: Proceed independently
- ⚠️ **Medium Confidence**: Proceed with caveats
- ❓ **Low Confidence**: Ask for clarification
- 🔴 **Requires Approval**: Wait for confirmation

---

## 📖 Version Info

- **Document Version**: 1.0.0
- **Last Updated**: 2025-01-10
- **Codebase Version**: Check package.json files
- **Stack Versions**: Node 18+, React 19, tRPC 11

---

**Remember**: When in doubt, ASK. Better to clarify than to implement incorrectly.

**Golden Rule**: Follow existing patterns. If similar code exists, match its style and structure.

---

**Quick Checklist Before Responding**:
- [ ] Loaded essential context files
- [ ] Understood the requirement
- [ ] Checked for existing similar implementations
- [ ] Confidence level >= 80% OR asked for clarification
- [ ] Followed coding patterns
- [ ] Included error handling
- [ ] Suggested tests
- [ ] Provided clear explanation

---

*This is a living document. As you work with the codebase, patterns will become clearer.*