# ATLAS: AI Personal Operating System
## Claude Code Implementation Prompt v2.0

You are Claude Code acting as a senior full-stack engineer, product architect, systems designer, and reliability-focused AI engineer.

Your task is to build a production-ready, executive-grade personal operating system named **Atlas**.

Atlas is a calm, intelligent chief-of-staff, focus copilot, and execution agent designed for DAILY, HEAVY use by a user with ADHD. Atlas combines:
1. An iPhone-installable HTML/JS PWA (voice-first command center)
2. A Broker Server (Node/Express) that orchestrates all operations
3. A PC Agent (Windows, Node-based) that executes real-world actions

---

## ⚠️ CRITICAL: IMPLEMENTATION APPROACH

### Session Management
This project is too large for a single session. Build in this EXACT order:

**PHASE 1: Foundation** (Session 1)
- Project structure with all directories
- Broker server skeleton with health endpoint
- PWA shell with manifest and service worker
- TODO LIST.md initialized with all features

**PHASE 2: Core Infrastructure** (Session 2)
- SQLite database with all schemas
- Authentication system (pairing, tokens)
- WebSocket foundation
- Context file CRUD operations

**PHASE 3: Voice Integration** (Session 3)
- OpenAI Realtime integration
- Transcript capture and storage
- Push-to-talk mechanics
- Fallback to Whisper API

**PHASE 4: ADHD Features** (Session 4)
- Focus copilot and sprint system
- NOW/NEXT/LATER todo management
- Resume UX
- Memory capture with approval

**PHASE 5: PC Agent** (Session 5)
- Agent scaffold and connection
- Job execution framework
- Rollback system
- Browser automation foundation

**PHASE 6: Polish** (Session 6)
- Onboarding flow
- Workflow builder
- Testing suite
- Documentation

### At Every Session End, Output:
1. List of files completed this session
2. Exact resume instructions for next session
3. Updated TODO LIST.md with accurate status

### Code Quality Rules
- Every file must be complete and functional
- No placeholder comments like "// TODO: implement"
- If something cannot be fully implemented, create a working stub
- Track ALL incomplete items in TODO LIST.md
- Never claim completion without working code

---

## 🧠 CRITICAL PERSONAL CONTEXT

```
I have ADHD with:
- Very poor working memory and recall
- Difficulty with task initiation and switching
- High distractibility
- Trouble resuming interrupted work
- Executive function challenges

I need Atlas to:
- Support without shame or overwhelm
- Keep me moving with tiny next steps
- Remember things so I don't have to
- Adapt to my emotional/cognitive state
- Be reliable enough to trust with my life management
```

**THIS IS NOT A DEMO.** Build Atlas as production software that will be relied on every day.

---

## 📋 PROJECT TRACKING

Create and maintain: `TODO LIST.md` at project root

```markdown
# Atlas TODO List

## Status Legend
- ⬜ Not started
- 🟨 In progress
- ✅ Done
- ⛔ Blocked

## Phase 1: Foundation
| Feature | Status | Dependencies | Notes |
|---------|--------|--------------|-------|
| Project structure | ⬜ | None | |
| Broker skeleton | ⬜ | Project structure | |
| PWA shell | ⬜ | None | |
| Service worker | ⬜ | PWA shell | |

[Continue for ALL features in this prompt...]

## Open Questions
- [List any decisions needed]

## Session Log
### Session 1 - [Date]
- Completed: [list]
- Next session: [instructions]
```

---

## 🤖 ATLAS PERSONA

### Core Identity
- **Name**: Atlas
- **Role**: Chief of Staff + Focus Copilot
- **Personality**: Calm, competent, warm, unflappable
- **Voice**: Trusted friend who's incredibly organized

### Communication Principles
1. Lead with action, not explanation
2. One sentence for status, one for next step
3. Never more than 3 options presented
4. Questions only when decisions needed
5. Comfortable with silence

### Response Structure
```
Standard: "[Status]. Next: [action]. [Optional: question/choice]"
Overwhelm: "Let's pause. [Acknowledge]. One thing: [smallest step]."
Complete: "Done: [what]. What's next?"
```

### Tone States
| State | Trigger | Style |
|-------|---------|-------|
| Gentle | Stress detected, user request | Soft, encouraging, minimal |
| Direct | Clear ask, time pressure | Crisp, action-only |
| Firm | Drift, avoidance | Boundary-setting, one thing |
| Coaching | Stuck, exploring | Curious questions |
| Executive | Planning, review | Structured, strategic |

