# Atlas

**Your calm chief of staff and focus copilot**

Atlas is a production-ready, executive-grade personal operating system designed for daily, heavy use by individuals with ADHD. It combines a voice-first iPhone PWA, an orchestrating broker server, and a Windows PC agent to provide seamless focus support, task management, and real-world action execution.

## Core Promise

```
Atlas is calm when you're overwhelmed.
Atlas remembers so you don't have to.
Atlas moves you forward, one tiny step at a time.
Atlas never judges, never shames, never overwhelms.
Atlas is worthy of your trust.
```

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                     iPhone PWA                               │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐           │
│  │  Voice  │ │  Todos  │ │ Memory  │ │ Agent   │           │
│  │ WebRTC  │ │NOW/NEXT │ │ Review  │ │ Control │           │
│  └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘           │
│       │           │           │           │                 │
│       └───────────┴───────────┴───────────┘                 │
│                         │                                    │
│              IndexedDB (Offline Store)                       │
└─────────────────────────┬───────────────────────────────────┘
                          │ HTTPS/WSS
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                    Broker Server                             │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐       │
│  │   Auth   │ │  Context │ │   Jobs   │ │  OpenAI  │       │
│  │  Tokens  │ │   CRUD   │ │  Queue   │ │  Proxy   │       │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘       │
│                         │                                    │
│              SQLite + Context Files                          │
└─────────────────────────┬───────────────────────────────────┘
                          │ WSS (Outbound)
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                     PC Agent                                 │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐       │
│  │   File   │ │  Script  │ │ Browser  │ │ Rollback │       │
│  │   Ops    │ │  Runner  │ │Playwright│ │  System  │       │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘       │
└─────────────────────────────────────────────────────────────┘
```

## Features

### Phase 1: Foundation ✅
- [x] Project structure with all directories
- [x] Broker server skeleton with health endpoint
- [x] PWA shell with manifest and service worker
- [x] 8-tab interface (Home, Todos, Coaching, Decisions, Memory, Agent, Learning, Workflows)
- [x] Offline-first architecture
- [x] iPhone-installable PWA

### Phase 2: Core Infrastructure ✅
- [x] SQLite database with all schemas
- [x] Authentication system (device pairing, tokens)
- [x] WebSocket foundation for PC Agent
- [x] Context file CRUD operations
- [x] Audit logging system

### Phase 3: Voice Integration ✅
- [x] OpenAI Realtime API integration
- [x] Transcript capture and storage
- [x] Push-to-talk mechanics
- [x] Fallback to Whisper API + TTS
- [x] Voice command parsing

### Phase 4: ADHD Features ✅
- [x] Focus copilot with task breakdown
- [x] NOW/NEXT/LATER todo management
- [x] Focus sprint system (5/15/25/50 min)
- [x] Resume UX for interrupted work
- [x] Memory capture with approval flow
- [x] 3-tier memory system (short/working/long-term)
- [x] Memory promotion and search
- [x] WebAuthn passkey authentication
- [x] Database persistence for authentication
- [x] Conversational UI with voice-first design
- [x] Toast notification system

### Phase 5: PC Agent ✅
- [x] Job execution framework
- [x] File operations (read/write/delete/list/mkdir/exists)
- [x] Script runner with allowlist
- [x] Job queue (3 concurrent jobs)
- [x] Capability levels (read_only/standard/elevated/admin)
- [ ] Browser automation (Playwright) - Optional
- [ ] Rollback system - Optional

### Phase 6: Polish
- [ ] Onboarding flow
- [ ] Workflow builder
- [ ] Learning system
- [ ] Comprehensive testing
- [ ] Production deployment

## Prerequisites

- Node.js >= 18
- npm >= 9
- Windows 10/11 (for PC Agent)
- iPhone/iPad with iOS 14+ (for PWA)

## Installation

### 1. Clone Repository

```bash
git clone <repository-url>
cd atlas
```

### 2. Broker Server Setup

```bash
cd broker
npm install

# Create .env file
cp .env.example .env

# Edit .env and add your OpenAI API key and secrets
# OPENAI_API_KEY=sk-your-key-here
# JWT_SECRET=your-random-32-char-secret
# PAIRING_SECRET=your-random-32-char-secret

# Start development server
npm run dev
```

The broker server will start on port 3003 (or PORT from .env).

**Health Check:** http://localhost:3003/health

### 3. PWA Setup

```bash
cd pwa
npm install

# Create .env file (optional for now)
cp .env.example .env

