link,[object Object]
Skip to content

AI Agent Guide โ€‹

Quick Reference & Navigation โ€‹

๐Ÿ“š Documentation Index โ€‹

  • Architecture: docs/architecture/overview.md - Technical stack and patterns
  • Data Model: docs/data-model/schema.md - Database tables and relationships
  • Features: docs/features/*.md - Feature-specific implementation guides
  • Setup: docs/setup/getting-started.md - Environment and installation
  • Performance: docs/performance.md - Optimization guidelines
  • Supabase: docs/setup/supabase.md - Backend configuration

โšก Pre-Modification Checklist โ€‹

Before making ANY changes, verify:

  • [ ] Read relevant feature documentation first
  • [ ] Check existing patterns in similar components
  • [ ] Understand current database schema via docs/data-model/
  • [ ] Verify RLS policies won't block your changes
  • [ ] Check if authentication is required for new features

๐ŸŽฏ Common Tasks Quick Index โ€‹

Adding New CRUD Feature โ€‹

  1. Database: Create migration via Supabase tool
  2. Types: Auto-generated after migration (don't edit manually)
  3. Hooks: Create TanStack Query hooks in src/hooks/
  4. Components: Create in appropriate src/components/ subdirectory
  5. Pages: Add to src/pages/ and route in AppRoutes.tsx
  6. Documentation: Update relevant docs/features/*.md

UI Component Creation โ€‹

  1. Base Components: Use src/components/ui/ (shadcn/ui)
  2. Custom Components: Create in feature-specific folders
  3. Styling: Use semantic tokens from index.css and tailwind.config.ts
  4. Responsiveness: Mobile-first approach required

Database Changes โ€‹

  1. Never edit src/integrations/supabase/types.ts directly
  2. Always use migration tool for schema changes
  3. RLS Policies: Required for user-specific data
  4. Testing: Verify policies work with different user roles

Safe Contribution Guidelines โ€‹

Core Principles โ€‹

  1. Never expose secrets - Always redact API keys, project IDs, and sensitive data
  2. Follow existing patterns - Study the codebase before making changes
  3. Maintain type safety - Use TypeScript strictly
  4. Respect conventions - Follow established naming and structure patterns

Secrets Redaction Rules โ€‹

Always Redact โ€‹

typescript
// โŒ NEVER expose
const SUPABASE_URL = 'https://nujcbrbtejvhuajfwgeo.supabase.co'
const STRIPE_SECRET = 'sk_live_...'

// โœ… Always redact
const SUPABASE_URL = 'https://YOUR_SUPABASE_PROJECT_REF.supabase.co'
const STRIPE_SECRET = 'YOUR_STRIPE_SECRET_KEY'

Safe to Include โ€‹

  • Environment variable names (not values)
  • Public configuration patterns
  • Type definitions
  • Component structures

Code Contribution Patterns โ€‹

1. Adding New Components โ€‹

typescript
// Pattern: Create in appropriate directory
// src/components/ui/          - Base UI components
// src/components/forms/       - Form-specific components
// src/components/layout/      - Layout components
// src/pages/                  - Page-level components

// Always use TypeScript interfaces
interface ComponentProps {
  title: string;
  onSave?: () => void;
}

export function NewComponent({ title, onSave }: ComponentProps) {
  // Implementation
}

2. Database Changes โ€‹

typescript
// NEVER modify src/integrations/supabase/types.ts directly
// Instead, create migrations in supabase/migrations/

// Example migration pattern:
CREATE TABLE new_feature (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES profiles(id),
  created_at TIMESTAMPTZ DEFAULT NOW()
);

ALTER TABLE new_feature ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can access own data" ON new_feature
  FOR ALL USING (user_id = auth.uid());

3. Adding Routes โ€‹

typescript
// Always add to src/components/routing/AppRoutes.tsx
// Follow existing patterns for protection:

// Public route
<Route path="/new-public" element={<AppLayout><NewPage /></AppLayout>} />

// Protected route
<Route 
  path="/new-protected" 
  element={
    <AppLayout>
      <ProtectedRoute>
        <NewProtectedPage />
      </ProtectedRoute>
    </AppLayout>
  } 
/>

// Admin route
<Route 
  path="/admin/new-admin" 
  element={
    <AppLayout>
      <AdminProtectedRoute>
        <NewAdminPage />
      </AdminProtectedRoute>
    </AppLayout>
  } 
/>

Automated Tasks You Can Safely Perform โ€‹

1. New CRUD Resource โ€‹

bash
# Safe steps:
# 1. Create Supabase migration for new table
# 2. Add route to AppRoutes.tsx
# 3. Create page component
# 4. Create form components
# 5. Add TanStack Query hooks
# 6. Update documentation

2. UI Component Creation โ€‹

typescript
// Safe pattern for new UI components:
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"

interface NewComponentProps {
  className?: string;
  children: React.ReactNode;
}

export function NewComponent({ className, children }: NewComponentProps) {
  return (
    <div className={cn("base-styles", className)}>
      {children}
    </div>
  )
}

3. Documentation Updates โ€‹

markdown
# Always update when adding features:
# - This file (docs/audiences/ai-agent.md)
# - Relevant feature docs (docs/features/*.md)
# - API documentation if adding endpoints
# - Update docs/changelog.md

Project Structure & Dependencies Guide โ€‹

๐Ÿ“ Directory Structure Explained โ€‹

src/
โ”œโ”€โ”€ components/         # Reusable UI components
โ”‚   โ”œโ”€โ”€ ui/            # shadcn/ui base components (Button, Input, etc.)
โ”‚   โ”œโ”€โ”€ layout/        # Layout components (Header, Footer, Sidebar)
โ”‚   โ”œโ”€โ”€ forms/         # Form-specific components
โ”‚   โ””โ”€โ”€ routing/       # Route definitions (AppRoutes.tsx)
โ”œโ”€โ”€ pages/             # Page components (one per route)
โ”œโ”€โ”€ hooks/             # Custom React hooks (API calls, state logic)
โ”œโ”€โ”€ contexts/          # React Context providers (auth, theme, etc.)
โ”œโ”€โ”€ lib/               # Utilities and configurations
โ”‚   โ”œโ”€โ”€ utils.ts       # Utility functions
โ”‚   โ””โ”€โ”€ validations.ts # Zod schemas
โ”œโ”€โ”€ integrations/      # External service integrations
โ”‚   โ””โ”€โ”€ supabase/      # Supabase client and types (AUTO-GENERATED)
โ””โ”€โ”€ types/             # TypeScript type definitions

๐Ÿ”ง Key Dependencies & Their Purpose โ€‹

  • @tanstack/react-query: Server state management (caching, mutations)
  • react-hook-form: Form handling and validation
  • zod: Schema validation
  • shadcn/ui: Pre-built accessible UI components
  • tailwindcss: Utility-first CSS framework
  • react-router-dom: Client-side routing
  • supabase: Backend-as-a-Service (database, auth, storage)

โš™๏ธ Configuration Files โ€‹

  • tailwind.config.ts: Design system tokens and component variants
  • index.css: Global styles and CSS variables (semantic tokens)
  • vite.config.ts: Build configuration and proxy setup
  • components.json: shadcn/ui configuration

Database & Supabase Patterns โ€‹

๐Ÿ—„๏ธ Database Best Practices โ€‹

Row Level Security (RLS) Patterns โ€‹

sql
-- โœ… CORRECT: Use security definer functions to avoid infinite recursion
CREATE OR REPLACE FUNCTION public.is_admin_user()
RETURNS boolean AS $$
  SELECT EXISTS (
    SELECT 1 FROM public.profiles
    WHERE id = auth.uid() AND role = 'admin'
  );
$$ LANGUAGE SQL SECURITY DEFINER STABLE;

-- โœ… CORRECT: Policy using the function
CREATE POLICY "Admins can view all" ON public.table_name
FOR SELECT USING (public.is_admin_user());

-- โŒ WRONG: Direct table reference causes infinite recursion
CREATE POLICY "Bad policy" ON public.profiles
FOR SELECT USING (
  (SELECT role FROM public.profiles WHERE id = auth.uid()) = 'admin'
);

Safe Query Patterns โ€‹

typescript
// โœ… CORRECT: Use maybeSingle() for single row queries
const { data, error } = await supabase
  .from('profiles')
  .select('*')
  .eq('id', userId)
  .maybeSingle();

// โŒ WRONG: single() throws if no row found
const { data, error } = await supabase
  .from('profiles')
  .select('*')
  .eq('id', userId)
  .single();

Migration Workflow โ€‹

  1. Always use the Supabase migration tool
  2. Never edit src/integrations/supabase/types.ts manually
  3. Test RLS policies with different user roles
  4. Backup data before schema changes

๐Ÿ” Authentication Patterns โ€‹

typescript
// โœ… CORRECT: Check auth state before mutations
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
  throw new Error('Authentication required');
}

// โœ… CORRECT: Handle auth state in components
const { user, loading } = useAuth();
if (loading) return <Loading />;
if (!user) return <LoginPrompt />;

What NOT to Modify โ€‹

Protected Files โ€‹

bash
# NEVER modify these:
package.json                          # Dependency management
src/integrations/supabase/types.ts   # Auto-generated
.env                                  # Contains secrets
supabase/migrations/*                 # Historical migrations

Dangerous Patterns โ€‹

typescript
// โŒ NEVER do direct SQL in frontend
const result = await supabase.rpc('execute_sql', { 
  query: 'DROP TABLE users' 
})

// โŒ NEVER hardcode secrets
const apiKey = 'sk_live_actual_key_here'

// โŒ NEVER modify auth schema
ALTER TABLE auth.users ADD COLUMN custom_field TEXT

// โœ… DO use proper patterns
const { data } = await supabase.from('table').select()
const apiKey = process.env.VITE_PUBLIC_API_KEY  // Only for public keys
// Create custom tables that reference auth.users

Frontend Development Guidelines โ€‹

โš›๏ธ React Patterns & State Management โ€‹

Component Structure โ€‹

typescript
// โœ… CORRECT: Well-structured component
interface ComponentProps {
  title: string;
  onSave?: () => void;
  className?: string;
}

export function Component({ title, onSave, className }: ComponentProps) {
  const [isLoading, setIsLoading] = useState(false);
  
  return (
    <div className={cn("base-styles", className)}>
      {/* Component content */}
    </div>
  );
}