### Phrase Bank (Use These)

**Gentle:**
- "You're not behind. Let's make this tiny."
- "One step is enough right now."
- "I'll hold the rest."

**Firm:**
- "Pause. One thing only."
- "We're choosing now."
- "Finish this, then stop."

**Direct:**
- "Do this: [step]."
- "Ignore the rest."

**Coaching:**
- "What's the real friction?"
- "What would good enough look like?"

**Executive:**
- "Top 3: [list]."
- "Recommendation: [choice]."

### Forbidden Phrases
- "I understand this must be frustrating"
- "Have you considered..."
- "You should..."
- "Don't forget to..."
- Anything over 15 words for routine responses

### Voice Commands (Always Recognized)
- "Atlas, stop" - Halt immediately
- "Atlas, cancel" - Cancel current operation
- "Atlas, pause" - Pause listening
- "Atlas, repeat" - Repeat last response
- "Atlas, be gentle/direct/firm" - Switch tone
- "Atlas, text mode" - Disable voice
- "Atlas, debug" - Show system status

---

## 🏗️ ARCHITECTURE OVERVIEW

```
┌─────────────────────────────────────────────────────────────┐
│                     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  │       │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘       │
└─────────────────────────────────────────────────────────────┘
```

### Data Flow
1. User speaks to PWA
2. PWA sends audio to OpenAI via Broker (ephemeral token)
3. OpenAI returns transcript + response
4. Broker updates context, queues jobs
5. PC Agent executes jobs, reports status
6. PWA displays results, captures to memory

---

## 🔐 SECURITY REQUIREMENTS

### API Key Protection
```javascript
// NEVER in frontend code:
const OPENAI_KEY = "sk-..." // ❌ FORBIDDEN

// Always via broker:
const token = await fetch('/api/session').then(r => r.json());
// token is ephemeral, scoped, short-lived
```

### Authentication Flow
```
1. First Launch:
   - Broker displays 6-digit pairing code
   - User enters code in PWA
   - PWA receives refresh token (90-day, stored securely)

2. Normal Operation:
   - PWA exchanges refresh token for access token (15-min)
   - All requests include: Authorization: Bearer <access_token>
   - Token auto-refreshes before expiry

3. Device Management:
   - GET /api/devices - List paired devices
   - DELETE /api/devices/:id - Revoke device
   - Revocation is immediate
```

### Action Approval Levels
| Level | Actions | Approval |
|-------|---------|----------|
| 0 | Read context, view status | None |
| 1 | Update todos, save memory | Single confirm |
| 2 | Write files, run scripts | Approve + confirm |
| 3 | Browser automation, system commands | 2FA + approve + confirm |

### PC Agent Security
```javascript
// Capability levels
const LEVELS = {
  READ_ONLY: 0,      // Default
  STANDARD: 1,       // Write to allowed dirs
  ELEVATED: 2,       // Browser automation
  ADMIN: 3           // Full system (requires 2FA)
};

// Directory restrictions
const ALLOWED_DIRS = [
  '~/Documents/Atlas/',
  '~/Downloads/',
  // User-configurable
];

// Script allowlist
const ALLOWED_SCRIPTS = new Map();
// Scripts must be pre-approved, content-hashed
```

### Audit Requirements
Every state-changing action must log:
```json
{
  "ts": "2024-01-15T10:30:00Z",
  "action": "todo.create",
  "actor": "user",
  "target": "todo:abc123",
  "before": null,
  "after": {"title": "Review budget", "status": "now"},
  "approved": true,
  "rollback_id": "rb_xyz789"
}
```

---

## 📱 PWA REQUIREMENTS

### Installation Requirements
```javascript
// manifest.json
{
  "name": "Atlas",
  "short_name": "Atlas",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#1a1a2e",
  "theme_color": "#4a90d9",
  "icons": [
    { "src": "/icons/192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icons/512.png", "sizes": "512x512", "type": "image/png" }
  ]
}
```

### Offline-First Architecture
```javascript
// Service worker strategy
const CACHE_NAME = 'atlas-v1';
const OFFLINE_ASSETS = [
  '/',
  '/app.js',
  '/styles.css',
  '/manifest.json'
];

// Cache strategy:
// - App shell: Cache-first (instant load)
// - Context data: Network-first, cache fallback
// - Voice: Always network (never cache)

// IndexedDB stores:
// - todos (full offline CRUD)
// - transcripts (searchable history)
// - memory (all tiers)
// - pendingSync (queued changes)
```

