# Kalei Build Plan — Phases 1 & 2

### From Platform Foundation to Core Experience
**Total Duration:** 5–8 weeks
**Approach:** Backend-first in Phase 1, then mobile + backend in parallel in Phase 2

---

## Overview

This document consolidates the two core build phases that take Kalei from a configured dev environment to a fully functional app with Mirror, Turn, and Lens experiences end-to-end. Phase 1 lays the platform foundation (auth, schema, AI gateway, safety). Phase 2 builds the user-facing experience on top of that foundation.

```
Phase 1: Platform Foundation (Weeks 1-3)
  → Auth, schema, entitlements, AI gateway, safety, observability

Phase 2: Core Experience Build (Weeks 4-8)
  → Mirror v1, Turn v1, Lens v1, Gallery, end-to-end flows
```

---

# PHASE 1 — Platform Foundation

**Duration:** 2–3 weeks
**Primary owner:** Backend-first with mobile stub integration

## 1.1 Objective

Build a production-grade platform foundation: robust auth and session model, entitlement checks for free vs. paid plans, core domain schema for Mirror/Turn/Lens, AI gateway scaffold with usage metering, and observability + error handling baseline.

## 1.2 Entry Criteria

Phase 0 exit checklist must be complete.

---

## 1.3 Core Scope

### 1.3.1 API Module Setup

Implement service modules: auth, profiles, entitlements, mirror (session/message skeleton), turn (request skeleton), lens (goal/action skeleton), ai_gateway, usage_cost, safety (precheck skeleton).

Each module needs: route handlers, input/output schema validation, service layer, repository/data access layer, and unit tests.

### 1.3.2 Identity and Access

Implement: email/password registration and login, JWT access token (short TTL), refresh token rotation and revocation, logout all sessions, role model (at least `user`, `admin`).

Security details: hash passwords with Argon2id or bcrypt, store refresh tokens hashed, include device metadata per session.

### 1.3.3 Entitlement Model

Implement plan model now, even before paywall UI is complete.

Suggested plan keys: `free`, `prism`, `prism_plus`.

Implement gates for: turns per day, mirror sessions per week, spectrum access.

Integration approach: no RevenueCat dependency. Ingest App Store Server Notifications and Google Play RTDN notifications directly. Maintain local entitlement snapshots as source of truth for authorization.

### 1.3.4 Data Model (Phase 1 Schema)

Create migrations for: users, profiles, subscriptions, entitlement_snapshots, turns, mirror_sessions, mirror_messages, mirror_fragments, lens_goals, lens_actions, ai_usage_events, safety_events.

Design requirements: every row has `created_at`, `updated_at` where relevant. Index by `user_id` and key query timestamps. Soft delete where legal retention requires it.

### 1.3.5 AI Gateway Scaffold

Implement a strict abstraction now: provider adapter interface, request envelope (feature, model, temperature, timeout), response normalization, token usage extraction, retry + timeout + circuit breaker policy.

Do not expose provider SDK directly in feature modules.

### 1.3.6 Safety Precheck Skeleton

Implement now even if rule set is basic: deterministic keyword precheck, safety event logging, return safety status to caller. Mirror and Turn endpoints must call this precheck before generation.

### 1.3.7 Usage Metering and Cost Guardrails

Implement: per-user usage counters in Redis, endpoint-level rate limit middleware, AI usage event write on every provider call, per-feature daily budget checks.

### 1.3.8 Observability Baseline

Implement: structured logging with request IDs, error tracking to GlitchTip, latency and error metrics per endpoint, AI cost metrics by feature.

---

## 1.4 Build Sequence

**Week 1:**
1. Finalize schema and migration files
2. Implement auth and profile endpoints
3. Add integration tests for auth flows

**Week 2:**
1. Implement entitlements and plan gating middleware
2. Implement AI gateway interface and one real provider adapter
3. Implement Redis rate limits and usage counters

