# Story 1.1: Project Initialization & Architecture Setup

Status: ready-for-dev

<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->

## Story

As a Developer,
I want to initialize the project with the approved stack,
So that the team has a solid foundation to build features on.

## Acceptance Criteria

1. **Given** the repository is empty **When** I run the initialization command **Then** Next.js 14+, Tailwind, and ShadCN UI are installed

2. **Given** the project is initialized **When** I configure the Vercel Edge Proxy **Then** the API routes are ready for secure LLM calls

3. **Given** the setup is complete **When** I run the dev server **Then** the app loads with the correct "Morning Mist" theme configuration

## Tasks / Subtasks

- [ ] **Task 1: Initialize Next.js 14+ Project** (AC: 1)
  - [ ] Run `npx create-next-app@latest . --typescript --tailwind --eslint --app --no-src-dir --import-alias "@/*"`
  - [ ] Verify project structure created (app/, components/, lib/, public/)
  - [ ] Run `npm run dev` to confirm initialization successful

- [ ] **Task 2: Install and Configure ShadCN UI** (AC: 1)
  - [ ] Run `npx shadcn-ui@latest init` with default settings
  - [ ] Install core components needed for MVP: `button`, `input`, `card`, `sheet`, `dialog`, `toast`
  - [ ] Verify component library works by importing a Button component

- [ ] **Task 3: Configure "Morning Mist" Theme** (AC: 3)
  - [ ] Update `tailwind.config.ts` with custom "Morning Mist" color palette:
    - Primary Action: Slate Blue (`#64748B`)
    - Background: Off-White/Cool Grey (`#F8FAFC`)
    - Surface: White (`#FFFFFF`)
    - Text: Deep Slate (`#334155`)
    - Accents: Soft Blue (`#E2E8F0`)
  - [ ] Add custom font configuration: `Inter` for UI, `Merriweather` for content
  - [ ] Update `app/globals.css` with theme CSS variables
  - [ ] Run dev server and verify theme loads correctly

- [ ] **Task 4: Install Additional Dependencies** (AC: 1)
  - [ ] Install `zustand` (v5+) for state management
  - [ ] Install `dexie` (v4.2.1+) for IndexedDB wrapper
  - [ ] Install `next-pwa` for PWA functionality
  - [ ] Install `lucide-react` for icons
  - [ ] Verify all packages install without conflicts

- [ ] **Task 5: Setup Project Structure (Feature-First Lite)** (AC: 1)
  - [ ] Create directory structure:
    ```
    app/
    ├── (main)/          # Main Layout (Nav + content)
    ├── (session)/       # Immersive Layout (No Nav)
    └── api/             # API Routes (Edge Runtime)
    components/
    ├── features/        # Feature-specific components
    ├── ui/              # ShadCN primitives
    └── layout/          # AppShell, Header, etc.
    services/            # Business logic layer
    store/               # Zustand stores
    lib/
        ├── db/          # Dexie schema
        └── llm/         # AI service
    ```
  - [ ] Verify folder structure matches architecture specification

- [ ] **Task 6: Setup Dexie.js Schema** (AC: 1)
  - [ ] Create `lib/db/schema.ts` with table definitions:
    - `chatLogs` (id, sessionId, role, content, timestamp, synced)
    - `userProfiles` (id, settings, preferences)
  - [ ] Create `lib/db/client.ts` as Dexie instance singleton
  - [ ] Export TypeScript types from schema
  - [ ] Verify schema compiles without errors

- [ ] **Task 7: Setup Zustand Store Skeleton** (AC: 1)
  - [ ] Create `store/use-session.ts` for active session state
  - [ ] Create `store/use-settings.ts` for theme/config state
  - [ ] Use atomic selectors pattern (not destructuring)
  - [ ] Export store types

- [ ] **Task 8: Setup Vercel Edge Function Skeleton** (AC: 2)
  - [ ] Create `app/api/llm/route.ts` with Edge Runtime
  - [ ] Add `export const runtime = 'edge'`
  - [ ] Create placeholder handler for LLM proxy
  - [ ] Add environment variable placeholder for API key
  - [ ] Verify route responds (can add temporary test endpoint)

- [ ] **Task 9: Configure PWA Foundation** (AC: 1)
  - [ ] Create `public/manifest.json` with PWA metadata
  - [ ] Configure `next-pwa` in `next.config.mjs`
  - [ ] Add PWA icons to `public/icons/`
  - [ ] Add `<link rel="manifest">` to `app/layout.tsx`
  - [ ] Verify PWA manifest is accessible