### Voice System
```javascript
// Primary: OpenAI Realtime API (WebRTC)
// Fallback 1: Whisper API + TTS
// Fallback 2: Text-only mode

const voiceConfig = {
  pushToTalk: true,          // Press and hold
  interruptible: true,       // Can interrupt Atlas
  silenceThreshold: 1500,    // ms before processing
  maxDuration: 60000,        // 60s max utterance
  fallbackTriggers: {
    connectionFails: 3,      // attempts before fallback
    qualityThreshold: 0.5,   // below = suggest text
    costLimit: 5.00          // daily $ limit
  }
};
```

### Status Bar (Always Visible)
```
┌─────────────────────────────────────────┐
│ 🟢 Connected │ Focus │ 🎤 On │ PC: Online │
└─────────────────────────────────────────┘
```

Components:
- Connection: 🟢 Connected / 🔴 Offline / 🟡 Syncing
- Mode: Focus / Review / Planning / Free
- Mic: 🎤 Active / 🔇 Muted / ⏸️ Paused
- PC Agent: Online / Offline / Working: [job]

### Tab Structure
```
┌─────┬───────┬─────────┬───────────┬────────┬───────┬──────────┬───────────┐
│Home │ Todos │ Coaching│ Decisions │ Memory │ Agent │ Learning │ Workflows │
└─────┴───────┴─────────┴───────────┴────────┴───────┴──────────┴───────────┘
```

Each tab requirements:

**Home**
- Current focus task (large, prominent)
- Next step (actionable)
- Quick stats (streak, completed today)
- One-tap resume button

**Todos**
- NOW: Single visible item (primary focus)
- NEXT: 2-3 items (collapsed by default)
- LATER: Scrollable list (hidden by default)
- Drag to reorder
- Swipe actions: Done / Later / Delete

**Coaching**
- Current coaching focus
- Progress notes
- Session history
- Schedule next session

**Decisions**
- Active decisions (pending)
- Decision framework templates
- Past decisions (searchable)
- Follow-up reminders

**Memory**
- Short-term (24h, auto-expires)
- Working (active projects)
- Long-term (permanent)
- Search across all
- Edit/delete any item

**Agent (PC)**
- Connection status
- Current job (if any)
- Job queue
- Job history with rollback
- Capability settings

**Learning**
- Observed patterns
- Pending proposals
- Approved preferences
- All items editable/deletable

**Workflows**
- Discovered workflows
- Proposed automations
- Active workflows
- Run history

### UI Constraints
- Plain HTML/CSS/JS (no frameworks unless essential)
- Straight apostrophes only (', not ')
- Short dashes only (-, not —)
- 24-hour timestamps (14:30, not 2:30 PM)
- Maximum 3 action buttons visible at once
- All text minimum 16px
- Touch targets minimum 44x44px

---

## 🧩 ADHD-FIRST DESIGN

### Focus Copilot System
```javascript
const focusCopilot = {
  // Break ANY task into smallest step
  breakDown: (task) => {
    // Return single next physical action
    // "Write report" → "Open document"
    // "Open document" → "Click Word icon"
  },
  
  // Detect drift
  detectDrift: (currentFocus, userMessage) => {
    // If user mentions unrelated topic:
    // "Noticed a drift. Back to [focus]?"
  },
  
  // Breadcrumb system
  saveState: () => {
    // Before any interruption:
    // - What we were doing
    // - Where we stopped
    // - What's next
  }
};
```

### NOW/NEXT/LATER Model
```javascript
const todoModel = {
  now: null,      // ONE item only, or null
  next: [],       // 2-3 items max
  later: [],      // Everything else
  
  rules: {
    // NOW can only be set by explicit user action
    // NEXT auto-promotes when NOW completes
    // LATER is default destination for new items
    // Moving to NOW requires clearing current NOW
  }
};
```

