bagsy/AGENTS.md
bananabas 88701de549 chore: clean up project structure
- Remove duplicate iOS app folder (ShopList/ → consolidated to Bagsy/)
- Remove build artifacts from git tracking
- Remove stale documentation files
- Remove old React Native mobile code
- Add PROJECT_STATUS.md for clear project overview

iOS app is now clearly organized under apps/ios/Bagsy/ with single Xcode project (Bagsy.xcodeproj)
2026-04-13 17:16:11 +01:00

506 lines
18 KiB
Markdown

# Bagsy — 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**: Native Swift/SwiftUI iOS app (no cross-platform overhead)
- **Shared**: TypeScript types for backend + iOS interop
## Project Structure
```
/
├── packages/
│ └── types/ # Shared TypeScript types (User, Household, Store, Item, etc.)
├── apps/
│ ├── api/ # Next.js 16 backend (App Router, API routes only)
│ └── ios/ # Native Swift iOS app (Xcode project)
│ └── Bagsy/ShopList/
│ ├── App/ # AppState, lifecycle, root view
│ ├── Core/ # API client, Keychain, Cache, WebSocket, Theme
│ ├── Features/ # Auth, Lists, Stores screen implementations
│ └── Models/ # Swift data models
├── 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 (Native iOS)
**Location**: `apps/ios/Bagsy/`
**Type**: Native Swift/SwiftUI (Xcode project)
**Target**: iOS 15+
### Technology Stack
- **Language**: Swift 5.9+
- **UI**: SwiftUI + Combine
- **HTTP**: URLSession (native)
- **Storage**: Keychain (secure credentials), Core Data (local cache)
- **Real-time**: WebSocket via URLSessionWebSocketTask
- **Auth**: Passkey via AuthenticationServices (Face ID / Touch ID)
- **Async**: async/await (Swift concurrency)
### Directory Structure
```swift
Bagsy/ShopList/
├── App/
│ ├── AppState.swift # Main app state, session, auth flow
│ ├── BagsyApp.swift # @main entry point
│ └── RootView.swift # Root navigation based on auth state
│
├── Core/
│ ├── API/
│ │ ├── APIClient.swift # URLSession wrapper, auth headers
│ │ └── APIModels.swift # API response/request types
│ ├── Storage/
│ │ ├── KeychainManager.swift # Passkey credentials, tokens
│ │ └── CacheManager.swift # Local list/store caching
│ ├── WebSocket/
│ │ ├── WebSocketManager.swift # Real-time sync
│ │ └── WebSocketMessage.swift # Message types
│ └── Theme/
│ ├── AppTheme.swift # Colors, spacing, design system
│ └── AppColors.swift # Dark/light mode palettes
│
├── Features/
│ ├── Auth/
│ │ ├── SignInView.swift # Email + passkey sign-in
│ │ ├── SignUpView.swift # Email + password registration
│ │ ├── HouseholdSetupView.swift # Create/join household
│ │ └── PasskeyManager.swift # AuthenticationServices wrapper
│ │
│ ├── Lists/
│ │ ├── ShoppingListView.swift # Main list (aisle tabs)
│ │ ├── ListItemView.swift # Item detail + AI suggestions
│ │ └── AddItemSheet.swift # Search, barcode, manual entry
│ │
│ └── Stores/
│ ├── StoresView.swift # Store list + management
│ ├── AislePickerView.swift # Aisle selection for items
│ └── StoreDetailView.swift # Store + aisles
│
└── Models/
├── User.swift
├── Household.swift
├── Store.swift
├── ShoppingList.swift
├── Item.swift
└── ListItem.swift
```
### Key Features Implemented
**Auth Flow**:
- Passkey (Face ID / Touch ID) via `AuthenticationServices`
- Email + password registration & sign-in
- Household creation & 6-char join codes
- Session management (stores token in Keychain)
**Shopping Lists**:
- Real-time sync via WebSocket
- Aisle-based organization (horizontal tabs)
- Item check-off with strike-through
- Preset lists with "don't forget" analytics
**Stores & Aisles**:
- Custom store creation
- Drag-to-reorder aisles
- Color theming per aisle
**AI Suggestions**:
- Long-press item → fetch alternatives from `/api/ai/suggest`
- Display as tappable chips
- Tap to swap in list
**Barcode Scanning** (infrastructure ready):
- Camera integration layer prepared
- Ready to implement Vision + ML Kit flow
### Environment Variables
Set in `AppState.swift` or config file:
```swift
let serverURL = URL(string: "http://192.168.x.x:3001")!
```
Change to production URL for App Store builds.
## 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
# Set DATABASE_URL in apps/api/.env.local
# Set OPENROUTER_API_KEY in apps/api/.env.local (optional)
```
### 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
# Prints local network IP: http://192.168.x.x:3001
```
**iOS App**:
```bash
cd apps/ios/Bagsy
open Bagsy.xcodeproj
# Cmd+R in Xcode to build and run
# Update serverURL in AppState.swift to match backend IP
```
### Workspace Commands
```bash
bun build # Build backend
bun lint # Lint backend TypeScript
bun typecheck # Type-check backend
bun format # Format all files
```
**Note**: iOS app build is controlled by Xcode, not bun.
## Implementation Roadmap
### Phase 1: Scaffold ✅ (COMPLETE)
- [x] Monorepo with Turborepo + bun workspaces
- [x] Shared types package
- [x] Next.js API skeleton
- [x] Native Swift iOS app (Xcode project)
- [x] Database schema (PostgreSQL + Drizzle)
- [x] ESLint + Prettier
### Phase 2: Backend Core ✅ (MOSTLY COMPLETE)
- [x] Better-auth setup (passkey, organization, magicLink)
- [x] Drizzle ORM + migrations
- [x] Auth handler (`/api/auth/[...all]`)
- [x] Households API (organization + custom join codes)
- [x] Stores API
- [x] Lists API with preset reset
- [ ] Items API (search & barcode stubs — awaiting implementation)
- [x] AI suggestions (`/api/ai/suggest`)
- [x] Items forgotten analytics
- [ ] Error handling & validation (ongoing)
### Phase 3: iOS Auth & Navigation ✅ (COMPLETE)
- [x] Auth stack (sign-in, sign-up, passkey, household)
- [x] SwiftUI navigation (tab-based + sheet flows)
- [x] Better-auth session management (Keychain + AppState)
- [x] Protected routes via AppState.session
- [x] Passkey manager (AuthenticationServices wrapper)
### Phase 4: iOS Core Screens ✅ (FEATURE COMPLETE)
- [x] Home screen (lists + "don't forget")
- [x] Main list screen (aisle tabs with SwiftUI ScrollViewReader)
- [x] Add item sheet (search, barcode infrastructure, manual)
- [x] AI alternatives (long-press → bottom sheet)
- [x] Barcode scanning (camera integration ready)
- [x] Store + aisle management
- [x] Preset list reset modal
### Phase 5: Polish & Testing (IN PROGRESS)
- [ ] Barcode scanning implementation (Vision + ML Kit)
- [ ] Comprehensive error handling + user feedback
- [ ] Performance profiling (Instruments)
- [ ] Accessibility audit (VoiceOver)
- [ ] iOS TestFlight + App Store submission
- [ ] Production deployment (Railway / Render)
## Important Notes for AI Agents
### Backend 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
### Passkey Setup (FIXED)
**Fixed in v1.1.4**:
- Passkey plugin now imported from `better-auth/plugins` (was wrongly from `@better-auth/passkey`)
- `baseURL` is now set in betterAuth config (was missing, causing rpID derivation failures)
- See `apps/api/lib/auth.ts` for reference
### Backend Stubbed Features
These routes return mock data:
- `GET /api/items/search?q=` — Return hardcoded items matching query
- `GET /api/items/barcode/[barcode]` — Return mock item or 404
Implement actual store/barcode APIs when needed.
### iOS Code Standards (Swift)
- **Swift strict mode** — No force unwraps in production code (use `guard`/`if let`)
- **Async/await** — Use Swift concurrency, not completion handlers
- **Memory safety** — Watch for reference cycles in Combine subscriptions
- **Keychain** — All sensitive data (tokens, credentials) stored in Keychain, never UserDefaults
- **URLSession** — Always set request timeout to 30s, handle network errors gracefully
- **SwiftUI** — Use `@EnvironmentObject` for global state (AppState)
- **Comments** — Document especially around concurrency, async operations
### iOS App Notes
- Update `serverURL` in `AppState.swift` for different environments (dev/prod)
- Keychain is device-locked and cleared on uninstall
- WebSocket reconnection is automatic (see `WebSocketManager.swift`)
- Passkey credentials are never stored — AuthenticationServices handles them
- Use the native dark mode (Settings → Display & Brightness)
### Database Constraints
- Foreign keys with cascading deletes where appropriate
- Indexes on frequently queried columns (householdId, storeId, itemId)
- Timestamps on all tables for auditing
- PostgreSQL required (SQLite doesn't support passkey tables)
## Resources
### Backend
- **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
- **Vercel AI SDK**: https://sdk.vercel.ai
- **OpenRouter**: https://openrouter.ai
### iOS
- **SwiftUI**: https://developer.apple.com/swiftui/
- **Combine**: https://developer.apple.com/combine/
- **AuthenticationServices**: https://developer.apple.com/documentation/authenticationservices
- **URLSession**: https://developer.apple.com/documentation/foundation/urlsession
- **Keychain Services**: https://developer.apple.com/documentation/security/keychain_services
### Project Docs
- **README.md** — Quick start, local setup, deployment
- **docs/WEBSOCKET_SYNC.md** — Real-time sync architecture
- **docs/iOS_SIDELOADING_GUIDE.md** — TestFlight + App Store submission