Custom Hooks Pattern โ€‹

typescript
// โœ… CORRECT: Custom hook for API operations
export function useListings() {
  return useQuery({
    queryKey: ['listings'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('listings')
        .select('*')
        .eq('status', 'active');
      
      if (error) throw error;
      return data;
    },
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

State Management Hierarchy โ€‹

  1. Server State: TanStack Query (API data, caching)
  2. Form State: react-hook-form (form validation, submission)
  3. Component State: useState (local UI state)
  4. Global State: React Context (auth, theme, language)

๐ŸŽจ Styling Guidelines โ€‹

Semantic Token Usage โ€‹

typescript
// โœ… CORRECT: Use semantic tokens from design system
<Button variant="primary" size="lg">
  Save Changes
</Button>

// โœ… CORRECT: Use CSS variables for custom styles
<div className="bg-background text-foreground border border-border">
  Content
</div>

// โŒ WRONG: Direct color usage
<div className="bg-blue-500 text-white border-gray-300">
  Content
</div>

Responsive Design Pattern โ€‹

typescript
// โœ… CORRECT: Mobile-first responsive classes
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
  {/* Grid items */}
</div>

QA & Performance Guidelines โ€‹

๐Ÿงช Testing Checklist โ€‹

Before Submitting Changes โ€‹

  • [ ] Functionality: Feature works as expected
  • [ ] Responsive: Mobile and desktop layouts work
  • [ ] Accessibility: Proper ARIA labels and keyboard navigation
  • [ ] Performance: No unnecessary re-renders or API calls
  • [ ] Error Handling: Graceful error states displayed
  • [ ] Loading States: Appropriate loading indicators
  • [ ] Authentication: Proper auth checks for protected features

Database Testing โ€‹

  • [ ] RLS Policies: Test with different user roles
  • [ ] Data Validation: Invalid data is rejected
  • [ ] Relationships: Foreign keys work correctly
  • [ ] Performance: Queries use appropriate indexes

๐Ÿš€ Performance Best Practices โ€‹

Query Optimization โ€‹

typescript
// โœ… CORRECT: Select only needed columns
const { data } = await supabase
  .from('listings')
  .select('id, title, price, main_image')
  .limit(20);

// โŒ WRONG: Select all columns unnecessarily
const { data } = await supabase
  .from('listings')
  .select('*');

Component Optimization โ€‹

typescript
// โœ… CORRECT: Memoize expensive calculations
const expensiveValue = useMemo(() => {
  return heavyCalculation(data);
}, [data]);

// โœ… CORRECT: Debounce search inputs
const debouncedSearch = useDebounce(searchTerm, 300);

Bundle Optimization โ€‹

  • Code Splitting: Lazy load heavy components
  • Tree Shaking: Import only used utilities
  • Image Optimization: Use appropriate formats and sizes

๐Ÿ› Debugging Procedures โ€‹

Error Investigation Steps โ€‹

  1. Console Logs: Check browser console for errors
  2. Network Tab: Verify API requests and responses
  3. React DevTools: Inspect component state and props
  4. Supabase Logs: Check database query errors
  5. Authentication: Verify user auth state

Common Error Patterns โ€‹

  • RLS Violations: Check user permissions and policy conditions
  • Type Errors: Verify data types match interface definitions
  • Query Errors: Check column names and table relationships
  • Infinite Loops: Look for dependencies in useEffect hooks

Step-by-Step Task Templates โ€‹

Template: Adding New Feature โ€‹

  1. Analysis Phase:

    • Read existing similar features
    • Identify required database changes
    • Plan component structure
  2. Database Phase:

    • Create migration file
    • Add RLS policies
    • Test locally
  3. Frontend Phase:

    • Add route
    • Create page component
    • Add data hooks
    • Create UI components
  4. Documentation Phase:

    • Update relevant docs
    • Add to changelog
    • Update this guide if needed

Template: Bug Fix โ€‹

  1. Investigation:

    • Check console errors
    • Review related code
    • Identify root cause
  2. Fix Implementation:

    • Make minimal necessary changes
    • Maintain existing patterns
    • Add error handling
  3. Verification:

    • Test fix locally
    • Check for side effects
    • Update tests if needed

Documentation Maintenance โ€‹

When to Update Docs โ€‹

  • Adding new features
  • Changing existing functionality
  • Discovering new patterns
  • Fixing documentation errors

Documentation Priorities โ€‹

  1. High: API changes, new features, security updates
  2. Medium: UI changes, performance improvements
  3. Low: Minor bug fixes, code organization

Step-by-Step Task Templates โ€‹

Template: Adding New Feature โ€‹

  1. Analysis Phase:

    • Read existing similar features
    • Identify required database changes
    • Plan component structure
  2. Database Phase:

    • Create migration file
    • Add RLS policies
    • Test locally
  3. Frontend Phase:

    • Add route
    • Create page component
    • Add data hooks
    • Create UI components
  4. Documentation Phase:

    • Update relevant docs
    • Add to changelog
    • Update this guide if needed

Template: Bug Fix โ€‹

  1. Investigation:

    • Check console errors
    • Review related code
    • Identify root cause
  2. Fix Implementation:

    • Make minimal necessary changes
    • Maintain existing patterns
    • Add error handling
  3. Verification:

    • Test fix locally
    • Check for side effects
    • Update tests if needed

Documentation Maintenance โ€‹

When to Update Docs โ€‹

  • Adding new features
  • Changing existing functionality
  • Discovering new patterns
  • Fixing documentation errors

Documentation Priorities โ€‹

  1. High: API changes, new features, security updates
  2. Medium: UI changes, performance improvements
  3. Low: Minor bug fixes, code organization

Remember: When in doubt, ask for clarification rather than making assumptions. The codebase has established patterns that should be followed consistently.