### Focus Sprint System
```javascript
const sprintTypes = {
  micro:    { duration: 5,  break: 1,  use: 'Quick tasks, triage' },
  short:    { duration: 15, break: 3,  use: 'Single task chunk' },
  standard: { duration: 25, break: 5,  use: 'Deep work' },
  extended: { duration: 50, break: 10, use: 'Complex work' }
};

const sprintFlow = {
  start: {
    confirm_focus: true,
    clear_distractions_prompt: true,
    block_notifications: 'optional'
  },
  during: {
    halfway_indicator: 'visual_only',
    drift_detection: true,
    emergency_exit: 'always_honored'
  },
  end: {
    completion_chime: 'configurable',
    summary_prompt: true,
    break_suggestion: true,
    auto_log: true
  }
};
```

### Resume UX
```javascript
// On every app open:
const resumeFlow = async () => {
  const lastSession = await getLastSession();
  
  if (lastSession.activeTask) {
    display({
      message: `Last time: ${lastSession.activeTask.title}`,
      nextStep: lastSession.nextStep,
      actions: [
        { label: 'Resume', action: 'continue' },
        { label: 'Different task', action: 'switch' },
        { label: 'Just checking in', action: 'browse' }
      ]
    });
  }
};
```

### Memory Capture Flow
```javascript
// NEVER save silently
const captureMemory = async (extracted) => {
  // 1. Show what was extracted
  const proposal = {
    type: extracted.type, // commitment, decision, action_item
    content: extracted.content,
    source: 'transcript',
    proposed_tier: 'short' // default to temporary
  };
  
  // 2. Ask for approval
  const approved = await promptUser({
    message: `Save this? "${proposal.content}"`,
    options: ['Save', 'Edit first', 'Discard']
  });
  
  // 3. Only persist if approved
  if (approved === 'Save') {
    await saveMemory(proposal);
    log('memory.save', proposal);
  }
};
```

---

## 💚 EMOTIONAL AWARENESS

### Detection Signals (Non-Diagnostic)
```javascript
const emotionalSignals = {
  voice: {
    pace: 'fast|normal|slow',
    pauses: 'frequent|normal|none',
    volume: 'loud|normal|quiet',
    tone: 'tense|neutral|relaxed'
  },
  language: {
    frustration: ['ugh', 'again', 'why', 'cant'],
    overwhelm: ['everything', 'too much', 'drowning'],
    urgency: ['asap', 'now', 'emergency', 'deadline'],
    fatigue: ['tired', 'exhausted', 'cant think']
  },
  behavior: {
    rapid_switching: 'count topic changes',
    restarts: 'count abandoned sentences',
    rejections: 'count declined suggestions'
  }
};
```

### Adaptation Rules
```javascript
const adaptTone = (signals) => {
  // High frustration + rapid switching
  if (signals.frustration > 0.7 && signals.rapid_switching > 3) {
    return {
      tone: 'firm',
      response_length: 'minimal',
      options: 1, // reduce choices
      message: "Pause. One thing only. What matters most right now?"
    };
  }
  
  // Overwhelm detected
  if (signals.overwhelm > 0.7) {
    return {
      tone: 'gentle',
      response_length: 'minimal',
      options: 2,
      message: "I'll hold the list. What's one tiny thing we can finish?"
    };
  }
  
  // Default
  return { tone: 'direct', response_length: 'normal', options: 3 };
};
```

### User Overrides (Always Honored)
```javascript
const toneOverrides = {
  'atlas be gentle': { tone: 'gentle', persist: 'session' },
  'atlas be direct': { tone: 'direct', persist: 'session' },
  'atlas be firm': { tone: 'firm', persist: 'session' },
  'atlas coaching mode': { tone: 'coaching', persist: 'session' },
  'atlas executive mode': { tone: 'executive', persist: 'session' },
  'always be [tone]': { tone: '$1', persist: 'permanent' }
};
```

---

## 🚀 ONBOARDING FLOW

### Requirements
- Maximum 5 screens
- Under 3 minutes total
- Immediate value delivery
- No account creation required (device-paired)

### Screens

**Screen 1: Welcome**
```
┌─────────────────────────────┐
│                             │
│         [Atlas Logo]        │
│                             │
│    I'm Atlas, your calm     │
│    chief of staff.          │
│                             │
│    I'll help you focus,     │
│    remember, and finish     │
│    what matters.            │
│                             │
│       [Let's start]         │
│                             │
└─────────────────────────────┘
```

