# JANDA RELATIONSHIP BUILDER - COMPLETE SYSTEM DOCUMENTATION

## 🎯 EXECUTIVE SUMMARY

**Live URLs:**
- Production: https://adampowell.pro/janda/
- Login Page: https://adampowell.pro/janda/login.html

**Server:** 198.211.114.12 (root access)
### SSH Access
ssh -i "$env:USERPROFILE\.ssh\id_ed25519" root@198.211.114.12
cd /var/www/adampowell.pro/janda/

**Active Directory:** `/var/www/adampowell.pro/janda/` ⚠️ **THIS IS THE LIVE FOLDER**

**Inactive Directories:**
- `/var/www/aha-training/janda-node-OLD-20251222/` (old backup, archived 2025-12-22)
- `/var/www/adampowell.pro/janda-node/` (old files, not used)

---

## 📂 DIRECTORY STRUCTURE

### Live Application Directory
```
/var/www/adampowell.pro/janda/
├── server.js                    # Main Express application (740 lines)
├── janda.db                     # SQLite database (116 KB)
├── package.json                 # Node.js dependencies
├── package-lock.json
├── ecosystem.config.js          # PM2 process manager config
├── seed.js                      # Database seeding script
├── create-users.js              # User creation utility
├── update-passwords.js          # Password update utility
├── node_modules/                # NPM dependencies (187 packages)
├── public/                      # Frontend static files
│   ├── index.html              # Main SPA entry (30 KB - mystical theme)
│   ├── login.html              # Login page (redirects to tarot)
│   ├── tarot.html              # Tarot reading page (142 KB - full featured)
│   ├── app.js                  # Frontend JavaScript
│   ├── spa-router.js           # SPA routing (18,144 bytes)
│   ├── style.css               # Styles (7,361 bytes)
│   ├── questions.html
│   ├── gratitude.html
│   ├── appreciation.html
│   ├── exercises.html
│   └── janda/                  # Audio files for tarot
│       ├── 432Hz.mp3           # 432Hz meditation music (43 MB)
│       └── mystical-soundscape.mp3  # Ambient soundscape (45 MB)
└── nginx-*.conf                 # Nginx config references
```

---

## 🗄️ DATABASE SCHEMA

**Database Type:** SQLite3
**Location:** `/var/www/adampowell.pro/janda/janda.db`
**Size:** 116 KB
**SQLite Version:** 3.27.2

### Tables

#### 1. `users`
```sql
CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password_hash TEXT NOT NULL,
    display_name TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_login DATETIME,
    notification_enabled INTEGER DEFAULT 1,
    notification_token TEXT
);
```

**Current Users:**
- ID: 1, Username: `J`, Display Name: `J`
- ID: 2, Username: `A`, Display Name: `Adam`

**Password Hash Algorithm:** bcrypt (rounds: 10)
**Common Password:** Both users share the same bcrypt hash
- Hash: `$2b$10$6M6sKiLtPmRum9y8da2Fn.7Wd5O.CmnHhznXe0p/V8lDr/URFOriC`

#### 2. `questions`
```sql
CREATE TABLE questions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    category TEXT NOT NULL,
    difficulty TEXT NOT NULL,
    question_text TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
```
**Purpose:** Relationship questions for daily prompts