**Week 3:**
1. Implement Mirror and Turn endpoint skeletons with safety precheck
2. Implement Lens goal and action skeleton endpoints
3. Add complete observability hooks and dashboards

---

## 1.5 API Contract — End of Phase 1

**Auth:**
- `POST /auth/register`
- `POST /auth/login`
- `POST /auth/refresh`
- `POST /auth/logout`
- `GET /me`

**Entitlements:**
- `GET /billing/entitlements`
- Webhook endpoints for App Store and Google Play billing event ingestion

**Feature Skeletons:**
- `POST /mirror/sessions`
- `POST /mirror/messages`
- `POST /turns`
- `POST /lens/goals`

## 1.6 Testing Requirements

Minimum automated coverage: auth happy path and invalid credential path, token refresh rotation path, entitlement denial for free limits, safety precheck path for crisis keyword match, AI gateway timeout and fallback behavior. Recommended: basic load test for auth + turn skeleton endpoints.

## 1.7 Phase 1 Deliverables

**Code:** Migration files for core schema, API modules with tests, Redis-backed rate limit and usage tracking, AI gateway abstraction with one provider, safety precheck middleware.

**Operational:** GlitchTip configured, endpoint metrics visible, API runbook for local and staging.

## 1.8 Phase 1 Exit Criteria

You can exit Phase 1 when: core auth model is stable and tested, plan gating is enforced server-side, Mirror/Turn/Lens endpoint skeletons are live, AI calls only happen through AI gateway, logs/metrics/error tracking are active.

## 1.9 Phase 1 Risks

- **Auth complexity balloons early.** Mitigation: keep v1 auth strict but minimal; defer advanced IAM.
- **Schema churn from feature uncertainty.** Mitigation: maintain a schema decision log and avoid premature optimization.
- **Provider coupling in feature code.** Mitigation: enforce gateway adapter pattern in code review.

---
---

# PHASE 2 — Core Experience Build

**Duration:** 3–5 weeks
**Primary owner:** Mobile + backend in parallel

## 2.1 Objective

Ship Kalei's core user experience end-to-end: Mirror with fragment highlighting and inline reframe, Turn generation with 3 perspectives and micro-action, Lens goals/daily actions/daily focus, Gallery/history views for user continuity.

## 2.2 Entry Criteria

Phase 1 exit checklist complete.

---

## 2.3 Product Scope

### 2.3.1 Mirror (Awareness)

**Required behavior:** User starts mirror session → submits messages → backend runs safety precheck first → backend runs fragment detection on safe content → app highlights detected fragments above confidence threshold → user taps fragment for inline reframe → user closes session and receives reflection summary.

**Backend work:** Finalize `mirror_sessions`, `mirror_messages`, `mirror_fragments`. Add close-session reflection endpoint. Add mirror session list/detail endpoints.

**Mobile work:** Mirror compose UI, highlight rendering for detected fragment ranges, tap-to-reframe interaction card, session close and reflection display.

### 2.3.2 Turn (Kaleidoscope)

**Required behavior:** User submits a fragment or thought → backend runs safety precheck → backend generates 3 reframed perspectives → backend returns micro-action (if-then) → user can save turn to gallery.

**Backend work:** Finalize `turns` table and categories. Add save/unsave state. Add history list endpoint.

**Mobile work:** Turn input and loading animation, display 3 patterns + micro-action, save to gallery and view history.

### 2.3.3 Lens (Direction)

**Required behavior:** User creates one or more goals → app generates or stores daily action suggestions → user can mark actions complete → optional daily affirmation/focus shown.

**Backend work:** Finalize `lens_goals`, `lens_actions`. Daily action generation endpoint. Daily affirmation endpoint through AI gateway.

**Mobile work:** Goal creation UI, daily action checklist UI, completion updates and streak indicator.

### 2.3.4 The Rehearsal (Lens Sub-Feature)

**Required behavior:** User selects "Rehearse" within a Lens goal → backend generates a personalized visualization script (process-oriented, first-person, multi-sensory, with obstacle rehearsal) → app displays as a guided text flow with SVG progress ring → session completes with a follow-up micro-action.