**Screen 2: Communication Style**
```
┌─────────────────────────────┐
│                             │
│  How should I talk to you?  │
│                             │
│  [Gentle]                   │
│  Soft, encouraging          │
│                             │
│  [Direct] ← Recommended     │
│  Clear, action-focused      │
│                             │
│  [Minimal]                  │
│  Just the essentials        │
│                             │
│  (You can change anytime)   │
│                             │
└─────────────────────────────┘
```

**Screen 3: Focus Preferences**
```
┌─────────────────────────────┐
│                             │
│  Focus sprints help you     │
│  work in short bursts.      │
│                             │
│  Your default sprint:       │
│                             │
│  ○ 5 min (micro tasks)      │
│  ○ 15 min (quick work)      │
│  ● 25 min (deep focus)      │
│  ○ 50 min (big projects)    │
│                             │
│          [Next]             │
│                             │
└─────────────────────────────┘
```

**Screen 4: Memory & Privacy**
```
┌─────────────────────────────┐
│                             │
│  I can remember things      │
│  for you, but I'll always   │
│  ask first.                 │
│                             │
│  ✓ I'll propose what to     │
│    save—you approve         │
│                             │
│  ✓ You can edit or delete   │
│    anything                 │
│                             │
│  ✓ "Off the record" mode    │
│    available anytime        │
│                             │
│          [Got it]           │
│                             │
└─────────────────────────────┘
```

**Screen 5: First Win**
```
┌─────────────────────────────┐
│                             │
│  Let's get one thing off    │
│  your mind right now.       │
│                             │
│  What's something you       │
│  need to do or remember?    │
│                             │
│  [Voice input] or [Type]    │
│                             │
│  ─────────────────────────  │
│                             │
│  [Skip for now]             │
│                             │
└─────────────────────────────┘
```

Then immediately:
- Break into NOW/NEXT
- Offer focus sprint
- Save with permission

---

## 📁 CONTEXT SYSTEM

### Directory Structure
```
/context
├── profiles/
│   ├── base.md           # Core identity, background
│   ├── work.md           # Professional context
│   └── health.md         # Health considerations (optional)
├── operational/
│   ├── todos.json        # Task management
│   ├── memory_short.json # 24-hour memory
│   ├── memory_working.json
│   ├── memory_long.json
│   ├── decisions.json
│   ├── coaching.json
│   └── preferences.json
├── learning/
│   ├── patterns.json     # Observed patterns
│   ├── skills.json       # Learned automations
│   └── proposals.json    # Pending suggestions
├── workflows/
│   ├── discovered.json
│   ├── approved.json
│   └── runs.json
└── audit.log             # Append-only
```

### Data Schemas

```typescript
// todos.json
interface TodoStore {
  version: number;
  items: Todo[];
}

interface Todo {
  id: string;           // uuid
  title: string;        // max 200 chars
  status: 'now' | 'next' | 'later' | 'done' | 'archived';
  created_at: string;   // ISO8601
  updated_at: string;
  due_at: string | null;
  parent_id: string | null;
  steps: Step[];
  tags: string[];
  source: 'voice' | 'manual' | 'extracted';
  source_transcript_id: string | null;
}

interface Step {
  id: string;
  text: string;
  done: boolean;
}

// memory_*.json
interface MemoryStore {
  version: number;
  items: MemoryItem[];
}

interface MemoryItem {
  id: string;
  type: 'commitment' | 'decision' | 'action_item' | 'preference' | 'context';
  content: string;
  extracted_from: string | null;  // transcript_id
  created_at: string;
  expires_at: string | null;      // short-term only
  promoted_to: 'working' | 'long' | null;
  tags: string[];
}

// audit.log (JSON lines)
interface AuditEntry {
  ts: string;           // ISO8601
  action: string;       // e.g., "todo.create", "memory.save"
  actor: 'user' | 'atlas' | 'system';
  target: string;       // e.g., "todo:abc123"
  before: any | null;
  after: any | null;
  approved: boolean;
  rollback_id: string | null;
}

// preferences.json
interface Preferences {
  version: number;
  tone: {
    default: 'gentle' | 'direct' | 'firm';
    learned_adjustments: ToneRule[];
  };
  focus: {
    default_sprint_minutes: number;
    break_reminders: boolean;
    block_notifications: boolean;
  };
  voice: {
    speech_rate: number;      // 0.5 - 2.0
    voice_id: string;
    push_to_talk: boolean;
  };
  privacy: {
    auto_capture: boolean;    // propose memory saves
    off_the_record: boolean;  // current session
  };
}
```

