- 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)
18 KiB
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, householdHousehold— family/group (backed by better-authorganizationtable)Store— grocery store with locationAisle— store section with color themingItem— grocery item with optional barcode, aisle, alternativesListItem— item in a shopping list with quantity, checked status, adder IDShoppingList— shopping list for a household, preset/auto-reset supportScanHistory— barcode scan records for forgotten items analyticsApiResponse<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 locationsaisles— store sections (order, hex color)items— grocery items (barcode, aisle, store, alternatives)shopping_lists— lists with preset/auto-reset flagslist_items— items in lists (quantity, checked, adder, excluded from preset)scan_history— barcode scans for forgotten itemshousehold_invite_codes— 6-char join codes with expiry
Additional tables (managed by better-auth):
user,session,account— user authenticationorganization,member,invitation— households + members (via organization plugin)passkey,verification— passkey & magic link data
Setup:
# 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 endpointsPOST /api/auth/sign-up— email + password registrationPOST /api/auth/sign-in— email + password loginPOST /api/auth/sign-in/passkey— WebAuthn passkey sign-inPOST /api/auth/passkey/add-passkey— register new passkeyGET /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 withopenssl 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:
{ "itemName": "Milk" }
Response:
{
"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):
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
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:
let serverURL = URL(string: "http://192.168.x.x:3001")!
Change to production URL for App Store builds.
Development Workflow
Local Setup
# 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:
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:
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
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)
- Monorepo with Turborepo + bun workspaces
- Shared types package
- Next.js API skeleton
- Native Swift iOS app (Xcode project)
- Database schema (PostgreSQL + Drizzle)
- ESLint + Prettier
Phase 2: Backend Core ✅ (MOSTLY COMPLETE)
- Better-auth setup (passkey, organization, magicLink)
- Drizzle ORM + migrations
- Auth handler (
/api/auth/[...all]) - Households API (organization + custom join codes)
- Stores API
- Lists API with preset reset
- Items API (search & barcode stubs — awaiting implementation)
- AI suggestions (
/api/ai/suggest) - Items forgotten analytics
- Error handling & validation (ongoing)
Phase 3: iOS Auth & Navigation ✅ (COMPLETE)
- Auth stack (sign-in, sign-up, passkey, household)
- SwiftUI navigation (tab-based + sheet flows)
- Better-auth session management (Keychain + AppState)
- Protected routes via AppState.session
- Passkey manager (AuthenticationServices wrapper)
Phase 4: iOS Core Screens ✅ (FEATURE COMPLETE)
- Home screen (lists + "don't forget")
- Main list screen (aisle tabs with SwiftUI ScrollViewReader)
- Add item sheet (search, barcode infrastructure, manual)
- AI alternatives (long-press → bottom sheet)
- Barcode scanning (camera integration ready)
- Store + aisle management
- 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
anytypes) - Error handling — All API routes must validate auth, handle DB errors, return proper HTTP status codes
- Logging — Use
console.warn,console.errorfor production debugging (console.log available for dev) - Types — Import from
@shop/typesfor shared types - Comments — Document complex logic, especially AI/business logic
API Response Format
Return JSON with this structure:
{ data?: T, error?: { code: string, message: string } }
Status codes:
200— Success201— Created400— Bad request401— Unauthorized403— Forbidden404— Not found500— Server error
Passkey Setup (FIXED)
Fixed in v1.1.4:
- Passkey plugin now imported from
better-auth/plugins(was wrongly from@better-auth/passkey) baseURLis now set in betterAuth config (was missing, causing rpID derivation failures)- See
apps/api/lib/auth.tsfor reference
Backend Stubbed Features
These routes return mock data:
GET /api/items/search?q=— Return hardcoded items matching queryGET /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
@EnvironmentObjectfor global state (AppState) - Comments — Document especially around concurrency, async operations
iOS App Notes
- Update
serverURLinAppState.swiftfor 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