- [ ] **Task 10: Service Layer Skeleton** (AC: 2)
  - [ ] Create `services/chat-service.ts` skeleton
  - [ ] Create `services/sync-manager.ts` skeleton
  - [ ] Add placeholder functions following "Logic Sandwich" pattern
  - [ ] Document that services return plain data, not Dexie observables

- [ ] **Task 11: Verification and Testing** (AC: 1, 2, 3)
  - [ ] Run `npm run dev` successfully
  - [ ] Verify no console errors on homepage
  - [ ] Verify ShadCN Button component renders
  - [ ] Verify theme colors apply correctly
  - [ ] Verify TypeScript compilation succeeds
  - [ ] Verify PWA manifest loads in DevTools

## Dev Notes

### Architecture Overview
This story establishes the "Local-First PWA" architecture. Key patterns:
- **Service Layer ("Logic Sandwich")**: UI → Zustand → Service → Dexie/LLM
- **Data Boundary**: IndexedDB is source of truth, LLM is compute-only
- **Edge Runtime**: All API routes must use Edge for <3s latency

### Source Tree Components to Touch
- `app/`: Next.js routes (App Router)
- `components/features/`: Feature-specific smart components
- `components/ui/`: ShadCN primitives
- `services/`: Business logic orchestration
- `store/`: Zustand global state
- `lib/db/`: Dexie schema and client
- `lib/llm/`: AI service integration
- `public/`: PWA manifest and icons

### Testing Standards Summary
- Manual verification: `npm run dev` starts successfully
- TypeScript compilation: No type errors
- PWA manifest validates in browser DevTools

### Project Structure Notes
**Alignment with Feature-First Lite:**
- `app/(main)/`: Routes with navigation (Home, History, Settings)
- `app/(session)/`: Routes without navigation (immersive chat)
- `components/features/`: Organized by feature (chat/, artifacts/, journal/)
- `services/`: Application logic layer separating UI from data complexity

**No conflicts detected** - repository is empty, greenfield setup.

### References

