diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0acef86 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,1220 @@ +# LocalGreenChain Agent Deployment Plan + +> **Generated**: 2025-11-23 +> **Purpose**: 10 parallel agents for worktree deployment +> **Branch Pattern**: `claude/agent-{N}-{task}-{session-id}` + +--- + +## Overview + +This document defines 10 specialized agents to implement the critical next steps for LocalGreenChain. Each agent works independently on a dedicated worktree and can be deployed in parallel. + +### Priority Matrix + +| Priority | Agents | Focus Area | +|----------|--------|------------| +| **P0 - Critical** | Agent 1, 2 | Auth + Database (Blocking MVP) | +| **P1 - High** | Agent 3, 4, 5 | File Storage + Deployment + Testing | +| **P2 - Medium** | Agent 6, 7, 8 | Real-time + Analytics + Notifications | +| **P3 - Enhancement** | Agent 9, 10 | Marketplace + Mobile | + +--- + +## Agent 1: Authentication System + +**Priority**: P0 - Critical (Blocks all user features) +**Estimated Complexity**: High +**Dependencies**: None + +### Objective +Implement a complete user authentication system with NextAuth.js supporting multiple providers. + +### Tasks + +1. **Install Dependencies** + ```bash + bun add next-auth @next-auth/prisma-adapter bcryptjs + bun add -D @types/bcryptjs + ``` + +2. **Create Auth Configuration** + - [ ] Create `pages/api/auth/[...nextauth].ts` with NextAuth configuration + - [ ] Configure providers: Credentials, GitHub, Google + - [ ] Set up JWT strategy with secure token handling + - [ ] Implement session callback for user data enrichment + +3. **Create Auth Pages** + - [ ] `pages/auth/signin.tsx` - Custom sign-in page + - [ ] `pages/auth/signup.tsx` - Registration page + - [ ] `pages/auth/forgot-password.tsx` - Password reset flow + - [ ] `pages/auth/verify-email.tsx` - Email verification + +4. **Create Auth Components** + - [ ] `components/auth/LoginForm.tsx` + - [ ] `components/auth/RegisterForm.tsx` + - [ ] `components/auth/PasswordResetForm.tsx` + - [ ] `components/auth/SocialLoginButtons.tsx` + - [ ] `components/auth/AuthGuard.tsx` - Route protection wrapper + +5. **Create Auth Hooks & Context** + - [ ] `lib/auth/useAuth.ts` - Authentication hook + - [ ] `lib/auth/AuthContext.tsx` - Auth state provider + - [ ] `lib/auth/permissions.ts` - Role-based permissions + +6. **Security Implementation** + - [ ] Password hashing with bcrypt (min 12 rounds) + - [ ] CSRF protection for forms + - [ ] Rate limiting on auth endpoints + - [ ] Secure cookie configuration + - [ ] Session invalidation on password change + +7. **API Middleware** + - [ ] `lib/auth/withAuth.ts` - API route protection middleware + - [ ] `lib/auth/withRole.ts` - Role-based API protection + - [ ] Update existing API routes to require authentication where needed + +### Files to Create +``` +lib/auth/ +├── AuthContext.tsx +├── useAuth.ts +├── permissions.ts +├── withAuth.ts +├── withRole.ts +└── types.ts + +pages/api/auth/ +├── [...nextauth].ts +├── register.ts +├── forgot-password.ts +└── verify-email.ts + +pages/auth/ +├── signin.tsx +├── signup.tsx +├── forgot-password.tsx +└── verify-email.tsx + +components/auth/ +├── LoginForm.tsx +├── RegisterForm.tsx +├── PasswordResetForm.tsx +├── SocialLoginButtons.tsx +└── AuthGuard.tsx +``` + +### Success Criteria +- [ ] Users can register with email/password +- [ ] Users can sign in with credentials or OAuth +- [ ] Protected routes redirect to sign-in +- [ ] Session persists across page refreshes +- [ ] Password reset flow works end-to-end +- [ ] All auth tests pass + +--- + +## Agent 2: Database Integration + +**Priority**: P0 - Critical (Blocks data persistence) +**Estimated Complexity**: High +**Dependencies**: None (Agent 1 can use schema once ready) + +### Objective +Implement PostgreSQL database with Prisma ORM, replacing all file-based storage. + +### Tasks + +1. **Install Dependencies** + ```bash + bun add @prisma/client + bun add -D prisma + ``` + +2. **Initialize Prisma** + ```bash + bunx prisma init + ``` + +3. **Design Complete Schema** + - [ ] Create `prisma/schema.prisma` with all models: + + ```prisma + // Core Models + model User { + id String @id @default(cuid()) + email String @unique + emailVerified DateTime? + passwordHash String? + name String? + image String? + role Role @default(USER) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + plants Plant[] + farms VerticalFarm[] + preferences ConsumerPreference[] + auditLogs AuditLog[] + } + + model Plant { + id String @id @default(cuid()) + name String + species String + variety String? + parentId String? + generation Int @default(1) + registeredAt DateTime @default(now()) + ownerId String + locationLat Float? + locationLng Float? + blockHash String? + + owner User @relation(fields: [ownerId], references: [id]) + parent Plant? @relation("PlantLineage", fields: [parentId], references: [id]) + children Plant[] @relation("PlantLineage") + transportEvents TransportEvent[] + environment EnvironmentRecord[] + } + + model TransportEvent { + id String @id @default(cuid()) + plantId String + eventType TransportEventType + fromLat Float? + fromLng Float? + toLat Float? + toLng Float? + distance Float? + carbonKg Float? + timestamp DateTime @default(now()) + metadata Json? + + plant Plant @relation(fields: [plantId], references: [id]) + } + + model VerticalFarm { + id String @id @default(cuid()) + name String + ownerId String + totalArea Float + zones Int + createdAt DateTime @default(now()) + + owner User @relation(fields: [ownerId], references: [id]) + farmZones FarmZone[] + batches CropBatch[] + } + + // ... additional models for zones, batches, recipes, etc. + ``` + +4. **Create Database Service Layer** + - [ ] `lib/db/prisma.ts` - Prisma client singleton + - [ ] `lib/db/plants.ts` - Plant CRUD operations + - [ ] `lib/db/users.ts` - User CRUD operations + - [ ] `lib/db/transport.ts` - Transport event operations + - [ ] `lib/db/farms.ts` - Vertical farm operations + - [ ] `lib/db/demand.ts` - Demand/preference operations + +5. **Create Migration System** + - [ ] Initial migration with all models + - [ ] Seed script for development data + - [ ] Migration script for production deployments + +6. **Update Existing Code** + - [ ] Refactor `PlantChain` to use database + - [ ] Update all API routes to use Prisma + - [ ] Remove file-based storage code + - [ ] Update agents to use database queries + +7. **Database Utilities** + - [ ] Connection pooling configuration + - [ ] Query logging for development + - [ ] Error handling wrapper + - [ ] Transaction helpers + +### Files to Create +``` +prisma/ +├── schema.prisma +├── migrations/ +└── seed.ts + +lib/db/ +├── prisma.ts +├── plants.ts +├── users.ts +├── transport.ts +├── farms.ts +├── demand.ts +├── audit.ts +└── types.ts +``` + +### Success Criteria +- [ ] All models defined in Prisma schema +- [ ] Migrations run successfully +- [ ] All API routes use database +- [ ] Data persists across restarts +- [ ] Seed data populates correctly +- [ ] Database tests pass + +--- + +## Agent 3: File Upload & Storage + +**Priority**: P1 - High +**Estimated Complexity**: Medium +**Dependencies**: Agent 2 (Database for metadata) + +### Objective +Implement cloud-based file storage for plant photos, documents, and certificates. + +### Tasks + +1. **Install Dependencies** + ```bash + bun add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner + bun add sharp multer + bun add -D @types/multer + ``` + +2. **Configure Storage Provider** + - [ ] `lib/storage/config.ts` - S3/R2/MinIO configuration + - [ ] Support for multiple providers (AWS S3, Cloudflare R2, local MinIO) + - [ ] Environment variable setup for credentials + +3. **Create Upload Service** + - [ ] `lib/storage/uploadService.ts` - Core upload functionality + - [ ] Presigned URL generation for direct uploads + - [ ] File type validation (images, PDFs only) + - [ ] File size limits (10MB default) + - [ ] Automatic image optimization with Sharp + +4. **Create Image Processing Pipeline** + - [ ] `lib/storage/imageProcessor.ts` + - [ ] Generate thumbnails (150x150, 300x300, 600x600) + - [ ] WebP conversion for optimization + - [ ] EXIF data extraction for metadata + - [ ] Image compression + +5. **Create API Endpoints** + - [ ] `pages/api/upload/image.ts` - Image upload endpoint + - [ ] `pages/api/upload/document.ts` - Document upload + - [ ] `pages/api/upload/presigned.ts` - Get presigned URL + - [ ] `pages/api/upload/[fileId].ts` - Get/delete file + +6. **Create UI Components** + - [ ] `components/upload/ImageUploader.tsx` - Drag & drop image upload + - [ ] `components/upload/PhotoGallery.tsx` - Plant photo gallery + - [ ] `components/upload/DocumentUploader.tsx` - PDF/document upload + - [ ] `components/upload/ProgressBar.tsx` - Upload progress + +7. **Database Integration** + - [ ] Add `File` model to Prisma schema + - [ ] Track upload metadata, URLs, and associations + - [ ] Implement soft delete for files + +### Files to Create +``` +lib/storage/ +├── config.ts +├── uploadService.ts +├── imageProcessor.ts +├── providers/ +│ ├── s3.ts +│ ├── r2.ts +│ └── local.ts +└── types.ts + +pages/api/upload/ +├── image.ts +├── document.ts +├── presigned.ts +└── [fileId].ts + +components/upload/ +├── ImageUploader.tsx +├── PhotoGallery.tsx +├── DocumentUploader.tsx +└── ProgressBar.tsx +``` + +### Success Criteria +- [ ] Images upload successfully to cloud storage +- [ ] Thumbnails generate automatically +- [ ] Presigned URLs work for direct uploads +- [ ] Gallery displays plant photos +- [ ] File deletion works properly +- [ ] Upload tests pass + +--- + +## Agent 4: Production Deployment + +**Priority**: P1 - High +**Estimated Complexity**: Medium +**Dependencies**: Agent 1, 2 (for full deployment) + +### Objective +Create complete production deployment infrastructure with Docker, logging, and monitoring. + +### Tasks + +1. **Docker Configuration** + - [ ] `Dockerfile` - Multi-stage production build + - [ ] `docker-compose.yml` - Full stack with DB, Redis + - [ ] `docker-compose.dev.yml` - Development environment + - [ ] `.dockerignore` - Exclude unnecessary files + +2. **Create Dockerfile** + ```dockerfile + # Build stage + FROM oven/bun:1 as builder + WORKDIR /app + COPY package.json bun.lockb ./ + RUN bun install --frozen-lockfile + COPY . . + RUN bun run build + + # Production stage + FROM oven/bun:1-slim + WORKDIR /app + COPY --from=builder /app/.next ./.next + COPY --from=builder /app/public ./public + COPY --from=builder /app/node_modules ./node_modules + COPY --from=builder /app/package.json ./ + EXPOSE 3000 + CMD ["bun", "run", "start"] + ``` + +3. **Environment Configuration** + - [ ] `.env.example` - Template with all variables + - [ ] `lib/config/env.ts` - Environment validation with Zod + - [ ] Separate configs for dev/staging/production + - [ ] Secrets management documentation + +4. **Logging System** + - [ ] `lib/logging/logger.ts` - Structured logging with pino + - [ ] Request/response logging middleware + - [ ] Error logging with stack traces + - [ ] Audit logging integration + - [ ] Log rotation configuration + +5. **Error Tracking** + - [ ] Sentry integration setup + - [ ] `lib/monitoring/sentry.ts` - Sentry configuration + - [ ] Error boundary components + - [ ] Source map uploads for production + +6. **Health Checks & Monitoring** + - [ ] `pages/api/health.ts` - Health check endpoint + - [ ] `pages/api/health/ready.ts` - Readiness probe + - [ ] `pages/api/health/live.ts` - Liveness probe + - [ ] Prometheus metrics endpoint + - [ ] Grafana dashboard configuration + +7. **CI/CD Pipeline** + - [ ] `.github/workflows/ci.yml` - Test and lint on PR + - [ ] `.github/workflows/deploy.yml` - Production deployment + - [ ] `.github/workflows/preview.yml` - Preview deployments + - [ ] Automated security scanning + +8. **Security Hardening** + - [ ] Security headers middleware + - [ ] Rate limiting configuration + - [ ] CORS policy setup + - [ ] CSP (Content Security Policy) + +### Files to Create +``` +Dockerfile +docker-compose.yml +docker-compose.dev.yml +.dockerignore +.env.example + +lib/config/ +├── env.ts +└── index.ts + +lib/logging/ +├── logger.ts +└── middleware.ts + +lib/monitoring/ +├── sentry.ts +├── metrics.ts +└── health.ts + +.github/workflows/ +├── ci.yml +├── deploy.yml +└── preview.yml + +infra/ +├── grafana/ +│ └── dashboard.json +└── prometheus/ + └── prometheus.yml +``` + +### Success Criteria +- [ ] Docker build succeeds +- [ ] docker-compose up runs full stack +- [ ] Health checks respond correctly +- [ ] Logs output in structured JSON +- [ ] CI pipeline runs on PRs +- [ ] Deployment to staging works + +--- + +## Agent 5: Testing & CI/CD + +**Priority**: P1 - High +**Estimated Complexity**: Medium +**Dependencies**: None + +### Objective +Comprehensive test coverage and automated CI/CD pipeline. + +### Tasks + +1. **Expand Unit Tests** + - [ ] Test all agent classes (10 agents) + - [ ] Test blockchain operations + - [ ] Test transport tracker + - [ ] Test demand forecaster + - [ ] Test vertical farm controller + - [ ] Target: 80% code coverage + +2. **API Integration Tests** + - [ ] Test all 52 API endpoints + - [ ] Test authentication flows + - [ ] Test error responses + - [ ] Test rate limiting + - [ ] Mock database for tests + +3. **E2E Tests with Cypress** + - [ ] `cypress/e2e/auth.cy.ts` - Authentication flows + - [ ] `cypress/e2e/plant-registration.cy.ts` - Plant lifecycle + - [ ] `cypress/e2e/transport.cy.ts` - Transport tracking + - [ ] `cypress/e2e/vertical-farm.cy.ts` - Farm management + - [ ] `cypress/e2e/transparency.cy.ts` - Transparency dashboard + +4. **Test Configuration** + - [ ] `jest.config.js` - Jest configuration + - [ ] `cypress.config.ts` - Cypress configuration + - [ ] Test utilities and mocks + - [ ] Fixtures for test data + +5. **CI Pipeline** + ```yaml + # .github/workflows/ci.yml + name: CI + on: [push, pull_request] + jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v1 + - run: bun install + - run: bun run lint + - run: bun run type-check + - run: bun run test --coverage + - run: bun run build + + e2e: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v1 + - run: bun install + - run: bun run build + - run: bun run cypress run + ``` + +6. **Code Quality Tools** + - [ ] ESLint configuration update + - [ ] Prettier configuration + - [ ] Husky pre-commit hooks + - [ ] lint-staged configuration + - [ ] Commitlint for commit messages + +7. **Test Reporting** + - [ ] Coverage reports to Codecov + - [ ] Test result annotations on PRs + - [ ] Cypress screenshots on failure + - [ ] Performance benchmarks + +### Files to Create +``` +__tests__/ +├── unit/ +│ ├── agents/ +│ │ ├── PlantLineageAgent.test.ts +│ │ ├── TransportTrackerAgent.test.ts +│ │ └── ... (8 more agent tests) +│ ├── blockchain/ +│ │ └── PlantChain.test.ts +│ └── services/ +│ └── ... (service tests) +├── integration/ +│ ├── api/ +│ │ ├── plants.test.ts +│ │ ├── transport.test.ts +│ │ ├── demand.test.ts +│ │ └── vertical-farm.test.ts +│ └── auth/ +│ └── authentication.test.ts +└── e2e/ + └── ... (moved to cypress/e2e) + +cypress/ +├── e2e/ +│ ├── auth.cy.ts +│ ├── plant-registration.cy.ts +│ ├── transport.cy.ts +│ └── vertical-farm.cy.ts +├── fixtures/ +│ └── ... (test data) +└── support/ + └── commands.ts + +.github/workflows/ +├── ci.yml +└── e2e.yml +``` + +### Success Criteria +- [ ] 80%+ code coverage +- [ ] All unit tests pass +- [ ] All integration tests pass +- [ ] E2E tests run in CI +- [ ] PR checks block on failures +- [ ] Coverage reports generated + +--- + +## Agent 6: Real-Time Updates + +**Priority**: P2 - Medium +**Estimated Complexity**: Medium +**Dependencies**: Agent 2 (Database) + +### Objective +Implement real-time updates using WebSockets with Socket.io for live data synchronization. + +### Tasks + +1. **Install Dependencies** + ```bash + bun add socket.io socket.io-client + bun add -D @types/socket.io + ``` + +2. **WebSocket Server Setup** + - [ ] `lib/realtime/socketServer.ts` - Socket.io server + - [ ] Integration with Next.js API routes + - [ ] Room-based subscriptions (per farm, per plant) + - [ ] Authentication middleware for sockets + +3. **Event Types** + - [ ] `lib/realtime/events.ts` - Define all event types + ```typescript + export enum RealtimeEvent { + PLANT_REGISTERED = 'plant:registered', + PLANT_UPDATED = 'plant:updated', + TRANSPORT_EVENT = 'transport:event', + FARM_ALERT = 'farm:alert', + BATCH_UPDATE = 'batch:update', + ENVIRONMENT_READING = 'environment:reading', + } + ``` + +4. **Client-Side Integration** + - [ ] `lib/realtime/useSocket.ts` - Socket.io React hook + - [ ] `lib/realtime/SocketContext.tsx` - Socket provider + - [ ] Auto-reconnection handling + - [ ] Offline state management + +5. **Real-Time Features** + - [ ] Live plant registration notifications + - [ ] Real-time transport tracking updates + - [ ] Live vertical farm sensor data + - [ ] Instant alert notifications + - [ ] Live auction/marketplace updates + +6. **UI Components** + - [ ] `components/realtime/ConnectionStatus.tsx` - Connection indicator + - [ ] `components/realtime/LiveFeed.tsx` - Activity feed + - [ ] `components/realtime/NotificationToast.tsx` - Real-time toasts + +7. **Fallback to SSE** + - [ ] Enhance existing SSE implementation + - [ ] Auto-fallback when WebSocket fails + - [ ] Graceful degradation + +### Files to Create +``` +lib/realtime/ +├── socketServer.ts +├── socketClient.ts +├── events.ts +├── useSocket.ts +├── SocketContext.tsx +├── rooms.ts +└── types.ts + +pages/api/socket.ts + +components/realtime/ +├── ConnectionStatus.tsx +├── LiveFeed.tsx +├── NotificationToast.tsx +└── LiveChart.tsx +``` + +### Success Criteria +- [ ] WebSocket connections establish successfully +- [ ] Real-time updates display instantly +- [ ] Room subscriptions work correctly +- [ ] Fallback to SSE works +- [ ] Connection status displays accurately +- [ ] Real-time tests pass + +--- + +## Agent 7: Advanced Analytics Dashboard + +**Priority**: P2 - Medium +**Estimated Complexity**: Medium +**Dependencies**: Agent 2 (Database) + +### Objective +Create comprehensive analytics dashboards with charts, trends, and insights. + +### Tasks + +1. **Install Dependencies** + ```bash + bun add recharts d3 date-fns + bun add -D @types/d3 + ``` + +2. **Analytics Data Layer** + - [ ] `lib/analytics/aggregator.ts` - Data aggregation service + - [ ] `lib/analytics/metrics.ts` - Metric calculations + - [ ] `lib/analytics/trends.ts` - Trend analysis + - [ ] Time-series data handling + - [ ] Caching for expensive calculations + +3. **API Endpoints** + - [ ] `pages/api/analytics/overview.ts` - Dashboard overview + - [ ] `pages/api/analytics/plants.ts` - Plant analytics + - [ ] `pages/api/analytics/transport.ts` - Transport metrics + - [ ] `pages/api/analytics/farms.ts` - Vertical farm analytics + - [ ] `pages/api/analytics/sustainability.ts` - Environmental impact + - [ ] `pages/api/analytics/export.ts` - Export data + +4. **Chart Components** + - [ ] `components/analytics/LineChart.tsx` - Time series + - [ ] `components/analytics/BarChart.tsx` - Comparisons + - [ ] `components/analytics/PieChart.tsx` - Distribution + - [ ] `components/analytics/AreaChart.tsx` - Stacked data + - [ ] `components/analytics/Heatmap.tsx` - Geographic density + - [ ] `components/analytics/Gauge.tsx` - KPI gauges + +5. **Dashboard Pages** + - [ ] `pages/analytics/index.tsx` - Main dashboard + - [ ] `pages/analytics/plants.tsx` - Plant insights + - [ ] `pages/analytics/transport.tsx` - Carbon & miles + - [ ] `pages/analytics/farms.tsx` - Farm performance + - [ ] `pages/analytics/sustainability.tsx` - Environmental + +6. **Dashboard Widgets** + - [ ] `components/analytics/KPICard.tsx` - Key metrics + - [ ] `components/analytics/TrendIndicator.tsx` - Up/down trends + - [ ] `components/analytics/DataTable.tsx` - Sortable tables + - [ ] `components/analytics/DateRangePicker.tsx` - Time selection + - [ ] `components/analytics/FilterPanel.tsx` - Data filtering + +7. **Export Features** + - [ ] PDF report generation + - [ ] CSV data export + - [ ] Chart image download + - [ ] Scheduled reports (email) + +### Files to Create +``` +lib/analytics/ +├── aggregator.ts +├── metrics.ts +├── trends.ts +├── cache.ts +└── types.ts + +pages/api/analytics/ +├── overview.ts +├── plants.ts +├── transport.ts +├── farms.ts +├── sustainability.ts +└── export.ts + +pages/analytics/ +├── index.tsx +├── plants.tsx +├── transport.tsx +├── farms.tsx +└── sustainability.tsx + +components/analytics/ +├── LineChart.tsx +├── BarChart.tsx +├── PieChart.tsx +├── AreaChart.tsx +├── Heatmap.tsx +├── Gauge.tsx +├── KPICard.tsx +├── TrendIndicator.tsx +├── DataTable.tsx +├── DateRangePicker.tsx +└── FilterPanel.tsx +``` + +### Success Criteria +- [ ] Dashboard loads with real data +- [ ] All chart types render correctly +- [ ] Date range filtering works +- [ ] Export generates valid files +- [ ] Performance under 3s load time +- [ ] Analytics tests pass + +--- + +## Agent 8: Notification System + +**Priority**: P2 - Medium +**Estimated Complexity**: Medium +**Dependencies**: Agent 1 (Auth), Agent 2 (Database) + +### Objective +Implement multi-channel notification system with email, push, and in-app notifications. + +### Tasks + +1. **Install Dependencies** + ```bash + bun add nodemailer @sendgrid/mail + bun add web-push + bun add -D @types/nodemailer @types/web-push + ``` + +2. **Notification Service** + - [ ] `lib/notifications/service.ts` - Core notification service + - [ ] `lib/notifications/channels/email.ts` - Email channel + - [ ] `lib/notifications/channels/push.ts` - Web push + - [ ] `lib/notifications/channels/inApp.ts` - In-app notifications + - [ ] Notification queue with retry logic + +3. **Email Templates** + - [ ] `lib/notifications/templates/welcome.ts` - Welcome email + - [ ] `lib/notifications/templates/plantReminder.ts` - Care reminders + - [ ] `lib/notifications/templates/transportAlert.ts` - Transport updates + - [ ] `lib/notifications/templates/farmAlert.ts` - Farm alerts + - [ ] React Email for template rendering + +4. **Push Notifications** + - [ ] Service worker for push + - [ ] VAPID key generation + - [ ] Subscription management + - [ ] Push payload handling + +5. **In-App Notifications** + - [ ] `lib/notifications/inApp.ts` - In-app notification store + - [ ] Notification preferences per user + - [ ] Mark as read/unread functionality + - [ ] Notification grouping + +6. **API Endpoints** + - [ ] `pages/api/notifications/index.ts` - List notifications + - [ ] `pages/api/notifications/[id].ts` - Get/update notification + - [ ] `pages/api/notifications/preferences.ts` - User preferences + - [ ] `pages/api/notifications/subscribe.ts` - Push subscription + - [ ] `pages/api/notifications/send.ts` - Send notification (internal) + +7. **UI Components** + - [ ] `components/notifications/NotificationBell.tsx` - Header bell icon + - [ ] `components/notifications/NotificationList.tsx` - Dropdown list + - [ ] `components/notifications/NotificationItem.tsx` - Single notification + - [ ] `components/notifications/PreferencesForm.tsx` - Settings + +8. **Scheduled Notifications** + - [ ] Plant care reminders (watering, feeding) + - [ ] Harvest time alerts + - [ ] Weekly digest emails + - [ ] Cron job integration + +### Files to Create +``` +lib/notifications/ +├── service.ts +├── queue.ts +├── scheduler.ts +├── channels/ +│ ├── email.ts +│ ├── push.ts +│ └── inApp.ts +├── templates/ +│ ├── welcome.ts +│ ├── plantReminder.ts +│ ├── transportAlert.ts +│ └── farmAlert.ts +└── types.ts + +pages/api/notifications/ +├── index.ts +├── [id].ts +├── preferences.ts +├── subscribe.ts +└── send.ts + +components/notifications/ +├── NotificationBell.tsx +├── NotificationList.tsx +├── NotificationItem.tsx +└── PreferencesForm.tsx + +public/ +└── sw.js (service worker) +``` + +### Success Criteria +- [ ] Emails send successfully +- [ ] Push notifications work +- [ ] In-app notifications display +- [ ] Preferences save correctly +- [ ] Reminders schedule properly +- [ ] Notification tests pass + +--- + +## Agent 9: Marketplace Foundation + +**Priority**: P3 - Enhancement +**Estimated Complexity**: High +**Dependencies**: Agent 1 (Auth), Agent 2 (Database) + +### Objective +Create the foundation for a plant trading marketplace with listings, offers, and basic transactions. + +### Tasks + +1. **Database Models** + - [ ] Add marketplace models to Prisma schema: + ```prisma + model Listing { + id String @id @default(cuid()) + sellerId String + plantId String? + title String + description String + price Decimal + currency String @default("USD") + quantity Int + category ListingCategory + status ListingStatus + createdAt DateTime @default(now()) + expiresAt DateTime? + + seller User @relation(fields: [sellerId], references: [id]) + plant Plant? @relation(fields: [plantId], references: [id]) + offers Offer[] + images ListingImage[] + } + + model Offer { + id String @id @default(cuid()) + listingId String + buyerId String + amount Decimal + message String? + status OfferStatus + createdAt DateTime @default(now()) + + listing Listing @relation(fields: [listingId], references: [id]) + buyer User @relation(fields: [buyerId], references: [id]) + } + ``` + +2. **Marketplace Service** + - [ ] `lib/marketplace/listingService.ts` - Listing CRUD + - [ ] `lib/marketplace/offerService.ts` - Offer management + - [ ] `lib/marketplace/searchService.ts` - Listing search + - [ ] `lib/marketplace/matchingService.ts` - Buyer/seller matching + +3. **API Endpoints** + - [ ] `pages/api/marketplace/listings/index.ts` - List/create + - [ ] `pages/api/marketplace/listings/[id].ts` - CRUD + - [ ] `pages/api/marketplace/listings/[id]/offers.ts` - Offers + - [ ] `pages/api/marketplace/search.ts` - Search listings + - [ ] `pages/api/marketplace/my-listings.ts` - User's listings + - [ ] `pages/api/marketplace/my-offers.ts` - User's offers + +4. **Marketplace Pages** + - [ ] `pages/marketplace/index.tsx` - Marketplace home + - [ ] `pages/marketplace/listings/[id].tsx` - Listing detail + - [ ] `pages/marketplace/create.tsx` - Create listing + - [ ] `pages/marketplace/my-listings.tsx` - Manage listings + - [ ] `pages/marketplace/my-offers.tsx` - Manage offers + +5. **UI Components** + - [ ] `components/marketplace/ListingCard.tsx` + - [ ] `components/marketplace/ListingGrid.tsx` + - [ ] `components/marketplace/ListingForm.tsx` + - [ ] `components/marketplace/OfferForm.tsx` + - [ ] `components/marketplace/OfferList.tsx` + - [ ] `components/marketplace/SearchFilters.tsx` + - [ ] `components/marketplace/PriceDisplay.tsx` + +6. **Seller Features** + - [ ] Seller profile page + - [ ] Rating and review system (model only) + - [ ] Listing analytics + - [ ] Inventory management + +7. **Buyer Features** + - [ ] Saved listings (wishlist) + - [ ] Search with filters + - [ ] Offer history + - [ ] Messaging foundation (model only) + +### Files to Create +``` +lib/marketplace/ +├── listingService.ts +├── offerService.ts +├── searchService.ts +├── matchingService.ts +└── types.ts + +pages/api/marketplace/ +├── listings/ +│ ├── index.ts +│ └── [id]/ +│ ├── index.ts +│ └── offers.ts +├── search.ts +├── my-listings.ts +└── my-offers.ts + +pages/marketplace/ +├── index.tsx +├── create.tsx +├── my-listings.tsx +├── my-offers.tsx +└── listings/ + └── [id].tsx + +components/marketplace/ +├── ListingCard.tsx +├── ListingGrid.tsx +├── ListingForm.tsx +├── OfferForm.tsx +├── OfferList.tsx +├── SearchFilters.tsx +└── PriceDisplay.tsx +``` + +### Success Criteria +- [ ] Listings create and display +- [ ] Search with filters works +- [ ] Offers submit correctly +- [ ] Seller can manage listings +- [ ] Buyer can browse and offer +- [ ] Marketplace tests pass + +--- + +## Agent 10: Mobile Optimization + +**Priority**: P3 - Enhancement +**Estimated Complexity**: Medium +**Dependencies**: All core agents (1-5) + +### Objective +Optimize the application for mobile devices with PWA capabilities and responsive improvements. + +### Tasks + +1. **PWA Configuration** + - [ ] `next.config.js` - PWA plugin configuration + - [ ] `public/manifest.json` - Web app manifest + - [ ] Service worker for offline support + - [ ] Install prompts + +2. **Install Dependencies** + ```bash + bun add next-pwa + ``` + +3. **Mobile-First Styling** + - [ ] Audit all components for mobile responsiveness + - [ ] `styles/mobile.css` - Mobile-specific overrides + - [ ] Touch-friendly tap targets (min 44px) + - [ ] Swipe gestures for navigation + - [ ] Bottom navigation bar + +4. **Mobile Components** + - [ ] `components/mobile/BottomNav.tsx` - Bottom navigation + - [ ] `components/mobile/SwipeableCard.tsx` - Swipeable cards + - [ ] `components/mobile/PullToRefresh.tsx` - Pull to refresh + - [ ] `components/mobile/MobileHeader.tsx` - Mobile header + - [ ] `components/mobile/InstallPrompt.tsx` - PWA install + +5. **Offline Support** + - [ ] Cache critical pages + - [ ] Offline fallback page + - [ ] Queue actions when offline + - [ ] Sync when back online + - [ ] IndexedDB for local storage + +6. **Performance Optimization** + - [ ] Image lazy loading + - [ ] Code splitting by route + - [ ] Bundle size analysis + - [ ] Critical CSS extraction + - [ ] Lighthouse score > 90 + +7. **Touch Interactions** + - [ ] Swipe to dismiss notifications + - [ ] Pinch to zoom on images + - [ ] Long press for context menus + - [ ] Haptic feedback (where supported) + +8. **Camera Integration** + - [ ] `lib/mobile/camera.ts` - Camera access + - [ ] QR code scanning + - [ ] Photo capture for plants + - [ ] Image cropping + +9. **Mobile Pages** + - [ ] `pages/m/index.tsx` - Mobile home (simplified) + - [ ] `pages/m/scan.tsx` - QR scanner + - [ ] `pages/m/quick-add.tsx` - Quick plant add + +### Files to Create +``` +public/ +├── manifest.json +├── icons/ +│ ├── icon-72x72.png +│ ├── icon-96x96.png +│ ├── icon-128x128.png +│ ├── icon-144x144.png +│ ├── icon-152x152.png +│ ├── icon-192x192.png +│ ├── icon-384x384.png +│ └── icon-512x512.png +├── offline.html +└── sw.js + +lib/mobile/ +├── camera.ts +├── offline.ts +├── gestures.ts +└── pwa.ts + +components/mobile/ +├── BottomNav.tsx +├── SwipeableCard.tsx +├── PullToRefresh.tsx +├── MobileHeader.tsx +├── InstallPrompt.tsx +└── QRScanner.tsx + +pages/m/ +├── index.tsx +├── scan.tsx +└── quick-add.tsx + +styles/ +└── mobile.css +``` + +### Success Criteria +- [ ] PWA installs on mobile +- [ ] Offline mode works +- [ ] All pages responsive +- [ ] Lighthouse score > 90 +- [ ] Camera/QR works +- [ ] Mobile tests pass + +--- + +## Deployment Instructions + +### Setting Up Worktrees + +For each agent, create a dedicated worktree: + +```bash +# From the main repository +cd localgreenchain + +# Create worktrees for each agent +git worktree add ../lgc-agent-1-auth claude/agent-1-auth-{session-id} +git worktree add ../lgc-agent-2-database claude/agent-2-database-{session-id} +git worktree add ../lgc-agent-3-storage claude/agent-3-storage-{session-id} +git worktree add ../lgc-agent-4-deploy claude/agent-4-deploy-{session-id} +git worktree add ../lgc-agent-5-testing claude/agent-5-testing-{session-id} +git worktree add ../lgc-agent-6-realtime claude/agent-6-realtime-{session-id} +git worktree add ../lgc-agent-7-analytics claude/agent-7-analytics-{session-id} +git worktree add ../lgc-agent-8-notifications claude/agent-8-notifications-{session-id} +git worktree add ../lgc-agent-9-marketplace claude/agent-9-marketplace-{session-id} +git worktree add ../lgc-agent-10-mobile claude/agent-10-mobile-{session-id} +``` + +### Agent Coordination + +1. **P0 Agents (1-2)** should start immediately - no dependencies +2. **P1 Agents (3-5)** can start after database schema is ready +3. **P2 Agents (6-8)** depend on auth and database +4. **P3 Agents (9-10)** can start once core features are stable + +### Merge Order + +1. Agent 2 (Database) - First, as all others depend on it +2. Agent 1 (Auth) - Second, required for protected features +3. Agent 5 (Testing) - Third, to validate core +4. Agent 4 (Deployment) - Fourth, for infrastructure +5. Agent 3 (Storage) - After auth is ready +6. Agents 6-8 in parallel +7. Agents 9-10 last + +--- + +## Summary + +| Agent | Task | Priority | Files | Est. LOC | +|-------|------|----------|-------|----------| +| 1 | Authentication | P0 | ~20 | ~2000 | +| 2 | Database | P0 | ~15 | ~1500 | +| 3 | File Storage | P1 | ~15 | ~1200 | +| 4 | Deployment | P1 | ~15 | ~800 | +| 5 | Testing | P1 | ~30 | ~3000 | +| 6 | Real-Time | P2 | ~15 | ~1000 | +| 7 | Analytics | P2 | ~20 | ~2500 | +| 8 | Notifications | P2 | ~20 | ~1500 | +| 9 | Marketplace | P3 | ~20 | ~2000 | +| 10 | Mobile | P3 | ~15 | ~1200 | + +**Total**: ~185 new files, ~16,700 lines of code + +--- + +*Generated for LocalGreenChain worktree deployment*