**Backend work:** Rehearsal generation endpoint through AI gateway. Prompt template enforcing: first-person perspective, present tense, multi-sensory detail, process focus, obstacle inclusion, ~10 min reading pace. Cache generated scripts per goal; refresh when actions change. Add `rehearsal_sessions` table.

**Mobile work:** Rehearsal screen (single flowing view with SVG progress ring timer). Step transitions (Grounding → Process → Obstacle → Close). Completion state with generated SVG pattern. Rehearsal history in Gallery.

### 2.3.5 The Ritual (Context-Anchored Daily Flow)

**Required behavior:** User selects a Ritual template (Morning/Evening/Quick) and anchors to a daily context → app delivers a timed, sequenced flow chaining Mirror/Turn/Lens steps → Ritual completion tracked with context consistency metrics.

**Backend work:** `ritual_configs` table (template, anchored time, notification preferences). `ritual_completions` table (timestamp, duration, steps completed). Context consistency calculation logic (same-window tracking per Wood et al.). Ritual notification scheduling.

**Mobile work:** Ritual selection/setup during onboarding or settings. Single flowing Ritual screen with SVG progress segments per step. Step transitions without navigation. Completion state with Ritual pattern. Context consistency display in streaks.

### 2.3.6 The Evidence Wall (Mastery Tracking)

**Required behavior:** System automatically collects proof points from all features (completed actions, saved keepsakes, self-corrections, streak milestones, goal completions, reframe echoes) → Evidence Wall in "You" tab displays as SVG mosaic → AI surfaces evidence contextually when self-efficacy dip detected.

**Backend work:** `evidence_points` table (user_id, type, source_feature, source_id, description, created_at). Background job to detect and log proof points from existing feature activity. Efficacy-dip detection logic (pattern analysis on recent Mirror/Turn language). Evidence surfacing endpoint for contextual AI integration.

**Mobile work:** Evidence Wall view in "You" tab (SVG mosaic grid, color-coded by source). Timeline toggle view. Evidence count badges. Contextual evidence card component for use within Mirror/Turn sessions.

---

## 2.4 Deep Technical Workstreams

### 2.4.1 Prompt and Output Contracts

Create strict prompt templates and JSON output contracts per feature: Mirror fragment detection, Mirror inline reframe, Turn multi-pattern output, Lens daily focus output, Rehearsal visualization script, Evidence Wall contextual surfacing. Require server-side validation of AI output shape before returning to clients.

### 2.4.2 Safety Integration

At this phase safety must be complete for user-facing flows: all Mirror and Turn requests pass safety gate, crisis response path returns resource payload (not reframe payload), safety events are queryable for audit.

### 2.4.3 Entitlement Enforcement

Enforce in API middleware: free turn daily limits, free mirror weekly limits, spectrum endpoint lock for non-entitled users. Add clear response codes and client UI handling for plan limits.

### 2.4.4 Performance Targets

Set targets now and test against them: Mirror fragment detection p95 under 3.5s, Turn generation p95 under 3.5s, client screen transitions under 300ms for cached navigation.

---

## 2.5 Build Plan

**Week 1 (Week 4 overall):**
- Finish Mirror backend and basic mobile UI
- Complete fragment highlight rendering

**Week 2 (Week 5 overall):**
- Finish inline reframe flow and session reflections
- Add Mirror history and session detail view

**Week 3 (Week 6 overall):**
- Finish Turn backend and mobile flow
- Add save/history integration

**Week 4 (Week 7 overall):**
- Finish Lens goals and daily actions
- Add daily focus/affirmation flow
- Build Rehearsal backend + mobile UI (Lens sub-feature)

**Week 5 (Week 8 overall):**
- Build Ritual backend (config, completions, consistency tracking)
- Build Ritual mobile UI (single-flow screen, SVG progress, setup flow)
- Build Evidence Wall backend (proof point collection job, evidence_points table)