### Safe Update Protocol
```javascript
// ALL context updates must follow:
const updateContext = async (file, changes, reason) => {
  // 1. Generate change plan
  const plan = {
    file,
    changes,
    reason,
    before: await readContext(file),
    after: applyChanges(await readContext(file), changes)
  };
  
  // 2. Get approval
  const approved = await getApproval(plan);
  if (!approved) return { success: false, reason: 'rejected' };
  
  // 3. Write with version check
  const result = await writeContext(file, plan.after, plan.before.version);
  if (!result.success) return { success: false, reason: 'conflict' };
  
  // 4. Audit log
  await appendAudit({
    action: `context.update.${file}`,
    before: plan.before,
    after: plan.after,
    approved: true,
    rollback_id: generateRollbackId()
  });
  
  return { success: true };
};
```

---

## 🖥️ BROKER SERVER

### Tech Stack
- Node.js + Express
- SQLite for structured data
- File system for context JSON
- WebSocket for real-time

### API Endpoints

```typescript
// Authentication
POST   /api/pair/initiate     // Generate pairing code
POST   /api/pair/complete     // Exchange code for tokens
POST   /api/session           // Refresh access token
GET    /api/devices           // List paired devices
DELETE /api/devices/:id       // Revoke device

// OpenAI Proxy
POST   /api/realtime/session  // Get ephemeral token
POST   /api/whisper           // Fallback transcription
POST   /api/tts               // Text-to-speech fallback

// Context
GET    /api/context/:file     // Read context file
PUT    /api/context/:file     // Update with approval
GET    /api/context           // List all files

// Jobs (PC Agent)
POST   /api/jobs              // Create job
GET    /api/jobs/:id          // Get job status
POST   /api/jobs/:id/approve  // Approve pending job
POST   /api/jobs/:id/cancel   // Cancel job
POST   /api/jobs/:id/rollback // Rollback completed job
GET    /api/jobs              // List jobs

// Learning
GET    /api/learning/proposals
POST   /api/learning/proposals/:id/approve
POST   /api/learning/proposals/:id/reject
GET    /api/learning/preferences

// Workflows
GET    /api/workflows
POST   /api/workflows/:id/run
POST   /api/workflows/:id/approve
DELETE /api/workflows/:id

// Health
GET    /health                // Basic health
GET    /health/detailed       // All subsystem status
```

### Response Format
```typescript
// Success
{ "ok": true, "data": <payload> }

// Error
{ "ok": false, "error": { "code": "string", "message": "string" } }

// Error codes
const ERROR_CODES = {
  AUTH_REQUIRED: 'Authentication required',
  AUTH_INVALID: 'Invalid or expired token',
  NOT_FOUND: 'Resource not found',
  CONFLICT: 'Version conflict, please refresh',
  VALIDATION: 'Invalid request data',
  RATE_LIMIT: 'Too many requests',
  AGENT_OFFLINE: 'PC Agent not connected',
  INTERNAL: 'Internal server error'
};
```

### WebSocket Protocol
```typescript
// Connection
ws://broker/agent?token=<access_token>

// Messages: Broker → Agent
{ type: 'job.new', job: Job }
{ type: 'job.cancel', job_id: string }
{ type: 'ping' }

// Messages: Agent → Broker
{ type: 'job.accepted', job_id: string }
{ type: 'job.progress', job_id: string, progress: number, log: string }
{ type: 'job.completed', job_id: string, result: any }
{ type: 'job.failed', job_id: string, error: string }
{ type: 'pong' }
```

---

## 💻 PC AGENT

### Tech Stack
- Node.js
- WebSocket client (auto-reconnect)
- Playwright for browser automation
- Windows Credential Vault for token storage

### Capabilities

```typescript
const capabilities = {
  file: {
    read: true,
    write: true,  // allowed dirs only
    delete: true, // requires confirmation
    watch: true
  },
  script: {
    allowlist: Map<string, ScriptConfig>,
    execution: 'sandboxed'
  },
  browser: {
    navigation: true,
    click: true,
    type: true,
    screenshot: true,
    form_submit: 'requires_approval',
    allowed_domains: string[]
  },
  system: {
    clipboard: true,
    notifications: true,
    apps: 'allowlist_only'
  }
};
```

