learning_ai_clock/AGENTS.md
saravanakumardb1 f10b83c122 feat(backend): scaffold product-specific Fastify backend (port 4011)
Add backend/ directory with Fastify 5 + TypeScript ESM service:
- Modules: timers, routines, households, shared-timers, webhooks (migrated from platform-service)
- Cosmos containers: timers, routines, households, shared_timers, webhook_subscriptions, webhook_events
- JWT verification via jose (matches platform-service issuer)
- Shared @bytelyst/* packages via file: refs
- 171 Vitest tests passing

Update AGENTS.md: update backend integration section with product backend details
2026-03-01 20:39:08 -08:00

301 lines
16 KiB
Markdown

# AGENTS.md — AI Coding Agent Instructions
> **For:** Claude Code, OpenAI Codex, Cursor, GitHub Copilot, Windsurf Cascade, and any AI coding agent.
> **Repo:** `learning_ai_clock` — ChronoMind AI-powered contextual clock & timer.
> **See also:** [`docs/PRD.md`](docs/PRD.md) for full product spec, [`docs/roadmap.md`](docs/roadmap.md) for implementation plan.
---
## 1. Project Identity
| Key | Value |
|-----|-------|
| **Product** | ChronoMind |
| **Product ID** | `chronomind` |
| **Bundle ID (iOS)** | `com.saravana.chronomind` |
| **Bundle ID (Android)** | `com.chronomind.app` |
| **Domain** | chronomind.app (TBD) |
| **Repo** | `learning_ai_clock` |
| **Ecosystem** | ByteLyst (shares platform-service with LysnrAI, MindLyst, NomGap) |
## 2. Repo Layout
```
learning_ai_clock/
├── web/ # Next.js 16 PWA (App Router)
│ ├── src/
│ │ ├── app/ # Pages: dashboard, focus, history, routines, settings, landing, privacy, terms
│ │ ├── components/ # React components (12 files)
│ │ │ ├── Dashboard.tsx # Main timeline + timer list
│ │ │ ├── CreateTimerModal.tsx # Timer creation with NL input
│ │ │ ├── AlarmOverlay.tsx # Full-screen critical alarm
│ │ │ ├── PomodoroView.tsx # Pomodoro session UI
│ │ │ ├── CountdownRing.tsx # Visual countdown ring
│ │ │ ├── RoutineEditor.tsx # Create/edit routines
│ │ │ ├── RoutineRunner.tsx # Execute routines step-by-step
│ │ │ ├── StatsView.tsx # Charts + analytics
│ │ │ ├── StreakCard.tsx # Streak display
│ │ │ ├── TimerCard.tsx # Individual timer card
│ │ │ ├── FocusView.tsx # Focus mode UI
│ │ │ └── Toast.tsx # In-app toast notifications
│ │ └── lib/ # Pure engine modules (16 files + 16 test files)
│ │ ├── timer-engine.ts # Timer state machine (424 lines)
│ │ ├── cascade.ts # Pre-warning cascade system
│ │ ├── urgency.ts # 5 urgency levels
│ │ ├── routines.ts # Routine engine
│ │ ├── linked-timers.ts # Timer chaining
│ │ ├── nl-parser.ts # Natural language parsing
│ │ ├── recurrence.ts # Recurring timer rules
│ │ ├── categories.ts # Timer categories/tags
│ │ ├── context-messages.ts # Contextual pre-warning messages
│ │ ├── prep-time.ts # Prep time intelligence
│ │ ├── adaptive-snooze.ts # Snooze pattern learning
│ │ ├── calendar-import.ts # .ics import
│ │ ├── stats.ts # Statistics + streaks
│ │ ├── sounds.ts # Web Audio API alarm tones
│ │ ├── notifications.ts # Web Push + Service Worker
│ │ ├── platform-sync.ts # Sync client for platform-service
│ │ ├── store.ts # Zustand + localStorage
│ │ ├── routine-store.ts # Routine Zustand store
│ │ ├── format.ts # Time formatting
│ │ ├── time-blindness.ts # Familiar time references
│ │ ├── export.ts # JSON/CSV export + import
│ │ ├── analytics.ts # Analytics stub
│ │ ├── use-sync.ts # React sync hook
│ │ ├── use-tick.ts # rAF tick hook
│ │ ├── use-theme.ts # Theme hook
│ │ ├── use-keyboard-shortcuts.ts
│ │ └── schemas.ts # Zod schemas
│ ├── e2e/ # Playwright E2E tests
│ │ └── core-flows.spec.ts # 10 test suites
│ ├── public/ # Static assets + manifest
│ ├── next.config.ts # Serwist PWA config
│ ├── package.json # Next.js 16, React 19, Zustand, Vitest
│ └── vitest.config.ts
├── ios/ # Native SwiftUI (iOS + watchOS + macOS)
│ ├── ChronoMind/ # iOS app
│ │ ├── App/ # Entry point + ContentView
│ │ ├── Shared/ # Cross-platform Swift code
│ │ │ ├── TimerEngine/ # Cascade, Format, TimerEngine, TimeBlindness, Urgency
│ │ │ ├── Store/ # TimerStore (UserDefaults-based)
│ │ │ ├── Notifications/ # UNUserNotificationCenter scheduling
│ │ │ ├── Haptics/ # UIImpactFeedbackGenerator
│ │ │ ├── Calendar/ # EventKit sync
│ │ │ ├── Cloud/ # CloudKitSyncManager + PlatformSyncManager
│ │ │ ├── Location/ # CoreLocation + MapKit travel time
│ │ │ ├── Sleep/ # HealthKit sleep integration
│ │ │ ├── Wellness/ # Mood check-in
│ │ │ ├── Gamification/ # Streaks, badges, focus score
│ │ │ ├── Growth/ # Referral manager
│ │ │ ├── Sharing/ # Shareable timer links
│ │ │ ├── Data/ # Data export manager
│ │ │ ├── Reschedule/ # AI reschedule engine
│ │ │ ├── Diagnostics/ # Crash reporter
│ │ │ ├── Accessibility/ # VoiceOver + Dynamic Type helpers
│ │ │ ├── AppGroup/ # SharedTimerData (iPhone <-> Watch <-> Widget)
│ │ │ └── Theme/ # ChronoMindTheme
│ │ ├── Views/ # SwiftUI screens + components
│ │ │ ├── Components/ # AlarmOverlay, TimerCard, CountdownRing, etc.
│ │ │ ├── CreateTimer/ # CreateTimerView, QuickTimerSheet
│ │ │ ├── Focus/ # PomodoroView
│ │ │ └── Gamification/ # BadgeGrid, ConfettiView, Streak, WeeklySummary, FocusScore
│ │ ├── LiveActivity/ # Dynamic Island + Lock Screen
│ │ └── SiriShortcuts/ # App Intents
│ ├── ChronoMindWatch/ # watchOS app (4 files)
│ ├── ChronoMindMac/ # macOS menu bar app (4 files)
│ ├── ChronoMindWidgets/ # WidgetKit (5 files)
│ ├── ChronoMindTests/ # XCTest (8 test files, 129 tests)
│ ├── ChronoMind.xcodeproj/
│ └── project.yml # XcodeGen project spec
├── android/ # Jetpack Compose + Kotlin
│ ├── app/src/main/java/com/chronomind/app/
│ │ ├── engine/ # Models.kt + TimerEngine.kt (Kotlin port)
│ │ ├── data/ # Room: TimerDatabase, TimerDao, TimerEntity, TimerMapper
│ │ ├── di/ # Hilt AppModule
│ │ ├── ui/
│ │ │ ├── screens/ # Timeline, Focus, History, Settings (4 screens)
│ │ │ ├── navigation/ # NavHost
│ │ │ └── theme/ # Material 3 theme
│ │ ├── notifications/ # AlarmManager, BroadcastReceiver, NotificationManager
│ │ ├── service/ # ForegroundService, QuickSettingsTile
│ │ ├── sync/ # PlatformApiClient, SyncRepository
│ │ ├── calendar/ # CalendarSyncManager (Google Calendar via CalendarContract)
│ │ ├── viewmodel/ # TimerViewModel
│ │ └── widget/ # Glance widgets (3 sizes)
│ ├── app/src/test/ # JUnit5 tests (30 tests)
│ └── wear/ # Wear OS app (1 file, minimal)
├── docs/
│ ├── PRD.md # Full product requirements
│ ├── roadmap.md # 5-phase implementation roadmap
│ ├── roadmap-v2-review.md # Roadmap audit trail
│ ├── INDUSTRY_RESEARCH.md # Competitive analysis
│ └── raw_idea.md # Original concept
└── .github/workflows/ # GitHub Actions CI
```
## 3. Tech Stack
| Layer | Technology |
|-------|-----------|
| **Web** | Next.js 16 (App Router), React 19, TailwindCSS v4, Zustand 5, Serwist (PWA), date-fns, Recharts, Zod, Vitest, Playwright |
| **iOS** | SwiftUI (iOS 17+), WidgetKit, ActivityKit, EventKit, CoreLocation, MapKit, HealthKit, App Intents |
| **watchOS** | SwiftUI (watchOS 10+), WidgetKit complications |
| **macOS** | SwiftUI (macOS 14+), AppKit (menu bar) |
| **Android** | Jetpack Compose, Material 3, Kotlin, Room, Hilt, Glance widgets, AlarmManager |
| **Wear OS** | Compose for Wear OS |
| **Backend** | Platform-service (Fastify 5, port 4003) in sibling repo `learning_ai_common_plat` |
| **Database** | Azure Cosmos DB via `@bytelyst/cosmos` (`productId: "chronomind"`) |
| **Tests** | Vitest (web, 373 tests), XCTest (iOS, 129 tests), JUnit5 (Android, 30 tests) |
## 4. Coding Conventions
### MUST follow
- Every Cosmos document MUST include a `productId: "chronomind"` field
- Web engine logic lives in `web/src/lib/` — pure TS, no React imports (testable without DOM)
- Components in `web/src/components/` — React UI only
- iOS shared logic in `ios/ChronoMind/Shared/` — consumed by iOS, Watch, Mac, Widgets
- Android engine in `android/app/.../engine/` — pure Kotlin, no Android framework deps
- Theme tokens use `--cm-*` CSS custom properties (web) or `ChronoMindTheme` (native)
- Commit messages: `type(scope): description` — types: `feat`, `fix`, `docs`, `refactor`, `test`, `chore`
### MUST NOT do
- Never use `console.log` in production code
- Never hardcode colors — use theme tokens
- Never hardcode API URLs — use env vars or config
- Never modify tests to make them pass — fix the actual code
- Never delete existing comments or documentation unless explicitly asked
- Never add emojis to code unless explicitly asked
## 5. Key Design Decisions
### Pre-Warning Cascade (Core Feature)
- 6 presets: Aggressive, Standard, Light, Minimal, None, Custom
- Each timer has cascade intervals (e.g., [120, 60, 30, 15, 5] minutes)
- Cascade fires notifications at each interval before target time
### Urgency Levels
- **Critical** — persistent sound, full-screen overlay, no auto-dismiss
- **Important** — prominent notification, medium sound
- **Standard** — normal notification
- **Gentle** — subtle notification, soft sound
- **Passive** — badge only, no sound
### Timer Types
- **Alarm** — fires at specific time
- **Countdown** — fires after duration
- **Pomodoro** — work/break cycles
- **Event** — days until future date with milestone warnings
## 6. Build & Test Commands
```bash
# ── Web ────────────────────────────────────────────
cd web && npm run dev # Dev server (port 3000)
cd web && npm run build # Production build (uses --webpack flag)
cd web && npm test # Vitest (373 tests)
cd web && npm run typecheck # tsc --noEmit
cd web && npm run test:e2e # Playwright E2E
# ── iOS (requires Xcode) ──────────────────────────
# Open ios/ChronoMind.xcodeproj in Xcode
# Cmd+B to build, Cmd+U to test (129 XCTests)
# ── Android (requires Android SDK) ────────────────
cd android && ./gradlew :app:compileDebugKotlin
cd android && ./gradlew :app:test # 30 JUnit5 tests
# ── Full Verification ─────────────────────────────
cd web && npm test && npm run typecheck && npm run build
# ── Docker / CI Builds ───────────────────────────
# Pack @bytelyst/* tarballs so builds don't need the sibling repo
cd ../learning_ai_common_plat && pnpm build
./scripts/docker-prep.sh # pack + rewrite web/package.json
docker build web/ # self-contained build
./scripts/docker-prep.sh --restore # undo
```
## 7. Backend Integration
ChronoMind has a **product-specific backend** in `backend/` (Fastify 5, port 4011) plus the shared **platform-service** (port 4003) for auth, billing, flags, etc.
### Product Backend (`backend/`, port 4011)
| Module | Container | Endpoints | Tests |
|--------|-----------|-----------|-------|
| `timers` | `timers` (pk: `/userId`) | 7 (CRUD + delta sync + batch) | 42 |
| `routines` | `routines` (pk: `/userId`) | 7 (CRUD + delta sync + batch) | 32 |
| `households` | `households` (pk: `/id`) | 9 (CRUD + invite/join/leave) | 26 |
| `shared-timers` | `shared_timers` (pk: `/householdId`) | 6 (CRUD + per-user ack) | 30 |
All documents include `productId: "chronomind"`.
```bash
cd backend && npm run dev # Dev server on port 4011
cd backend && npm test # 130 Vitest tests
```
### Sync Protocol
- `syncVersion` monotonic integer — optimistic concurrency, 409 on stale writes
- Delta sync: `GET /timers/sync?since=<ISO>` returns only changed timers
- Batch upsert: `POST /timers/batch` for offline queue flush
### Sync Clients (written, not yet wired into app flow)
- Web: `web/src/lib/platform-sync.ts` + `use-sync.ts`
- iOS: `ios/ChronoMind/Shared/Cloud/PlatformSyncManager.swift`
- Android: `android/.../sync/PlatformApiClient.kt` + `SyncRepository.kt`
## 8. Color Palette
| Token | Hex | Use |
|-------|-----|-----|
| `--cm-bg-canvas` | `#0A0B0F` | Page background |
| `--cm-bg-elevated` | `#12131A` | Elevated surfaces |
| `--cm-surface-card` | `#1A1B26` | Cards |
| `--cm-text-primary` | `#E8ECF4` | Main text |
| `--cm-text-secondary` | `#8B92A8` | Descriptions |
| `--cm-text-tertiary` | `#565C72` | Timestamps |
| `--cm-accent` | `#5B8DEE` | Primary accent |
| Critical urgency | `#FF4757` | Red |
| Important urgency | `#FF9F43` | Orange |
| Standard urgency | `#FECA57` | Yellow |
| Gentle urgency | `#2ED573` | Green |
| Passive urgency | `#8B92A8` | Gray |
## 9. Known Gaps (as of Feb 2026)
### iOS — Missing Swift Ports
- `Recurrence.swift` — no recurring timer engine on iOS
- `NLParser.swift` — no natural language parser on iOS
- `ContextMessages.swift` — no contextual pre-warning messages on iOS
- Routine models + UI (`RoutineListView`, `RoutineRunnerView`) not built
- Still using UserDefaults — SwiftData migration pending
### Android
- `RoutineScreen.kt` not built
- Wear OS is minimal (1 file)
### Cross-Platform
- Sync clients exist but not wired into app flow
- No account creation (Apple/Google Sign-In)
- No iCloud/CloudKit sync wired
### Infrastructure
- No domain registered
- No Vercel deployment
- No TestFlight / App Store / Play Store submissions
## 10. Common Pitfalls
1. **Next.js 16 + Turbopack** — Must pass `--webpack` flag to `next build` and `next dev` (Serwist not yet compatible with Turbopack)
2. **Web engine purity**`web/src/lib/` files must NOT import from React or Next.js
3. **iOS targets** — 4 targets share `Shared/` folder: ChronoMind (iOS), ChronoMindWatch, ChronoMindMac, ChronoMindWidgets
4. **Android Hilt** — All new `@Singleton` classes must be provided in `AppModule.kt`
5. **Sync version** — All timer mutations must increment `syncVersion` for conflict detection