[Source: _bmad-output/planning-artifacts/architecture.md#Project Structure]
[Source: _bmad-output/project-context.md#Critical Implementation Rules]
[Source: _bmad-output/planning-artifacts/architecture.md#Data Architecture]
[Source: _bmad-output/planning-artifacts/ux-design-specification.md#Design System Foundation]

## Dev Agent Context

### Critical Architecture Patterns to Follow

1. **The "Logic Sandwich" Pattern (Service Layer)**
   - UI Components must NEVER import `lib/db` directly
   - Pattern: `UI Component` → `Zustand Store` → `Service Layer` → `Dexie/LLM`
   - Services must return *plain data objects*, not Dexie observables
   - [Source: project-context.md#Critical Implementation Rules]

2. **State Management (Zustand)**
   - ALWAYS use atomic selectors
   - Bad: `const { messages } = useChatStore()`
   - Good: `const messages = useChatStore((s) => s.messages)`
   - [Source: project-context.md#State Management]

3. **Edge Runtime Constraint**
   - All API routes under `app/api/` must use Edge Runtime
   - Code: `export const runtime = 'edge';`
   - [Source: project-context.md#Edge Runtime Constraint]

4. **Naming Conventions**
   - React Components: `PascalCase` (e.g., `ChatWindow.tsx`)
   - Database Tables: `camelCase` (e.g., `chatLogs`)
   - API Endpoints: `kebab-case` (e.g., `/api/chat-sessions`)
   - Internal Functions: `verbNoun` (e.g., `fetchUserSession`)
   - [Source: project-context.md#Naming Conventions]

### Technical Requirements

**Technology Stack (with versions):**
- Next.js 14+ (App Router)
- TypeScript (Strict Mode)
- Tailwind CSS
- ShadCN UI
- Zustand v5
- Dexie.js v4.2.1
- Auth.js v5 (Beta)
- Vercel Edge Runtime

**Code Structure (Feature-First Lite):**
```
src/
├── app/                    # Routes only. Minimal logic.
│   ├── (main)/             # Main Layout (Nav + content)
│   ├── (session)/          # Immersive Layout (No Nav)
│   └── api/                # API Routes (Edge Runtime)
├── components/
│   ├── features/           # Feature-specific logic (Smart components)
│   ├── ui/                 # Dumb/Primitive ShadCN components
│   └── layout/             # AppShell, BottomNav, Header
├── services/               # Business logic and Database orchestration
├── store/                  # Zustand stores
└── lib/
    ├── db/                 # Dexie schema and client definition
    └── llm/                # AI service
```
[Source: architecture.md#Project Structure]

### Architecture Compliance

**Database Schema (Dexie.js):**
- Tables: `chatLogs`, `userProfiles`
- Primary Keys: `id` (String UUID)
- Indices: `camelCase` (e.g., `createdAt`)
- [Source: architecture.md#Naming Patterns]

**API Response Format (Standardized Wrapper):**
```ts
type ApiResponse<T> = {
  success: boolean;
  data?: T;
  error?: { code: string; message: string };
  timestamp: string; // ISO 8601
}
```
[Source: architecture.md#Format Patterns]

**State Management:**
- Co-locate actions in store definition
- Use atomic selectors to prevent re-renders
- [Source: architecture.md#Communication Patterns]

### Library/Framework Requirements

**ShadCN UI Components to Install:**
- `button` - Primary/Secondary actions
- `input` - Chat input field
- `card` - Draft display
- `sheet` - Slide-up draft view
- `dialog` - Auth, confirmations
- `toast` - Notifications

**Custom Fonts:**
- UI Font: `Inter` or `Geist Sans` (navigation, chat, buttons)
- Content Font: `Merriweather` or `Playfair Display` (Ghostwriter draft)
[Source: ux-design-specification.md#Typography System]

**Color System ("Morning Mist"):**
- Primary Action: Slate Blue (`#64748B`)
- Background: Off-White/Cool Grey (`#F8FAFC`)
- Surface: White (`#FFFFFF`)
- Text: Deep Slate (`#334155`)
- Accents: Soft Blue (`#E2E8F0`)
[Source: ux-design-specification.md#Color System]

### File Structure Requirements

**Create these directories and files:**

```
app/
├── (main)/
│   ├── layout.tsx          # Main layout with nav
│   └── page.tsx            # Home/dashboard
├── (session)/
│   ├── layout.tsx          # Immersive layout (no nav)
│   └── chat/
│       └── page.tsx        # Active chat session
├── api/
│   └── llm/
│       └── route.ts        # LLM proxy (Edge Runtime)
├── layout.tsx
└── globals.css

components/
├── features/
│   ├── chat/               # ChatWindow, Bubble, TypingIndicator
│   ├── artifacts/          # ReflectionCard, SummaryView
│   └── journal/            # HistoryList
├── ui/                     # ShadCN components
└── layout/                 # AppShell, BottomNav, Header

lib/
├── db/
│   ├── schema.ts           # Dexie schema definitions
│   └── client.ts           # DB instance singleton
└── llm/                    # AI service (future)

services/
├── sync-manager.ts         # Offline queue handler
└── chat-service.ts         # Orchestrator (DB <-> State <-> LLM)

store/
├── use-session.ts          # Active session state
└── use-settings.ts         # Theme/config state

public/
├── manifest.json           # PWA manifest
└── icons/                  # PWA icons
```

### Testing Requirements

**Verification Steps:**
1. Run `npm run dev` - server starts on port 3000
2. Visit http://localhost:3000 - page loads without errors
3. Check browser console - no errors
4. Add a ShadCN Button component - renders correctly
5. Check theme colors - "Morning Mist" palette applied
6. Verify TypeScript: `npx tsc --noEmit` - no type errors
7. Check PWA manifest in DevTools Application tab
8. Verify Dexie types are exported correctly

**No automated tests required for this story** - testing setup comes in later stories.

### Project Context Reference

**Critical Implementation Rules:**
1. UI Components must NEVER import `lib/db` directly
2. ALWAYS use atomic selectors in Zustand
3. IndexedDB is the Source of Truth for User Data
4. All API routes must use Edge Runtime
5. Services return plain data, not Dexie observables

[Source: project-context.md]

## Dev Agent Record

### Agent Model Used

Claude Opus 4.5 (model ID: 'claude-opus-4-5-20251101')

### Debug Log References

None - project initialization story

### Completion Notes List

Story created with comprehensive context including:
- Epic 1 full context and cross-story dependencies
- Complete architecture decisions and patterns
- "Morning Mist" theme specifications
- Feature-First Lite project structure
- Service Layer pattern ("Logic Sandwich")
- Dexie.js schema requirements
- Zustand atomic selector pattern
- Edge Runtime requirements
- PWA configuration foundation

### File List

**Output File:**
- `/home/maximilienmao/Projects/Test01/_bmad-output/implementation-artifacts/1-1-project-initialization-architecture-setup.md`

**Source Documents Referenced:**
- `_bmad-output/project-context.md`
- `_bmad-output/planning-artifacts/epics.md`
- `_bmad-output/planning-artifacts/prd.md`
- `_bmad-output/planning-artifacts/architecture.md`
- `_bmad-output/planning-artifacts/ux-design-specification.md`
