bagsy/AGENTS.md

500 lines
17 KiB
Markdown

# ShopList — Full-Stack Monorepo Implementation Guide for AI Agents
## Overview
This is a **family shopping list app** built as a **Turborepo monorepo** with:
- **Backend**: Next.js 16 with better-auth, Drizzle ORM, OpenRouter AI
- **Frontend**: Expo 55 with Expo UI (SwiftUI on iOS, Jetpack Compose on Android), Zustand state management
- **Shared**: TypeScript types, ESLint + Prettier configuration
## Project Structure
```
/
├── packages/
│ └── types/ # Shared TypeScript types (User, Household, Store, Item, etc.)
├── apps/
│ ├── api/ # Next.js 16 backend (App Router, API routes only)
│ └── mobile/ # Expo 55 app (iOS & Android)
├── package.json # Workspace root, bun package manager
├── turbo.json # Turborepo pipeline config
├── tsconfig.json # Shared TypeScript config (strict mode)
├── .eslintrc.json # Workspace ESLint (flat config)
├── .prettierrc.json # Prettier formatting rules
└── AGENTS.md # This file
```
## Core Types (`@shop/types`)
**Location**: `packages/types/src/index.ts`
All types are exported from `@shop/types` and used by both backend and mobile:
- `User` — authenticated user with email, name, household
- `Household` — family/group (backed by better-auth `organization` table)
- `Store` — grocery store with location
- `Aisle` — store section with color theming
- `Item` — grocery item with optional barcode, aisle, alternatives
- `ListItem` — item in a shopping list with quantity, checked status, adder ID
- `ShoppingList` — shopping list for a household, preset/auto-reset support
- `ScanHistory` — barcode scan records for forgotten items analytics
- `ApiResponse<T>` — generic API response wrapper
## Backend (`@shop/api`)
**Location**: `apps/api/`
**Type**: Next.js 16 with App Router (API routes only, no frontend)
**Port**: 3001 (configurable)
### Database
**Technology**: PostgreSQL + Drizzle ORM
**Schema** (`db/schema.ts`):
- `stores` — household stores with locations
- `aisles` — store sections (order, hex color)
- `items` — grocery items (barcode, aisle, store, alternatives)
- `shopping_lists` — lists with preset/auto-reset flags
- `list_items` — items in lists (quantity, checked, adder, excluded from preset)
- `scan_history` — barcode scans for forgotten items
- `household_invite_codes` — 6-char join codes with expiry
**Additional tables** (managed by better-auth):
- `user`, `session`, `account` — user authentication
- `organization`, `member`, `invitation` — households + members (via organization plugin)
- `passkey`, `verification` — passkey & magic link data
**Setup**:
```bash
# Generate migrations from schema
bun db:generate
# Apply migrations to database
bun db:push
```
### Authentication
**Technology**: better-auth with plugins: organization, passkey, magicLink
**File**: `lib/auth.ts`
**Routes**:
- `/api/auth/[...all]` — catch-all handler for all auth endpoints
- `POST /api/auth/sign-up` — email + password registration
- `POST /api/auth/sign-in` — email + password login
- `POST /api/auth/sign-in/passkey` — WebAuthn passkey sign-in
- `POST /api/auth/passkey/add-passkey` — register new passkey
- `GET /api/auth/sign-in/magic-link` — magic link (currently stubbed, logs to console)
- Other organization/invitation endpoints auto-managed by better-auth
**Environment**:
- `BETTER_AUTH_SECRET` — encryption key (generate with `openssl rand -base64 32`)
- `BETTER_AUTH_URL` — origin URL (e.g., `http://localhost:3001`)
### API Endpoints
All endpoints require an authenticated session (via better-auth cookies). Implementation stubs are noted with `// TODO`.
#### Households (via better-auth organization plugin)
| Method | Route | Description |
| ------ | ----------------------------- | ------------------------------------- |
| `GET` | `/api/households` | Get active household for current user |
| `POST` | `/api/households` | Create new household |
| `POST` | `/api/households/invite-code` | Generate 6-char join code (custom) |
| `POST` | `/api/households/join` | Join household by code (custom) |
#### Stores
| Method | Route | Description |
| -------- | ------------------------------ | ------------------------- |
| `GET` | `/api/stores` | List stores for household |
| `POST` | `/api/stores` | Create new store |
| `GET` | `/api/stores/[id]` | Get store with aisles |
| `PUT` | `/api/stores/[id]` | Update store |
| `DELETE` | `/api/stores/[id]` | Delete store |
| `GET` | `/api/stores/[id]/aisles` | List aisles for store |
| `POST` | `/api/stores/[id]/aisles` | Add aisle |
| `PUT` | `/api/stores/[id]/aisles/[id]` | Update aisle |
| `DELETE` | `/api/stores/[id]/aisles/[id]` | Remove aisle |
#### Shopping Lists
| Method | Route | Description |
| -------- | ----------------------- | --------------------------------- |
| `GET` | `/api/lists` | List shopping lists for household |
| `POST` | `/api/lists` | Create new list |
| `GET` | `/api/lists/[id]` | Get list with items |
| `PUT` | `/api/lists/[id]` | Update list |
| `DELETE` | `/api/lists/[id]` | Delete list |
| `POST` | `/api/lists/[id]/reset` | Reset preset list with exclusions |
#### Items
| Method | Route | Description |
| -------- | ------------------------------ | ---------------------------------------------- |
| `GET` | `/api/items` | List items for household |
| `POST` | `/api/items` | Create new item |
| `GET` | `/api/items/[id]` | Get item |
| `PUT` | `/api/items/[id]` | Update item |
| `DELETE` | `/api/items/[id]` | Delete item |
| `GET` | `/api/items/search?q=` | **Stubbed** — search store website (mock data) |
| `GET` | `/api/items/barcode/[barcode]` | **Stubbed** — barcode lookup (mock data) |
| `GET` | `/api/items/forgotten` | Items not scanned in last 2 weeks |
#### Scan History
| Method | Route | Description |
| ------ | ------------------- | ---------------- |
| `POST` | `/api/scan-history` | Log barcode scan |
#### AI Suggestions
| Method | Route | Description |
| ------ | ----------------- | -------------------------------------------------- |
| `POST` | `/api/ai/suggest` | Get AI alternatives via OpenRouter + Vercel AI SDK |
**Body**:
```json
{ "itemName": "Milk" }
```
**Response**:
```json
{
"suggestions": [
{ "name": "Almond Milk", "reason": "Popular dairy-free alternative" },
{ "name": "Oat Milk", "reason": "Sustainable plant-based option" }
]
}
```
### AI Configuration
**Technology**: Vercel AI SDK + OpenRouter
**Model**: Configurable via OpenRouter (default: `anthropic/claude-3.5-haiku`)
**Environment**:
- `OPENROUTER_API_KEY` — API key for OpenRouter
- Or use Vercel AI Gateway with `AI_GATEWAY_API_KEY` (recommended for multi-provider flexibility)
**Implementation** (`app/api/ai/suggest/route.ts`):
```typescript
import { generateText } from 'ai';
import { openRouter } from '@ai-sdk/openrouter';
const { text } = await generateText({
model: openRouter('anthropic/claude-3.5-haiku'),
prompt: `Suggest 3 alternatives to "${itemName}"...`,
temperature: 0.7,
maxTokens: 200,
});
```
**Benefits**:
- No lock-in (swap models anytime)
- Centralized billing via OpenRouter
- Easy to test different models
## Mobile App (`@shop/mobile`)
**Location**: `apps/mobile/`
**Type**: Expo 55 (iOS + Android)
**Port**: Dev via `expo start`
### Technology Stack
- **Framework**: Expo 55 + Expo Router (file-based routing)
- **UI**: `@expo/ui/swift-ui` (iOS with Liquid Glass), `@expo/ui/jetpack-compose` (Android alpha) + React Native fallback
- **State**: Zustand (auth, lists, stores, items)
- **Auth**: better-auth with Expo client + passkey + organization plugins
- **Styling**: Native components (no Tailwind/NativeWind)
### Directory Structure
```
app/
├── _layout.tsx # Root layout (Expo Router)
├── index.tsx # Home screen (placeholder)
├── (auth)/ # Auth stack (not yet implemented)
│ ├── sign-in.tsx
│ ├── sign-up.tsx
│ ├── passkey-prompt.tsx
│ └── household.tsx
└── (app)/ # Main app stack (not yet implemented)
├── _layout.tsx
├── index.tsx # Home with lists + "don't forget"
├── list/
│ ├── [id].tsx # Main list (aisle swiper)
│ └── add-item.tsx # Add item sheet
├── stores/
│ ├── index.tsx
│ ├── new.tsx
│ └── [id]/aisles.tsx
└── settings.tsx
lib/
├── auth-client.ts # better-auth Expo client
└── api.ts # Central API fetch wrapper
store/
├── auth.ts # Zustand: user, session
├── lists.ts # Zustand: shopping lists + items
├── stores.ts # Zustand: stores + aisles
└── items.ts # Zustand: items + search results
assets/
├── icon.png
├── splash.png
├── adaptive-icon.png
└── favicon.png
```
### Environment
- `EXPO_PUBLIC_API_URL` — backend API URL (default: `http://localhost:3001`)
- `NODE_ENV` — `development` or `production`
### Key Screens (To Be Implemented)
#### Auth Stack
1. **Sign In** — Passkey primary (with autofill via Conditional UI), email+password fallback
2. **Sign Up** — Email + password registration
3. **Passkey Prompt** — Post-signup passkey registration (optional, skippable)
4. **Household** — Create new household or join existing by 6-char code
#### App Stack
1. **Home** —
- List of shopping lists (including presets separately)
- "Don't forget" section (items not bought in 2 weeks)
- FAB to create new list or start from preset
2. **Main List Screen** (core UX) —
- Horizontal aisle swiper (`FlatList` or PagerView)
- **Background**: absolutely positioned gradient using aisle colour (does NOT scroll)
- **Content**: items in aisle (only content scrolls horizontally)
- Dropdown to sort: by aisle (default), by category, by who added, alphabetical
- Check-off items: strike-through + opacity fade
- FAB opens bottom sheet: search items, barcode scan, manual entry
3. **Add Item Sheet** —
- Text search (hits `/api/items/search?q=`)
- Barcode scanner (`expo-camera`)
- Manual entry
4. **AI Alternatives** —
- Long-press item → bottom sheet with loading state
- Fetch from `/api/ai/suggest`
- Display as tappable chips
- Tap chip → swap item in list
5. **Barcode Flow** —
- Scan → `GET /api/items/barcode/[barcode]`
- If found: add to list
- If not: prompt for name, `POST /api/items` with barcode
- Log scan: `POST /api/scan-history`
6. **Store + Aisle Setup** —
- Store creation with `expo-location` pre-fill
- Aisle management: drag-to-reorder, colour picker
7. **Preset List Reset** —
- Modal with item checkboxes
- Selected → marked `excludedFromPreset: true`
- `POST /api/lists/[id]/reset` with excluded IDs
### UI Approach
**iOS** (`@expo/ui/swift-ui`):
- Full SwiftUI component support
- Liquid Glass effects on headers/cards via `glassEffect` modifier
- `Form`, `Section`, `List`, `HStack`, `VStack`, `Toggle`, `Button`, `Text`, `Image`
**Android** (`@expo/ui/jetpack-compose` + RN fallback):
- Use Jetpack Compose `Host` where available
- Fall back to standard React Native (`FlatList`, `TextInput`, `Pressable`, etc.)
- `Platform.select()` for branching
**Styling**:
- Native components (no Tailwind)
- Use `expo-blur` for transparency effects
- Use `expo-linear-gradient` for aisle background gradients
## Development Workflow
### Local Setup
```bash
# Install dependencies (bun is required)
bun install
# Set up environment files
cp apps/api/.env.example apps/api/.env.local
cp apps/mobile/.env.example apps/mobile/.env
# Set DATABASE_URL in apps/api/.env.local
# Set OPENROUTER_API_KEY in apps/api/.env.local
# Set EXPO_PUBLIC_API_URL in apps/mobile/.env
```
### Running the Apps
**Backend**:
```bash
cd apps/api
bun run db:push # Apply database migrations (one-time)
bun run dev # Start Next.js on port 3001
```
**Mobile**:
```bash
cd apps/mobile
bun run dev # Starts Expo on localhost:8081
# Scan QR code with Expo Go (iOS/Android)
# Or use: bun run dev:ios / bun run dev:android
```
### Workspace Commands
```bash
bun build # Build all packages
bun lint # Lint all packages
bun typecheck # Type-check all packages
bun format # Format all files
```
## Implementation Roadmap
### Phase 1: Scaffold ✅ (COMPLETE)
- [x] Monorepo with Turborepo + bun workspaces
- [x] Shared types package
- [x] Next.js API skeleton
- [x] Expo mobile skeleton
- [x] Database schema
- [x] ESLint + Prettier
### Phase 2: Backend Core (Next)
- [ ] better-auth integration & migration
- [ ] Drizzle ORM setup + migrations
- [ ] Implement `/api/auth/[...all]` handler
- [ ] Implement `/api/households/*` (organization plugin + custom join codes)
- [ ] Implement `/api/stores/*`
- [ ] Implement `/api/lists/*` with preset reset logic
- [ ] Implement `/api/items/*` (search & barcode stubs)
- [ ] Implement `/api/ai/suggest` (Vercel AI SDK + OpenRouter)
- [ ] Implement `/api/items/forgotten`
- [ ] Add error handling, logging, validation
### Phase 3: Mobile Auth & Navigation
- [ ] Implement auth stack (sign-up, sign-in, passkey, household)
- [ ] Set up Expo Router structure
- [ ] Integrate better-auth Expo client
- [ ] Implement session management (Zustand + better-auth)
- [ ] Add auth guards to routes
### Phase 4: Mobile Core Screens
- [ ] Home screen with lists + "don't forget"
- [ ] Main list screen (aisle swiper with fixed gradient)
- [ ] Add item sheet (search, barcode, manual)
- [ ] AI alternatives long-press sheet
- [ ] Barcode scanning flow
- [ ] Store + aisle setup
- [ ] Preset list reset modal
### Phase 5: Polish & Testing
- [ ] E2E tests (backend + mobile)
- [ ] Performance optimization
- [ ] Accessibility audit
- [ ] iOS build + App Store submission
- [ ] Android build + Play Store submission
## Important Notes for AI Agents
### Code Standards
- **TypeScript strict mode** throughout (no `any` types)
- **Error handling** — All API routes must validate auth, handle DB errors, return proper HTTP status codes
- **Logging** — Use `console.warn`, `console.error` for production debugging (console.log available for dev)
- **Types** — Import from `@shop/types` for shared types
- **Comments** — Document complex logic, especially AI/business logic
### API Response Format
Return JSON with this structure:
```typescript
{ data?: T, error?: { code: string, message: string } }
```
Status codes:
- `200` — Success
- `201` — Created
- `400` — Bad request
- `401` — Unauthorized
- `403` — Forbidden
- `404` — Not found
- `500` — Server error
### Stubbed Features
These routes should return mock data for now:
- `GET /api/items/search?q=` — Return hardcoded items matching query
- `GET /api/items/barcode/[barcode]` — Return mock item or 404
Comment with `// TODO: implement store scraping/API` or similar.
### Mobile UI Notes
- Prefer Expo UI components over React Native where available
- Use `Platform.select()` for iOS/Android branching
- Keep state in Zustand; call `api.get/post/put/delete()` from UI
- No hardcoded URLs — use `process.env.EXPO_PUBLIC_API_URL`
### Database Constraints
- Foreign keys with cascading deletes where appropriate
- Indexes on frequently queried columns (householdId, storeId, itemId)
- Timestamps on all tables for auditing
## Resources
- **Turborepo**: https://turbo.build
- **Next.js App Router**: https://nextjs.org/docs
- **better-auth**: https://www.better-auth.com
- **Drizzle ORM**: https://orm.drizzle.team
- **Expo**: https://docs.expo.dev
- **Expo UI**: https://docs.expo.dev/versions/latest/sdk/ui
- **Zustand**: https://github.com/pmndrs/zustand
- **Vercel AI SDK**: https://sdk.vercel.ai
- **OpenRouter**: https://openrouter.ai
## Contact
For questions about this architecture or implementation details, see AGENTS.md in the repo root.