# Start development server
npm run dev
```

The PWA will be available at https://localhost:3000

**Note:** For iPhone installation, you'll need HTTPS. The dev server includes SSL support, but you may need to generate self-signed certificates for local testing.

### 4. PC Agent Setup (Windows)

```bash
cd pc-agent
npm install

# Create .env file
cp .env.example .env

# Edit .env and configure:
# BROKER_URL=ws://localhost:3003/agent
# ALLOWED_DIRS=C:\Users\YourUsername\Documents\Atlas

# Start development agent
npm run dev
```

## Environment Variables

### Broker Server

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `OPENAI_API_KEY` | Yes | - | OpenAI API key for voice/transcription |
| `JWT_SECRET` | Yes | - | Secret for JWT token signing (32+ chars) |
| `PAIRING_SECRET` | Yes | - | Secret for device pairing (32+ chars) |
| `PORT` | No | 3003 | Server port |
| `DATA_DIR` | No | ./data | Data directory for SQLite and context files |
| `NODE_ENV` | No | development | Environment (development/production) |

### PWA

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BROKER_API_URL` | No | http://localhost:3001 | Broker server URL |
| `DEV_PORT` | No | 3000 | Development server port |

### PC Agent

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BROKER_URL` | Yes | ws://localhost:3003/agent | Broker WebSocket URL |
| `ALLOWED_DIRS` | Yes | - | Comma-separated list of allowed directories |
| `CAPABILITY_LEVEL` | No | 1 | Agent capability level (0-3) |
| `LOG_LEVEL` | No | info | Logging level |

## Development Workflow

### Running All Components

You'll need 3 terminal windows:

**Terminal 1 - Broker:**
```bash
cd broker
npm run dev
```

**Terminal 2 - PWA:**
```bash
cd pwa
npm run dev
```

**Terminal 3 - PC Agent:**
```bash
cd pc-agent
npm run dev
```

### Testing Connections

1. Check broker health: `curl http://localhost:3003/health`
2. Open PWA: https://localhost:3000
3. Verify PC Agent connects (check broker terminal for "Agent connected")

## Installing PWA on iPhone

1. Ensure broker server is accessible from iPhone (same network or public URL)
2. Open https://your-broker-url:3000 in Safari
3. Tap Share button
4. Tap "Add to Home Screen"
5. Tap "Add"
6. Launch Atlas from home screen

## Project Structure

```
atlas/
├── broker/                 # Broker server (Node/Express)
│   ├── src/
│   │   ├── server.js      # Main server file
│   │   ├── routes/        # API routes
│   │   ├── middleware/    # Express middleware
│   │   ├── services/      # Business logic
│   │   └── models/        # Data models
│   ├── package.json
│   └── .env.example
│
├── pwa/                    # Progressive Web App
│   ├── public/
│   │   ├── index.html     # Main HTML
│   │   ├── app.js         # Application logic
│   │   ├── styles.css     # Styles
│   │   ├── sw.js          # Service worker
│   │   ├── manifest.json  # PWA manifest
│   │   └── icons/         # App icons
│   ├── package.json
│   └── .env.example
│
├── pc-agent/               # Windows PC Agent
│   ├── src/
│   │   ├── agent.js       # Main agent file
│   │   └── runners/       # Job runners
│   ├── package.json
│   └── .env.example
│
├── context/                # Context files
│   ├── profiles/          # User profiles
│   ├── operational/       # Todos, memory, decisions
│   ├── learning/          # Learned patterns
│   └── workflows/         # Workflows
│
├── TODO LIST.md           # Feature tracking
└── README.md              # This file
```

## API Endpoints (Phase 1)

### Health
- `GET /health` - Basic health check
- `GET /health/detailed` - Detailed system status

### Coming in Phase 2+
- Authentication endpoints
- Context CRUD endpoints
- Job management endpoints
- OpenAI proxy endpoints

## ADHD-First Design Principles

1. **ONE focus task** - NOW can only have one item
2. **Tiny steps** - Break everything into smallest actionable steps
3. **Resume UX** - Always know where you left off
4. **No silent changes** - All memory saves require approval
5. **Calm, not overwhelming** - Maximum 3 action buttons visible
6. **Trust-worthy** - Full audit log, complete rollback capability

## Security

- **API Keys:** Never in frontend code, always proxied through broker
- **Authentication:** Device pairing with JWT tokens
- **PC Agent:** Directory allowlist, script content hashing
- **Audit:** All state changes logged with rollback capability
- **HTTPS:** Required for production

## Testing

```bash
# Unit tests
npm test

# Integration tests
npm run test:integration

# E2E tests (Playwright)
npm run test:e2e
```

## Contributing

This is a personal project designed for production use. Contributions welcome after Phase 6 completion.

