Appearance
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 โ
- Database: Create migration via Supabase tool
- Types: Auto-generated after migration (don't edit manually)
- Hooks: Create TanStack Query hooks in
src/hooks/ - Components: Create in appropriate
src/components/subdirectory - Pages: Add to
src/pages/and route inAppRoutes.tsx - Documentation: Update relevant
docs/features/*.md
UI Component Creation โ
- Base Components: Use
src/components/ui/(shadcn/ui) - Custom Components: Create in feature-specific folders
- Styling: Use semantic tokens from
index.cssandtailwind.config.ts - Responsiveness: Mobile-first approach required
Database Changes โ
- Never edit
src/integrations/supabase/types.tsdirectly - Always use migration tool for schema changes
- RLS Policies: Required for user-specific data
- Testing: Verify policies work with different user roles
Safe Contribution Guidelines โ
Core Principles โ
- Never expose secrets - Always redact API keys, project IDs, and sensitive data
- Follow existing patterns - Study the codebase before making changes
- Maintain type safety - Use TypeScript strictly
- 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 documentation2. 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.mdProject 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 variantsindex.css: Global styles and CSS variables (semantic tokens)vite.config.ts: Build configuration and proxy setupcomponents.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 โ
- Always use the Supabase migration tool
- Never edit
src/integrations/supabase/types.tsmanually - Test RLS policies with different user roles
- 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 migrationsDangerous 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.usersFrontend 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 โ
- Server State: TanStack Query (API data, caching)
- Form State: react-hook-form (form validation, submission)
- Component State: useState (local UI state)
- 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 โ
- Console Logs: Check browser console for errors
- Network Tab: Verify API requests and responses
- React DevTools: Inspect component state and props
- Supabase Logs: Check database query errors
- 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 โ
Analysis Phase:
- Read existing similar features
- Identify required database changes
- Plan component structure
Database Phase:
- Create migration file
- Add RLS policies
- Test locally
Frontend Phase:
- Add route
- Create page component
- Add data hooks
- Create UI components
Documentation Phase:
- Update relevant docs
- Add to changelog
- Update this guide if needed
Template: Bug Fix โ
Investigation:
- Check console errors
- Review related code
- Identify root cause
Fix Implementation:
- Make minimal necessary changes
- Maintain existing patterns
- Add error handling
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 โ
- High: API changes, new features, security updates
- Medium: UI changes, performance improvements
- Low: Minor bug fixes, code organization
Step-by-Step Task Templates โ
Template: Adding New Feature โ
Analysis Phase:
- Read existing similar features
- Identify required database changes
- Plan component structure
Database Phase:
- Create migration file
- Add RLS policies
- Test locally
Frontend Phase:
- Add route
- Create page component
- Add data hooks
- Create UI components
Documentation Phase:
- Update relevant docs
- Add to changelog
- Update this guide if needed
Template: Bug Fix โ
Investigation:
- Check console errors
- Review related code
- Identify root cause
Fix Implementation:
- Make minimal necessary changes
- Maintain existing patterns
- Add error handling
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 โ
- High: API changes, new features, security updates
- Medium: UI changes, performance improvements
- 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.