### Job Execution Flow
```typescript
const executeJob = async (job: Job) => {
  // 1. Validate capability level
  if (job.required_level > currentLevel) {
    return { error: 'Insufficient capability level' };
  }
  
  // 2. Create checkpoint
  const checkpoint = await createCheckpoint(job);
  
  // 3. Execute with logging
  try {
    const result = await runners[job.type](job.params, {
      onProgress: (p) => reportProgress(job.id, p),
      onLog: (l) => appendLog(job.id, l)
    });
    
    // 4. Success
    await reportComplete(job.id, result, checkpoint);
    return result;
    
  } catch (error) {
    // 5. Failure with rollback info
    await reportFailed(job.id, error, checkpoint);
    throw error;
  }
};
```

### Rollback System
```typescript
interface Checkpoint {
  id: string;
  job_id: string;
  created_at: string;
  type: 'file' | 'script' | 'browser';
  state: {
    files_modified: FileSnapshot[];
    clipboard_before: string | null;
    browser_state: BrowserSnapshot | null;
  };
}

const rollback = async (checkpoint_id: string) => {
  const checkpoint = await getCheckpoint(checkpoint_id);
  
  // Restore files
  for (const file of checkpoint.state.files_modified) {
    if (file.existed) {
      await fs.writeFile(file.path, file.content);
    } else {
      await fs.unlink(file.path);
    }
  }
  
  // Log rollback
  await appendAudit({
    action: 'job.rollback',
    target: checkpoint.job_id,
    checkpoint_id
  });
};
```

### Security Boundaries
```typescript
// Directory validation
const isPathAllowed = (path: string, operation: 'read' | 'write') => {
  const resolved = path.resolve(path);
  
  // Never allow system paths
  const forbidden = [
    'C:\\Windows',
    'C:\\Program Files',
    process.env.APPDATA,
    // etc.
  ];
  
  if (forbidden.some(f => resolved.startsWith(f))) {
    return false;
  }
  
  // Check against allowlist for writes
  if (operation === 'write') {
    return allowedDirs.some(d => resolved.startsWith(d));
  }
  
  return true;
};

// Script validation
const validateScript = async (scriptPath: string) => {
  const allowed = allowedScripts.get(scriptPath);
  if (!allowed) return { valid: false, reason: 'not_allowlisted' };
  
  const currentHash = await hashFile(scriptPath);
  if (currentHash !== allowed.hash) {
    return { valid: false, reason: 'content_changed' };
  }
  
  return { valid: true };
};
```

---

## 🔄 CONTINUOUS LEARNING

### Learning Pipeline
```typescript
const learningPipeline = {
  // 1. Observe (always running)
  observe: {
    approvals: true,      // What user approves/rejects
    corrections: true,    // What user modifies
    completions: true,    // Task completion patterns
    timing: true,         // When user works best
    drift: true           // Focus drift patterns
  },
  
  // 2. Analyze (periodic)
  analyze: {
    frequency: 'daily',
    outputs: [
      'preference_updates',
      'pattern_detections',
      'workflow_candidates'
    ]
  },
  
  // 3. Propose (requires approval)
  propose: {
    message: "I noticed you prefer [X]. Save this preference?",
    options: ['Yes', 'No', 'Tell me more']
  },
  
  // 4. Persist (only after approval)
  persist: {
    location: 'learning/preferences.json',
    audit: true,
    reversible: true
  }
};
```

### Pattern Detection Examples
```typescript
const patterns = {
  // Time-based
  'peak_focus_hours': {
    detection: 'High completion rate 9-11 AM',
    proposal: 'Schedule important tasks for morning?'
  },
  
  // Task-based  
  'email_batching': {
    detection: 'You check email then get distracted',
    proposal: 'Batch email to 3x daily?'
  },
  
  // Interaction-based
  'tone_preference': {
    detection: 'You respond better to direct tone',
    proposal: 'Default to direct style?'
  }
};
```

---

## 📊 PROACTIVE BEHAVIORS

### Daily Briefing (Morning)
```typescript
const dailyBriefing = {
  trigger: 'first_interaction_of_day',
  content: [
    'top_priority',           // "Most important: [task]"
    'calendar_preview',       // "You have N meetings"
    'pending_decisions',      // "N decisions waiting"
    'yesterday_incomplete'    // "Carried over: [task]"
  ],
  max_duration: '30 seconds',
  format: 'spoken + visual summary'
};
```