## License

MIT

## Troubleshooting

### Broker won't start
- Check `.env` file exists and has valid values
- Verify port 3003 is not in use: `netstat -ano | findstr :3003`
- Check Node version: `node --version` (should be >= 18)

### PWA won't connect to broker
- Verify broker is running and accessible
- Check browser console for errors
- Ensure CORS is enabled (broker has cors middleware)
- For production, confirm requests go to `/atlas/api/` (not `/api/`)

### Whisper returns 500
- Confirm `OPENAI_API_KEY` is set and valid
- Hard refresh the PWA after deployments (service worker cache)
- Some browsers record as `audio/mp4` instead of `audio/webm`; Atlas now sends the actual MIME type

### PC Agent won't connect
- Verify `BROKER_URL` in `.env` is correct
- Check broker terminal for WebSocket errors
- Ensure no firewall blocking WebSocket connection

## Production Deployment

Atlas is deployed to **https://adampowell.pro/atlas** ✅

### Server Information
- **Server:** 198.211.114.12 (adampowell.pro)
- **Location:** /var/www/adampowell.pro/Atlas/
- **PWA Files:** /var/www/adampowell.pro/html/atlas/ (copied from Atlas/pwa/public/)
- **Service:** systemd - atlas.service
- **Port:** 3003 (localhost only)
- **Status:** ✅ Running
- **Authentication:** WebAuthn passkey (Touch ID/Windows Hello)
- **Database:** SQLite with persistent authentication
- **Cache Version:** v13
- **Logs:** `ssh root@198.211.114.12 "journalctl -u atlas -f"`

### Deployment Files
- [deploy-from-windows.ps1](deployment/deploy-from-windows.ps1) - PowerShell deployment script
- [deploy-to-production.sh](deployment/deploy-to-production.sh) - Server-side deployment
- [atlas.service](deployment/atlas.service) - Systemd service file
- [nginx-atlas.conf](deployment/nginx-atlas.conf) - Nginx configuration

### Manual Deployment

```powershell
# From Windows, deploy to production
cd Atlas/deployment
.\deploy-from-windows.ps1
```

Or manually via SSH:

```bash
# SSH to server
ssh root@198.211.114.12

# Navigate to Atlas
cd /var/www/adampowell.pro/Atlas/broker

# Install dependencies
npm install --production

# Configure .env
nano .env
# Add OPENAI_API_KEY

# Restart service
systemctl restart atlas
systemctl status atlas
```

### Production Configuration

1. **Add OpenAI API Key:**
   ```bash
   ssh root@198.211.114.12 "nano /var/www/adampowell.pro/Atlas/broker/.env"
   ```
   Set: `OPENAI_API_KEY=sk-your-key-here`

2. **Restart Atlas:**
   ```bash
   ssh root@198.211.114.12 "systemctl restart atlas"
   ```

3. **Access Atlas:**
   - Local: `curl http://localhost:3003/health`
   - Public: https://adampowell.pro/atlas (once nginx is configured)

### Installation Complete

- ✅ PWA accessible at https://adampowell.pro/atlas
- ✅ API proxy configured for /atlas/api/
- ✅ WebSocket proxy configured for /atlas/agent
- ✅ OpenAI API key configured
- ✅ Service running and healthy
- ✅ WebAuthn passkey authentication configured
- ✅ Database persistence for user sessions
- See [SYSTEM.md](../SYSTEM.md) for server documentation

### Authentication System

Atlas uses **WebAuthn passkey authentication** for secure, passwordless access:

- **Biometric Login:** Uses Touch ID (iPhone/Mac) or Windows Hello
- **Persistent Sessions:** Authentication persists in SQLite database across server restarts
- **30-Day Tokens:** JWT tokens valid for 30 days
- **Single User:** Restricted to username "Adam" only
- **No Passwords:** Completely passwordless - uses device platform authenticators

**First-Time Setup:**
1. Visit https://adampowell.pro/atlas
2. Click "Sign In with Passkey"
3. Use Touch ID/Windows Hello to create your passkey
4. Done! Your device is now authenticated for 30 days

**Subsequent Access:**
- Passkey registration persists in database
- Simply use Touch ID/Windows Hello to authenticate
- Session remains active even after server restarts

## Next Steps

See [TODO LIST.md](TODO LIST.md) for detailed feature tracking and implementation status.

**Current Phase:** Phase 5 Complete ✅
**Next Phase:** Phase 6 - Polish & Testing

## Support

For issues and feature requests, see the session log in [TODO LIST.md](TODO LIST.md).

---

Built with care for those of us who need a calm, capable partner to navigate daily chaos.