**Week 6 (Week 9 overall):**
- Build Evidence Wall mobile UI (mosaic view, timeline, contextual card)
- Wire Evidence Wall contextual surfacing into Mirror/Turn sessions
- Integrate Ritual into onboarding flow

**Week 7 (Week 10 overall — hardening):**
- Optimize latency across all features
- Improve retry and offline handling
- Run end-to-end QA pass across all flows including Ritual → Mirror → Turn → Lens → Evidence

---

## 2.6 Test Plan

**Unit tests:** Prompt builder functions, AI output validators, entitlement middleware, safety decision functions.

**Integration tests:** Full Mirror message lifecycle, full Turn generation lifecycle, Lens action completion lifecycle.

**Manual QA matrix:** Normal usage, plan-limit blocked usage, low-connectivity behavior, crisis-language safety behavior.

## 2.7 Phase 2 Deliverables

**Functional:** Mirror v1 complete, Turn v1 complete, Lens v1 complete (with Rehearsal), Ritual v1 complete, Evidence Wall v1 complete, Gallery/history v1 complete.

**Engineering:** Stable endpoint contracts, documented prompt versions, meaningful test coverage for critical flows, feature-level latency and error metrics.

## 2.8 Phase 2 Exit Criteria

You can exit Phase 2 when: users can complete Mirror → Turn → Lens flow end-to-end, Ritual sequences features into a single daily flow, Rehearsal generates process-oriented visualization scripts, Evidence Wall collects and surfaces proof points, plan limits and safety behavior are consistent and test-backed, no critical P0 bugs in core user paths, telemetry confirms baseline latency and reliability targets.

## 2.9 Phase 2 Risks

- **Output variability from model causes UI breakage.** Mitigation: strict response schema validation and fallback copy.
- **Too much feature scope in one pass.** Mitigation: ship v1 flows first, defer advanced UX polish.
- **Latency drift from complex prompts.** Mitigation: simplify prompts and use cached static context.

---
---

# Cross-Phase Reference

## Combined Timeline

| Week | Phase | Focus |
|------|-------|-------|
| 1 | Phase 1 | Schema, auth, profile endpoints |
| 2 | Phase 1 | Entitlements, AI gateway, rate limits |
| 3 | Phase 1 | Feature skeletons, safety, observability |
| 4 | Phase 2 | Mirror backend + mobile UI |
| 5 | Phase 2 | Mirror inline reframes + history |
| 6 | Phase 2 | Turn backend + mobile flow |
| 7 | Phase 2 | Lens goals + daily actions + Rehearsal |
| 8 | Phase 2 | Ritual (backend + mobile + onboarding) + Evidence Wall backend |
| 9 | Phase 2 | Evidence Wall mobile + contextual surfacing integration |
| 10 | Phase 2 | Hardening, latency, end-to-end QA |

## Dependencies

- Phase 2 Mirror depends on Phase 1 AI gateway + safety precheck
- Phase 2 entitlement enforcement depends on Phase 1 plan gating middleware
- Phase 2 Lens daily actions depend on Phase 1 AI gateway being stable
- All Phase 2 features depend on Phase 1 observability for debugging

## Combined API Surface (End of Phase 2)

**Auth:** register, login, refresh, logout, me
**Billing:** entitlements, App Store + Google Play webhooks
**Mirror:** create session, send message (with fragment detection), close session (with reflection), list sessions, session detail
**Turn:** create turn (with 3 patterns + micro-action), save/unsave, list history
**Lens:** create goal, generate daily actions, complete action, daily affirmation
**Rehearsal:** generate visualization script (per goal), list rehearsal history
**Ritual:** create/update ritual config, start ritual session, complete ritual, list completions, context consistency stats
**Evidence Wall:** list proof points (filterable by type/source), get contextual evidence (for AI surfacing)
**Gallery:** list saved turns + mirror reflections + rehearsal/ritual patterns (unified history)