### End of Day Review
```typescript
const eodReview = {
  trigger: 'user_initiated OR 6pm local',
  content: [
    'completed_today',
    'incomplete_items',
    'commitments_made',
    'decisions_recorded'
  ],
  actions: [
    'move_incomplete_to_tomorrow',
    'set_tomorrow_priority',
    'capture_any_notes'
  ]
};
```

### Overload Triage
```typescript
const overloadTriage = {
  trigger: 'overwhelm_detected OR todo_count > 10',
  process: [
    '1. List everything (no judgment)',
    '2. What MUST happen today?',
    '3. What can wait?',
    '4. What can be delegated/dropped?',
    '5. Set ONE thing as NOW'
  ],
  output: 'Refined NOW/NEXT/LATER with clear priorities'
};
```

---

## 🧪 TESTING REQUIREMENTS

### Unit Tests (Jest)
```typescript
// Coverage target: 80%
describe('TodoModel', () => {
  test('NOW can only have one item');
  test('NEXT limited to 3 items');
  test('Completing NOW auto-promotes from NEXT');
});

describe('MemoryCapture', () => {
  test('Never saves without approval');
  test('Extracts commitments from transcripts');
});

describe('ToneAdaptation', () => {
  test('Detects overwhelm signals');
  test('User override honored immediately');
});
```

### Integration Tests
```typescript
describe('API', () => {
  test('Auth flow complete cycle');
  test('Context CRUD with versioning');
  test('Job lifecycle');
});

describe('WebSocket', () => {
  test('Reconnection with backoff');
  test('Job progress streaming');
});
```

### E2E Tests (Playwright)
```typescript
describe('PWA', () => {
  test('Onboarding complete flow');
  test('Voice command processing (mocked)');
  test('Todo CRUD operations');
  test('Focus sprint full cycle');
  test('Offline mode');
});
```

---

## 🚀 DEPLOYMENT

### Development Setup
```bash
# Prerequisites
node >= 18
npm >= 9

# Setup
git clone <repo>
cd atlas

# Broker
cd broker
npm install
cp .env.example .env  # Add OPENAI_API_KEY
npm run dev

# PWA (separate terminal)
cd pwa
npm install
npm run dev  # Serves on https://localhost:3000

# PC Agent (separate terminal)
cd pc-agent
npm install
npm run dev
```

### Production Setup
```bash
# Broker (VPS or home server)
npm run build
pm2 start dist/server.js

# PWA (static hosting)
npm run build
# Deploy dist/ to Cloudflare Pages, Vercel, etc.

# PC Agent (Windows)
npm run build
npm run install-service  # Installs as Windows service
```

### Environment Variables
```env
# Broker
OPENAI_API_KEY=sk-...
JWT_SECRET=<random 32+ chars>
PAIRING_SECRET=<random 32+ chars>
PORT=3001
DATA_DIR=./data

# PC Agent
BROKER_URL=wss://your-broker.com
ALLOWED_DIRS=C:\Users\You\Documents\Atlas,C:\Users\You\Downloads
```

---

## ✅ ACCEPTANCE CRITERIA

### Must Have (MVP)
- [ ] PWA installs on iPhone home screen
- [ ] Voice input/output works (with fallback)
- [ ] NOW/NEXT/LATER todo management
- [ ] Focus sprint with timer
- [ ] Memory capture with approval
- [ ] PC Agent connects and executes file jobs
- [ ] Rollback works for file operations
- [ ] Audit log captures all changes

### Should Have (v1.0)
- [ ] Full offline support
- [ ] All 8 tabs functional
- [ ] Tone adaptation working
- [ ] Daily briefing
- [ ] Browser automation
- [ ] Workflow detection

### Nice to Have (v1.1+)
- [ ] Multi-device sync
- [ ] Calendar integration
- [ ] Email triage
- [ ] Mobile notifications

---

## 📝 FINAL CHECKLIST

Before marking complete, verify:

- [ ] Every file in codebase is complete (no TODOs in code)
- [ ] TODO LIST.md accurately reflects reality
- [ ] All schemas match implementation
- [ ] Auth flow tested end-to-end
- [ ] Offline mode works
- [ ] Rollback tested for all job types
- [ ] Audit log captures everything
- [ ] README has setup instructions
- [ ] No API keys in frontend code

---

## 🎯 ATLAS 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.
```

Build Atlas as if your life depends on it—because for someone with ADHD, it might.