#### 3. `question_responses`
```sql
CREATE TABLE question_responses (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    question_id INTEGER NOT NULL,
    user_id INTEGER NOT NULL,
    response_text TEXT NOT NULL,
    answered_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_private INTEGER DEFAULT 0,
    FOREIGN KEY (question_id) REFERENCES questions(id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### 4. `exercises`
```sql
CREATE TABLE exercises (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    category TEXT NOT NULL,
    description TEXT NOT NULL,
    duration_minutes INTEGER,
    difficulty TEXT NOT NULL,
    instructions TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
```

#### 5. `exercise_completions`
```sql
CREATE TABLE exercise_completions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    exercise_id INTEGER NOT NULL,
    user_id INTEGER NOT NULL,
    completed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    rating INTEGER,
    notes TEXT,
    completed_together INTEGER DEFAULT 1,
    FOREIGN KEY (exercise_id) REFERENCES exercises(id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### 6. `mood_logs`
```sql
CREATE TABLE mood_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    mood_level INTEGER NOT NULL,
    energy_level INTEGER NOT NULL,
    relationship_satisfaction INTEGER NOT NULL,
    notes TEXT,
    logged_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### 7. `gratitude_entries`
```sql
CREATE TABLE gratitude_entries (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    gratitude_text TEXT NOT NULL,
    about_partner INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### 8. `goals`
```sql
CREATE TABLE goals (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    description TEXT,
    target_date DATE,
    status TEXT DEFAULT 'active',
    created_by INTEGER NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    completed_at DATETIME,
    FOREIGN KEY (created_by) REFERENCES users(id)
);
```

#### 9. `goal_progress`
```sql
CREATE TABLE goal_progress (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    goal_id INTEGER NOT NULL,
    user_id INTEGER NOT NULL,
    progress_note TEXT NOT NULL,
    progress_percentage INTEGER DEFAULT 0,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (goal_id) REFERENCES goals(id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### 10. `calendar_events`
```sql
CREATE TABLE calendar_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    description TEXT,
    event_date DATE NOT NULL,
    event_time TIME,
    location TEXT,
    created_by INTEGER NOT NULL,
    reminder_sent INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (created_by) REFERENCES users(id)
);
```

#### 11. `love_languages`
```sql
CREATE TABLE love_languages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    words_of_affirmation INTEGER DEFAULT 0,
    quality_time INTEGER DEFAULT 0,
    receiving_gifts INTEGER DEFAULT 0,
    acts_of_service INTEGER DEFAULT 0,
    physical_touch INTEGER DEFAULT 0,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### 12. `nudges`
```sql
CREATE TABLE nudges (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    from_user_id INTEGER NOT NULL,
    to_user_id INTEGER NOT NULL,
    nudge_type TEXT NOT NULL,
    message TEXT,
    sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    read_at DATETIME,
    FOREIGN KEY (from_user_id) REFERENCES users(id),
    FOREIGN KEY (to_user_id) REFERENCES users(id)
);
```

#### 13. `conversation_starters`
```sql
CREATE TABLE conversation_starters (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    category TEXT NOT NULL,
    difficulty TEXT NOT NULL,
    starter_text TEXT NOT NULL
);
```

#### 14. `appreciation_notes`
```sql
CREATE TABLE appreciation_notes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    from_user_id INTEGER NOT NULL,
    to_user_id INTEGER NOT NULL,
    note_text TEXT NOT NULL,
    is_read INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (from_user_id) REFERENCES users(id),
    FOREIGN KEY (to_user_id) REFERENCES users(id)
);
```

#### 15. `milestones`
```sql
CREATE TABLE milestones (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    description TEXT,
    milestone_date DATE NOT NULL,
    milestone_type TEXT,
    created_by INTEGER NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (created_by) REFERENCES users(id)
);
```

#### 16. `daily_checkins`
```sql
CREATE TABLE daily_checkins (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    checkin_date DATE NOT NULL,
    stress_level INTEGER,
    connection_level INTEGER,
    notes TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### 17. `tarot_readings`
```sql
CREATE TABLE tarot_readings (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    timestamp TEXT NOT NULL,
    question TEXT NOT NULL,
    spread_type TEXT NOT NULL,
    cards_drawn TEXT NOT NULL,        -- JSON string of cards
    interpretation TEXT NOT NULL,     -- AI-generated reading
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### 18. `daily_cards`
```sql
CREATE TABLE daily_cards (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    card_date TEXT NOT NULL,          -- YYYY-MM-DD format
    card_name TEXT NOT NULL,
    card_data TEXT NOT NULL,          -- JSON string of full card object
    is_reversed INTEGER NOT NULL,     -- 0 or 1
    message TEXT NOT NULL,            -- AI-generated daily message
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(user_id, card_date),       -- One card per user per day
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```
**Purpose:** Persistent daily tarot cards - one per user per day, synced across all devices

---

## 🌐 WEB SERVER CONFIGURATION

### Nginx Setup

**Version:** nginx/1.14.2
**Config File:** `/etc/nginx/sites-enabled/adampowell.pro`

**JANDA Proxy Configuration:**
```nginx
location /janda/ {
    proxy_pass http://127.0.0.1:3004/;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_read_timeout 400s;  # 6+ minutes for GPT-5-nano tarot readings with reasoning
}
```

**SSL Certificates:**
- Location: `/etc/letsencrypt/live/adampowell.pro/`
- Certificate: `fullchain.pem`
- Private Key: `privkey.pem`
- Managed by: Let's Encrypt
- Auto-renewal: Active

**HTTPS Redirect:**
All HTTP traffic (port 80) automatically redirects to HTTPS (port 443)

**Root Directory:** `/var/www/adampowell.pro/html` (for main site)

---

## ⚙️ NODE.JS APPLICATION

### Server Configuration

**Framework:** Express.js v4.18.2
**Port:** 3004 (localhost only, proxied through Nginx)
**Node Version:** v18.20.8
**NPM Version:** 10.8.2
**Process Manager:** PM2 (v5.x)

### PM2 Configuration

**Config File:** `/var/www/adampowell.pro/janda/ecosystem.config.js`

```javascript
module.exports = {
  apps: [{
    name: 'janda-app',
    script: './server.js',
    env: {
      NODE_ENV: 'production',
      PORT: 3004,
      OPENAI_API_KEY: 'REDACTED_OPENAI_KEY_2026_04_10'
    }
  }]
};
```

**PM2 Process Info:**
- Name: `janda-app`
- Status: Online
- Uptime: Variable (auto-restart on crash)
- Restarts: 39 total (as of last check)
- Mode: Fork mode
- PID File: `/root/.pm2/pids/janda-app-3.pid`
- Error Log: `/root/.pm2/logs/janda-app-error.log`
- Out Log: `/root/.pm2/logs/janda-app-out.log`

**PM2 Commands:**
```bash
pm2 list                    # List all processes
pm2 info janda-app         # Detailed process info
pm2 restart janda-app      # Restart the app
pm2 logs janda-app         # View logs
pm2 monit                  # Monitor in real-time
pm2 stop janda-app         # Stop the app
pm2 start ecosystem.config.js  # Start from config
```

### Dependencies

```json
{
  "express": "^4.18.2",           // Web framework
  "express-session": "^1.17.3",   // Session management
  "better-sqlite3": "^9.2.2",     // SQLite database driver
  "bcrypt": "^5.1.1",             // Password hashing
  "cors": "^2.8.5",               // Cross-Origin Resource Sharing
  "dotenv": "^16.3.1",            // Environment variables
  "axios": "^1.6.2"               // HTTP client for API calls
}
```

### Middleware Stack

1. **CORS** - Origin: `https://adampowell.pro`, Credentials: true
2. **express.json()** - JSON body parsing
3. **express.urlencoded()** - Form data parsing
4. **express-session** - Session management
   - Secret: `janda-secret-key-change-in-production-2024`
   - Cookie: 24 hours, httpOnly, not secure (proxied through HTTPS)
5. **express.static()** - Serves `/public` directory

---

## 🔐 AUTHENTICATION & SECURITY

### Session Management

**Type:** Server-side sessions (express-session)
**Storage:** In-memory (resets on server restart)
**Session Secret:** `janda-secret-key-change-in-production-2024`
**Cookie Settings:**
- Name: `connect.sid` (default)
- Max Age: 24 hours (86,400,000 ms)
- HttpOnly: true
- Secure: false (relies on Nginx HTTPS proxy)

### Password Security

**Algorithm:** bcrypt
**Rounds:** 10
**Storage:** `users.password_hash` column

### Authentication Middleware

```javascript
const requireAuth = (req, res, next) => {
    if (!req.session.userId) {
        return res.status(401).json({ error: 'Unauthorized' });
    }
    next();
};
```

All protected endpoints use `requireAuth` middleware.

### User Credentials

**User 1:**
- Username: `J`
- Display Name: `J`
- Password: (hashed - same as User 2)

**User 2:**
- Username: `A`
- Display Name: `Adam`
- Password: (hashed - same as User 1)

---

## 📡 API ENDPOINTS

### Authentication Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| POST | `/api/login` | No | Login with username/password |
| POST | `/api/logout` | No | Destroy session |
| GET | `/api/session` | No | Check current session |

### User Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/users/partner` | Yes | Get partner user info |

### Christmas Card Endpoints (Special Feature)

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/christmas-card/check` | Yes | Check if card should show (J only) |
| POST | `/api/christmas-card/dismiss` | Yes | Dismiss Christmas card |

### Questions Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/questions/daily` | Yes | Get 5 daily questions (rotates) |
| POST | `/api/questions/answer` | Yes | Submit answer to question |
| GET | `/api/questions/stats` | Yes | Get answer statistics |

### Gratitude Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/gratitude` | Yes | Get recent gratitude entries (50 limit) |
| POST | `/api/gratitude` | Yes | Create gratitude entry |

### Appreciation/Love Notes Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/appreciation` | Yes | Get sent/received notes (50 limit) |
| POST | `/api/appreciation` | Yes | Send appreciation note to partner |
| POST | `/api/appreciation/:id/read` | Yes | Mark note as read |

### Mood Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/mood` | Yes | Get recent mood logs (20 limit) |
| POST | `/api/mood` | Yes | Log mood entry |
| GET | `/api/mood/average` | Yes | Get mood averages (user & partner) |

### Exercises Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/exercises` | Yes | Get all exercises with completion status |
| POST | `/api/exercises/:id/complete` | Yes | Mark exercise as completed |

### Tarot Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/tarot/daily` | Yes | Get daily card (database-backed, one per day) |
| POST | `/api/tarot` | Yes | Get AI tarot reading with personalization |
| POST | `/api/tarot/save` | Yes | Save tarot reading to database |
| POST | `/api/tarot/reading` | Yes | Alternative tarot reading endpoint |
| GET | `/api/tarot/history` | Yes | Get reading history (paginated) |
| GET | `/api/tarot/reading/:id` | Yes | Get specific reading by ID |
| DELETE | `/api/tarot/reading/:id` | Yes | Delete a reading |

**Daily Card Features:**
- Returns existing card if already drawn today
- Generates new card + AI message if first draw of the day
- Includes time-awareness (morning/afternoon/evening)
- References lunar phase and season in message
- Auto-generates full reading for card

### Dashboard Endpoints

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | `/api/dashboard/stats` | Yes | Get comprehensive dashboard stats |

### Static Files

| Route | Description |
|-------|-------------|
| `/*` (static) | Serves files from `/public` directory |
| `/*` (fallback) | Returns `index.html` for SPA routing |

---

## 🤖 AI INTEGRATION (TAROT FEATURE)

### OpenAI API

**Model:** `gpt-5-nano` (Upgraded from gpt-4o-mini on 2025-12-23)
**API Key:** (Stored in `ecosystem.config.js`)
- Key: `REDACTED_OPENAI_KEY_2026_04_10`

**Endpoint:** `https://api.openai.com/v1/responses` (GPT-5-nano format)

**Configuration:**
- Max Output Tokens: 15000 (increased from 6000)
- Timeout: 360 seconds (6 minutes - increased from 120s to accommodate GPT-5-nano reasoning)
- Server-level Timeout: 360 seconds (req.setTimeout and res.setTimeout)
- Response Format: Structured output with message arrays

**Persona:** Master Eliana Moonweaver (legendary tarot reader with 40 years experience)

**Reading Length:** 1200-1800 words per reading

**Fallback:** If API fails, generates a fallback reading using template

### Personalization Features

**User Context:**
- Names: Jenna (user J) and Adam (user A) - always addressed by name, never "seeker"
- Birthdates: Jenna (Jan 5, 1994), Adam (Jan 14, 1992)
- Astrological Signs: Both Capricorn ♑ - readings incorporate Capricorn traits
- Gender Energy: Feminine (Jenna) and Masculine (Adam) energy contexts

**Pet Context (Pet Tarot Readings):**
- Mickey: Boy cow cat (born June 20, 2025) - quiet, reserved, sweet, loyal, thoughtful energy
- Nala: Girl Torbie cat (born Nov 15, 2022) - energetic, playful, sweet, loyal, protective

**Cosmic Context:**
- Lunar Phase: Tracks 8 moon phases with associated energies
- Season: Winter/Spring/Summer/Autumn with seasonal themes
- Time of Day: Morning/afternoon/evening awareness for daily cards

**Historical Context:**
- Last 3 readings tracked for pattern recognition
- Recurring cards acknowledged
- Spiritual journey continuity emphasized

### Available Spreads

**Foundational (3 cards):**
1. Past • Present • Future
2. Situation • Action • Outcome
3. Mind • Body • Spirit
4. Challenge • Help • Outcome

**Personal (3-4 cards):**
5. 🦋 Sacred Healing • Transformation (3 cards)

**Relationship (4-5 cards):**
6. 💕 Sacred Union (Couples Spread - 5 cards) - requires partner names
7. ✨ Anniversary • Celebration (4 cards) - requires partner names

**Cosmic (4-5 cards):**
8. 🌙 New Moon • Manifestation (4 cards)
9. ⭐ The Year Ahead • Destiny (5 cards)

**Companion (4 cards):**
10. 🐾 Pet & Companion Guidance (4 cards) - specialized for Mickey & Nala

---

## 🔄 DEPLOYMENT & UPDATES

### Git Integration

**Repository:** Connected to GitHub
**Webhook:** `/gitwebhook` endpoint on port 3005
**Webhook Server:** `/var/www/adampowell.pro/github-webhook.js`

**Current Git Status (adampowell.pro):**
- Branch: `main`
- Modified: `SYSTEM.md`, `janda-node/public/tarot.html`
- Untracked: Audio files (432Hz.mp3, mystical-soundscape.mp3)

### Deployment Workflow

1. Push changes to GitHub
2. GitHub webhook triggers update
3. Webhook server pulls latest changes
4. PM2 auto-restarts application (if needed)

### Manual Deployment

```bash
# SSH into server
ssh -i "$env:USERPROFILE\.ssh\id_ed25519" root@198.211.114.12

# Navigate to directory
cd /var/www/adampowell.pro/janda

# Pull latest changes
git pull

# Install dependencies (if needed)
npm install

# Restart PM2 process
pm2 restart janda-app

# Check status
pm2 status
```

---

## 🛠️ UTILITIES & SCRIPTS

### Database Scripts

**`seed.js`** - Seeds database with:
- Relationship questions (seeded from CSV)
- Exercises
- Conversation starters

**`create-users.js`** - Creates initial user accounts

**`update-passwords.js`** - Updates user passwords

### Nginx Config Files

- `nginx-current.conf` - Current nginx config
- `nginx-proxy.conf` - Proxy configuration reference
- `nginx-proxy2.conf` - Alternate proxy config

---

## 📊 SYSTEM ARCHITECTURE DIAGRAM

```
Internet (HTTPS)
       |
       ↓
  Nginx (Port 443)
  SSL Termination
       |
       ↓
  Proxy: /janda/ → localhost:3004
       |
       ↓
  Node.js/Express (Port 3004)
  [PM2 Process Manager]
       |
       ↓
  SQLite Database (janda.db)
       |
  [AI Integration] → OpenAI API (GPT-4o-mini)
```

---

## 🔧 MAINTENANCE TASKS

### Regular Maintenance

**Database Backup:**
```bash
cd /var/www/adampowell.pro/janda
sqlite3 janda.db ".backup 'janda-backup-$(date +%Y%m%d).db'"
```

**View Logs:**
```bash
pm2 logs janda-app
pm2 logs janda-app --lines 100
```

**Monitor Performance:**
```bash
pm2 monit
pm2 info janda-app
```

**Restart Application:**
```bash
pm2 restart janda-app
```

**Check SSL Certificate Expiry:**
```bash
certbot certificates
```

**Renew SSL Certificates:**
```bash
certbot renew
nginx -s reload
```

### Troubleshooting

**App Not Responding:**
```bash
pm2 restart janda-app
pm2 logs janda-app --err
```

**Database Locked:**
```bash
# Check for active connections
lsof /var/www/adampowell.pro/janda/janda.db

# Restart app
pm2 restart janda-app
```

**502 Bad Gateway:**
```bash
# Check if Node app is running
pm2 status

# Check nginx config
nginx -t

# Restart nginx
systemctl restart nginx
```

**Questions Showing Old Answered Questions:**
```bash
# Check database statistics
sqlite3 /var/www/adampowell.pro/janda/janda.db "
SELECT
  (SELECT COUNT(*) FROM questions) as total_questions,
  (SELECT COUNT(DISTINCT question_id) FROM question_responses WHERE user_id = 1) as j_answered,
  (SELECT COUNT(DISTINCT question_id) FROM question_responses WHERE user_id = 2) as adam_answered;
"

# Check if questions endpoint has proper filtering logic (server.js lines 287-317)
ssh -i "$env:USERPROFILE\.ssh\id_ed25519" root@198.211.114.12 "sed -n '287,320p' /var/www/adampowell.pro/janda/server.js"

# Should see NOT IN subquery filtering by user_id, not simple LIMIT/OFFSET
# If wrong logic, restore from backup:
cd /var/www/adampowell.pro/janda
cp server.js.backup.20260112_074526 server.js
pm2 restart janda-app
```

**Editing server.js (Lessons Learned 2026-01-12):**
```bash
# ❌ AVOID: Python regex (fails with nested braces)
# ❌ AVOID: Node.js in bash heredoc (backticks interpreted as commands)
# ❌ AVOID: Sed with complex multiline insertions (mangles code)

# ✅ RECOMMENDED: Python exact string replacement
# 1. Create Python script that matches ENTIRE old code block as one string
# 2. Replace with ENTIRE new code block as one string
# 3. Validate syntax: node -c server.js
# 4. Restart: pm2 restart janda-app
# 5. Test: curl http://localhost:3004/api/questions/daily

# Always create backup before editing:
cp server.js server.js.backup.$(date +%Y%m%d_%H%M%S)
```

**404 Errors on /janda/ URLs:**
```bash
# Check if nginx has /janda/ location block
grep -A 10 "location /janda/" /etc/nginx/sites-enabled/adampowell.pro

# If missing, restore from backup or add manually:
# location = /janda { return 302 /janda/; }
# location /janda/ {
#     proxy_pass http://127.0.0.1:3004/;
#     proxy_http_version 1.1;
#     proxy_set_header Host $host;
#     proxy_set_header X-Real-IP $remote_addr;
#     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#     proxy_set_header X-Forwarded-Proto https;
#     proxy_read_timeout 400s;
# }

# Test and reload nginx
nginx -t && systemctl reload nginx
```

---

## 🔑 CRITICAL FILES & CREDENTIALS

### Files to NEVER Delete

- `/var/www/adampowell.pro/janda/janda.db` - **DATABASE**
- `/var/www/adampowell.pro/janda/server.js` - **APPLICATION**
- `/var/www/adampowell.pro/janda/ecosystem.config.js` - **PM2 CONFIG**
- `/etc/nginx/sites-enabled/adampowell.pro` - **NGINX CONFIG**
- `/etc/letsencrypt/live/adampowell.pro/` - **SSL CERTS**

### Sensitive Data

**OpenAI API Key:**
```
REDACTED_OPENAI_KEY_2026_04_10
```

**Session Secret:**
```
janda-secret-key-change-in-production-2024
```

**SSH Key Path (Local):**
```
$env:USERPROFILE\.ssh\id_ed25519
```

**Server Root Access:**
```
root@198.211.114.12
```

---

## 📈 PERFORMANCE METRICS

**Current Status (as of 2026-01-12):**
- Heap Usage: 55.74%
- Used Heap: 12.75 MiB
- Total Heap: 22.88 MiB
- Event Loop Latency (p95): 0.88 ms
- Uptime: Variable (PM2 auto-restarts)
- Total Restarts: 198 (includes fixes and deployments)

---

## 🚨 IMPORTANT NOTES

1. **CONSOLIDATED DIRECTORY** - Everything now in `/var/www/adampowell.pro/janda/` (migrated 2025-12-22)
2. **Database is SQLite** - Single file, easy to backup but single-threaded
3. **Sessions are in-memory** - Lost on server restart
4. **OpenAI API Key is hardcoded** - Should be moved to environment variable
5. **No HTTPS on localhost** - Relies on Nginx SSL termination
6. **PM2 manages process** - Auto-restarts on crash
7. **Nginx proxies /janda/** - Routes to port 3004
8. **Both users share same password** - Security consideration
9. **Audio files included** - 432Hz meditation (43MB) + mystical soundscape (45MB) for tarot feature
10. **Questions prioritize unanswered** - Fixed 2026-01-12: daily questions endpoint (lines 287-317) uses NOT IN subquery to show unanswered questions first
11. **server.js backup available** - Clean backup at `server.js.backup.20260112_074526` if questions logic needs restoration

---

## 🎯 QUICK REFERENCE COMMANDS

### SSH Access
```bash
ssh -i "$env:USERPROFILE\.ssh\id_ed25519" root@198.211.114.12
```

### Navigate to App
```bash
cd /var/www/adampowell.pro/janda
```

### Common Operations
```bash
# View running processes
pm2 list

# Restart app
pm2 restart janda-app

# View logs
pm2 logs janda-app

# Edit server code
nano server.js

# Database access
sqlite3 janda.db

# Check nginx config
nginx -t

# Reload nginx
nginx -s reload

# Check app status
curl http://localhost:3004/api/session
```

---

## 📝 CHANGELOG

**2026-01-12 (Critical Nginx and Questions Database Fixes):**
- 🔧 **Fixed Missing Nginx Configuration** - Restored /janda/ location blocks after they were accidentally removed:
  - **Issue**: Website returning 404 errors at https://adampowell.pro/janda/login.html
  - **Root Cause**: Nginx configuration was missing /janda/ location blocks in both HTTP and HTTPS server blocks
  - **Fix Applied**:
    - Restored nginx config from backup (adampowell.pro.backup.20260112_073447)
    - Added /janda/ location blocks to both HTTP (port 80) and HTTPS (port 443) server blocks using Python script
    - Configuration now properly proxies /janda/ requests to localhost:3004
    - Includes 400s timeout for long GPT-5-nano tarot readings
  - **Result**: Website immediately accessible at https://adampowell.pro/janda/
  - **Files Modified**: /etc/nginx/sites-enabled/adampowell.pro
- 🐛 **Fixed Questions Database Showing Old Answered Questions** - Updated daily questions rotation to prioritize unanswered:
  - **Issue**: Questions page showing old/answered questions instead of new unanswered ones after hard refresh
  - **Root Cause**: Daily questions endpoint used simple day-based rotation without checking if current user had already answered
  - **Statistics**: 50 total questions, 45 answered by Adam, only 11 answered by J (39 unanswered for J), 5 unanswered for Adam
  - **Previous Logic** (lines 287-291):
    ```javascript
    const total = db.prepare('SELECT COUNT(*) as count FROM questions').get().count;
    const perDay = 5;
    const offset = (dayNum * perDay) % Math.max(1, total - perDay);
    let questions = db.prepare('SELECT * FROM questions LIMIT ? OFFSET ?').all(perDay, offset);
    ```
    - Rotated through all 50 questions based on day number
    - Offset: `(dayNum * 5) % (total - 5)`
    - Showed same 5 questions every 10 days regardless of answer status
  - **New Logic** (lines 287-317):
    ```javascript
    const perDay = 5;

    // Get unanswered questions first (questions current user hasn't answered)
    const unansweredQuestions = db.prepare(`
        SELECT * FROM questions
        WHERE id NOT IN (
            SELECT question_id FROM question_responses
            WHERE user_id = ?
        )
        ORDER BY id
    `).all(req.session.userId);

    // Get answered questions (as fallback if not enough unanswered)
    const answeredQuestions = db.prepare(`
        SELECT * FROM questions
        WHERE id IN (
            SELECT question_id FROM question_responses
            WHERE user_id = ?
        )
        ORDER BY id
    `).all(req.session.userId);

    // Combine: prioritize unanswered, then answered
    const allQuestionsOrdered = [...unansweredQuestions, ...answeredQuestions];
    const total = allQuestionsOrdered.length;

    // Calculate rotating offset based on day
    const offset = (dayNum * perDay) % Math.max(1, total - perDay + 1);

    // Get 5 questions for today
    let questions = allQuestionsOrdered.slice(offset, offset + perDay);

    // If we don't have enough, wrap around
    if (questions.length < perDay && total > 0) {
        const remaining = perDay - questions.length;
        questions = questions.concat(allQuestionsOrdered.slice(0, remaining));
    }
    ```
    - Queries unanswered questions first using NOT IN subquery
    - Falls back to answered questions if not enough unanswered
    - Applies day-based rotation to prioritized list
    - Wraps around if needed to always show 5 questions
  - **Fix Attempts** (Multiple failures before success):
    1. ❌ Python regex replacement - Pattern didn't match nested braces correctly
    2. ❌ Node.js template string in bash heredoc - Bash interpreted backticks as command substitution
    3. ❌ Node.js line-by-line replacement - Line count calculation off, syntax error at line 374
    4. ❌ Node.js array-based replacement - Incorrect line count (53 not 54), syntax error at line 367
    5. ❌ Sed script with deletion + insertion - Mangled code into one line, old line not deleted, duplicate `let questions`
    6. ✅ Python exact string replacement - Matched entire old code block, replaced successfully
  - **Result**: Users now see their unanswered questions first before revisiting old ones
  - **Files Modified**: /var/www/adampowell.pro/janda/server.js (lines 287-317)
  - **Backup Created**: server.js.backup.20260112_074526
  - **Service Restarted**: pm2 restart janda-app (restart #198)
  - **Verification**: Syntax check passed (`node -c`), application responding, PM2 status online
- ✅ **System Verification**:
  - PM2 janda-app process online and stable
  - Nginx configuration valid (nginx -t passed)
  - Nginx reloaded successfully
  - Website accessible at https://adampowell.pro/janda/
  - Questions now properly filtered for each user

**2025-12-24 (Christmas Eve - Final Release Preparation):**
- 🎁 **Christmas Release Readiness Review** - Comprehensive verification that JANDA is ready as Christmas gift:
  - **Authentication System**: Verified login, remember me, session management, logout all working
  - **Database Status**: Confirmed 2 users (J & Adam), 50 questions, 12 exercises, 16 tables, backup present
  - **All Features Tested**: Dashboard stats, Questions, Gratitude, Love Notes, Exercises all functional
  - **Christmas Card**: Beautiful animated card with snowflakes shows on first visit for user J
  - **Tarot System**: All 9 spreads working (including Pet & Companion Guidance for Mickey & Nala)
  - **Daily Card**: Personalized messages from Master Eliana working perfectly
  - **UI/UX**: Mystical purple/gold theme throughout, responsive design, mobile optimized
  - **Production Status**: Running on 198.211.114.12, PM2 stable, NGINX configured, HTTPS active
- ⚡ **Critical Performance Fixes** - Eliminated 504 Gateway Timeout errors on complex tarot readings:
  - **Nginx Timeout**: Increased `proxy_read_timeout` from 90s to 400s (6+ minutes) in `/etc/nginx/sites-enabled/adampowell.pro`
  - **Server.js Timeout**: Increased axios timeout from 180s to 360s (6 minutes) for both tarot endpoints
  - **Server-level Timeouts**: Added `req.setTimeout(360000)` and `res.setTimeout(360000)` to tarot endpoints
  - **Impact**: 5-card spreads (1200-1800 words) now complete successfully with GPT-5-nano reasoning time
  - **Deployment**: Updated nginx config uploaded to server, nginx reloaded, no downtime
- 🔮 **Master Eliana Prompt Restructure** - Fixed AI persona to focus on tarot card interpretation vs practical advice:
  - **Issue**: Master Eliana was acting like consultant giving bullet-point checklists and action plans instead of mystical tarot reader
  - **Root Cause**: Prompt emphasized "PRACTICAL steps" and "CONCRETE advice" too heavily
  - **Fix Applied**:
    - Moved anti-AI-bot warning to TOP of prompt (read first before anything else)
    - Changed "Practical & Spiritual Wisdom" → "Spiritual Wisdom"
    - Removed all references to "CONCRETE advice", "PRACTICAL steps", "step-by-step plans"
    - Emphasized "TAROT CARD INTERPRETATION and archetypal symbolism"
    - Explicitly forbid: bullet points, numbered lists, timelines, action checklists, follow-up offers
    - Refocused sections: "The Card's Symbolism" (archetypal meaning), "Spiritual Wisdom" (mystical insights)
  - **Result**: Readings now immersive mystical tarot interpretations ("Symbol Unveiled", "archetypal significance", "spiritual wisdom") instead of consultant advice
  - **Testing**: Confirmed with 5-card Year Ahead spread - no bullet points, no follow-up offers, pure tarot symbolism
- ✅ **Security Review Completed**:
  - Session-based auth with bcrypt password hashing verified
  - All API endpoints protected with requireAuth middleware
  - Parameterized queries prevent SQL injection
  - OpenAI API key hardcoded (acceptable for private gift website)
  - HTTPS via Let's Encrypt SSL, auto-renewal active
- 📊 **System Verification**:
  - **Git Status**: All changes committed and pushed to main branch
  - **Nginx**: Config syntax validated, service reloaded successfully
  - **PM2**: janda-app process online and stable (uptime tracking, auto-restart enabled)
  - **Audio Files**: 432Hz.mp3 (43MB) and mystical-soundscape.mp3 (45MB) present
  - **Logs**: No critical errors, last timeout error from before fix deployment
- 🎄 **Final Verdict**: ✅ READY FOR CHRISTMAS MORNING - All features functional, beautifully designed, performance optimized, secure and stable

**2025-12-30 (Post-Launch Fixes & Enhancements):**
- 🔧 **Fixed 403 Forbidden Error** - Restored missing Nginx configuration for /janda/ location:
  - **Issue**: Website returning 403 Forbidden after creating another website on same server
  - **Root Cause**: `/janda/` location block was removed from `/etc/nginx/sites-enabled/adampowell.pro`
  - **Fix**: Re-added complete location block with proper proxy settings to port 3004
  - **Configuration Added**:
    ```nginx
    location = /janda { return 302 /janda/; }
    location /janda/ {
        proxy_pass http://127.0.0.1:3004/;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_read_timeout 400s;
    }
    ```
  - **Result**: Website immediately accessible at https://adampowell.pro/janda/
- 🐛 **Fixed Auto-Refresh Bug on Questions Page** - Eliminated page refreshes while typing:
  - **Issue**: questions.html refreshing every 30 seconds, destroying user's typed text mid-answer
  - **Root Cause**: Aggressive auto-sync polling interval (30s) without checking if user is typing
  - **Fixes Applied**:
    - Added `isUserTyping()` helper function to detect active textarea/input focus
    - Increased auto-refresh interval from 30 seconds to 5 minutes (10x reduction)
    - Modified all refresh events (visibility change, focus, interval) to check `isUserTyping()` first
    - Refresh only occurs when user is NOT actively typing in a form field
  - **Result**: Users can now type answers without interruption while still getting partner updates
- 🔒 **Answer Privacy Feature** - Hide partner answers until both users respond:
  - **Previous Behavior**: Could see partner's answer immediately after they submitted (spoiled the reveal)
  - **New Behavior**:
    - If neither answered: Show answer form for both
    - If only you answered: Show your answer + beautiful "⏳ Waiting for Partner's answer..." message
    - If both answered: 🎉 Reveal both answers simultaneously
  - **UX Enhancement**: Added purple gradient waiting state with hourglass emoji and message
  - **Impact**: Creates anticipation and shared discovery moment when both complete a question
  - **Files Modified**: `/var/www/adampowell.pro/janda/public/questions.html`

**2025-12-23 (Late Evening - Pet Reading Frontend Restoration):**
- 🐾 **Restored Pet & Companion Guidance Spread to Frontend** - Re-added missing spread option to tarot UI:
  - **Issue**: Pet reading spread was implemented in backend but missing from frontend tarot.html
  - **Fix**: Added 'pet-guidance' spread type to tarot.html spreadTypes object
  - **Spread Details**: 4-card spread (Your Companion's Energy, The Bond You Share, Guidance & Care, Spiritual Message)
  - **Category**: companion
  - **Result**: Users can now select pet readings from the UI dropdown menu
  - **Specialized For**: Mickey & Nala tarot readings with Master Eliana's deep understanding of their personalities

**2025-12-23 (Late Evening - Critical Bug Fix):**
- 🐛 **Fixed getLunarPhase() TypeError** - Resolved server crash causing daily cards and readings to fail:
  - **Issue**: Variables `year` and `month` were declared as `const` but reassigned during lunar phase calculation
  - **Symptoms**: TypeError "Assignment to constant variable" at server.js:81, 504 Gateway Timeout on tarot readings
  - **Impact**: Daily cards slow to render, full readings failing with timeout errors
  - **Fix**: Changed `const year` and `const month` to `let` declarations in getLunarPhase() function
  - **Result**: Daily cards now render instantly, cosmic alignment features working properly

**2025-12-23 (Evening - Deep Personalization & Pet Tarot):**
- 🎭 **Comprehensive Reading Personalization** - Master Eliana now provides deeply personal, context-aware readings:
  - **Astrological Integration**: Jenna (Capricorn ♑, Jan 5, 1994) and Adam (Capricorn ♑, Jan 14, 1992) readings incorporate Capricorn traits
  - **Name-Based Intimacy**: All readings use "Dearest Jenna" or "Beloved Adam" - NEVER generic "seeker" language
  - **Gender Energy Context**: Readings consider feminine/masculine energies and how they relate to individual perspectives
- 🐾 **Pet/Cat Tarot Readings** - New dedicated spread for beloved animal companions:
  - **New Spread**: "🐾 Pet & Companion Guidance" (4-card spread: Pet's Energy, Bond Together, Guidance & Care, Spiritual Message)
  - **Mickey & Nala Personalization**: Master Eliana knows their personalities, birthdays, and unique energies
    - Mickey (boy, cow cat, born June 20, 2025): Quiet, reserved, deeply sweet and loyal, thoughtful masculine energy
    - Nala (girl, Torbie, born Nov 15, 2022): Energetic, playful, sweet, fiercely loyal, protective, vibrant feminine energy
  - **Spiritual Bond Recognition**: Readings honor cats as mystical beings who walk between worlds and serve as spiritual teachers
  - **Practical + Mystical Guidance**: Balances esoteric wisdom with actionable care advice
- 🌙 **Cosmic Alignment System** - Readings now aware of natural cycles:
  - **Lunar Phase Integration**: Tracks 8 moon phases (New Moon, Waxing Crescent, First Quarter, Waxing Gibbous, Full Moon, Waning Gibbous, Last Quarter, Waning Crescent)
  - **Seasonal Awareness**: Readings incorporate Winter/Spring/Summer/Autumn energies
  - **Dynamic Context**: "The moon is 🌕 Full Moon (illumination, completion, release), and we are in Winter (introspection, rest, inner work)"
- 📖 **Reading History Context** - Spiritual growth tracking across readings:
  - **Pattern Recognition**: Master Eliana references your last 3 readings
  - **Recurring Card Awareness**: If The Empress keeps appearing, she'll acknowledge and explore why
  - **Journey Continuity**: "I notice The Tower appeared three days ago, and now The Star—a beautiful progression from breakdown to hope"
  - **Temporal Awareness**: Shows days since previous readings and their themes
- ⏰ **Time-Aware Daily Cards** - Messages adapt to when you draw them:
  - **Morning** (before noon): "as you begin this day" - offers wisdom to carry through the day ahead
  - **Afternoon** (noon-5pm): "in this afternoon moment" - provides insight for hours that remain
  - **Evening** (after 5pm): "as you reflect on this day" - invites reflection and preparation for tomorrow
  - **Cosmic Context Included**: Daily cards now reference current moon phase and season
- 💾 **Daily Card Persistence** - Database-backed daily cards (one per day per user):
  - **New Database Table**: `daily_cards` stores user_id, card_date, card_data, is_reversed, AI message
  - **UNIQUE Constraint**: (user_id, card_date) prevents multiple cards per day
  - **Cross-Device Sync**: Same card appears whether on phone, tablet, or desktop
  - **Full Reading Integration**: Daily card automatically generates full Master Eliana reading
  - **Mystical Loading Experience**: Pulsing crystal ball with "Master Eliana is Channeling..." messages

**2025-12-23 (Afternoon - iPhone 16 Mobile Optimizations):**
- 📱 **Mobile-First Responsive Design** - Comprehensive iPhone 16 optimization across JANDA system:
  - Fixed Jenna's welcome modal on mobile (responsive padding/font sizes)
  - Header navigation now stacks vertically on mobile instead of squishing together
  - Navigation links visible and properly wrapped on all mobile devices
  - Volume button resized for mobile (48px collapsed, 240px expanded)
  - Card title overflow prevented with proper word wrapping
- 🐛 **Mobile Bug Fixes:**
  - Audio system now restarts music when unmuting
  - Daily card displays instantly with async message loading (no delay)
  - Full reading flow from daily card properly transitions to reading interface
  - Navigation buttons no longer disappear when navigating between pages on mobile
- 🎯 **UX Improvements:**
  - Login now redirects to dashboard instead of tarot (better first-time experience)
  - Mobile viewport scaling optimized (768px, 430px, 393px breakpoints)
  - Touch-friendly interface with proper spacing and sizing
- 🧹 **Code Cleanup:**
  - Removed all testing screenshot directories and diagnostic scripts
  - Cleaned up temporary debugging tools

**2025-12-22 (Night - UI/UX Enhancements):**
- ✨ **Unified Mystical Theme** - Applied purple/gold sacred tarot aesthetic across entire application:
  - Transformed dashboard, questions, gratitude, exercises, love notes pages
  - Cinzel font for headings, Cormorant Garamond for body text
  - Deep purple gradients (#8b5cf6, #a78bfa) with gold accents (#ffd700)
  - Added mystical animations (fadeIn, slideUp, glow-pulse, float)
  - Golden glow hover effects on cards and buttons
  - Cohesive immersive experience throughout application
- 🔮 **Tarot Page Improvements:**
  - Fixed nav bar z-index - always visible above particle field
  - Updated navbar links from .php to correct SPA routes
  - Added all navigation sections (Dashboard, Questions, Exercises, Gratitude, Love Notes)
  - Jenna's welcome message now shows every time for user J (fetches from session API)
  - Scroll-to-top on stage changes for proper positioning
- 💕 **Ask Together Mode Enhancements:**
  - Removed separate ritual preparation modal
  - Integrated 60-second couple's breathwork meditation
  - New meditation phases: "Hug → Hold hands & close eyes → Hearts synchronize → Sacred bond"
  - Dual breathing circles (purple & gold) for couples
  - Works with all spreads, not just couple-specific ones
  - Seamless flow from question to meditation to card dealing
- 🎵 **Audio System Fixes:**
  - Removed autoplay (browser blocked without user interaction)
  - Music now starts when user clicks "Begin Reading" button
  - Smooth 45% volume fade during meditation phase
  - Added fadeToVolume() method for smooth audio transitions
  - Complies with browser autoplay policies
- 🚀 **Navigation & UX:**
  - Login now redirects to /janda/#tarot (tarot-first experience)
  - Removed duplicate Quick Actions from dashboard
  - Streamlined UI with single navigation in header
- 📖 **Documentation:**
  - Added comprehensive "How to Use" guide modal
  - Explains all features: Daily Card, Full Reading, Reading Modes, 9 Sacred Spreads
  - Mystical purple/gold themed guide with scrollable content
  - Master Eliana Moonweaver signature

**2025-12-22 (Evening):**
- 🎵 Added 5 legendary tarot features (Christmas gift for Jenna):
  - Binaural beats & meditation music system (432Hz + mystical soundscape)
  - Personal welcome message for Jenna
  - Daily card draw feature
  - 4 new special occasion spreads (Anniversary, New Moon, Year Ahead, Healing)
  - "Ask Together" couple's ritual mode
- 📂 **MAJOR MIGRATION:** Consolidated all files from `/var/www/aha-training/janda-node/` to `/var/www/adampowell.pro/janda/`
- Updated PM2 configuration to new location
- Backed up database before migration (janda-backup-20251222-163724.db)
- Archived old directory as janda-node-OLD-20251222

**2025-12-22 (Morning):**
- Tarot reading system implemented
- OpenAI GPT-4o-mini integration
- Master Eliana Moonweaver persona
- Tarot history and storage features
- Christmas card feature for user 'J'
- Question seeding from CSV files
- Relationship exercises added

**Earlier:**
- Initial application deployment
- User authentication system
- Mood tracking, gratitude, appreciation features
- Dashboard statistics

---

## 🔮 FUTURE IMPROVEMENTS

1. **Move API keys to .env file** - Remove hardcoded secrets
2. **Implement persistent sessions** - Use Redis or database sessions
3. **Add SSL to session cookies** - Set secure: true flag
4. **Database migrations** - Track schema changes
5. **Automated backups** - Cron job for daily database backups
6. **Monitoring & Alerts** - Set up uptime monitoring
7. **Rate limiting** - Prevent API abuse
8. **Input validation** - Add request validation middleware
9. **HTTPS redirect in app** - Don't rely solely on Nginx
10. **Separate dev/prod configs** - Use NODE_ENV properly

---

**Document Version:** 1.5
**Last Updated:** 2026-01-12 (Critical Fixes - Nginx & Questions Database)
**Author:** System Documentation (Claude Code)
**Contact:** root@198.211.114.12
