# 9. Rebuild Guide

## Recommended Architecture

### Stack Selection

| Layer | Technology | Rationale |
|-------|-----------|-----------|
| **Runtime** | Node.js 20+ | Claude CLI is a Node-based tool, ecosystem alignment |
| **Server** | Express.js | Lightweight, well-understood, supports WebSocket upgrade |
| **Frontend** | React 18 + Vite | Fast builds, HMR, large component ecosystem |
| **Database** | SQLite (better-sqlite3) | Single-tenant, no separate DB server, filesystem-portable |
| **Real-time** | WebSocket (ws) | Direct streaming from Claude CLI to browser |
| **Terminal** | node-pty + xterm.js | PTY emulation for Claude CLI process management |
| **AI Engine** | Claude CLI (Anthropic) | Core product dependency, provides tool use and file access |
| **Styling** | CSS Modules / Tailwind | Dark/light theme support required |
| **Diagrams** | React Flow, Mermaid, Recharts | Workflow editor, inline diagrams, analytics charts |

### Architecture Diagram

```
┌─────────────────────────────────────────────┐
│                   Browser                    │
│  React SPA (Vite) ──── WebSocket Client     │
└──────────────┬──────────────┬───────────────┘
               │ HTTP         │ WS
┌──────────────┴──────────────┴───────────────┐
│              Express Server                  │
│  ┌─────────┐ ┌─────────┐ ┌──────────────┐  │
│  │  Routes  │ │Middleware│ │  Services    │  │
│  │  (API)   │ │ (Auth)   │ │ (Business)  │  │
│  └────┬─────┘ └─────────┘ └──────┬───────┘  │
│       │                          │           │
│  ┌────┴─────────────────────────┴────────┐  │
│  │           Claude CLI (node-pty)        │  │
│  │     ┌─────────────────────────────┐   │  │
│  │     │  System Prompt Injections    │   │  │
│  │     │  Personas, Guides, Modes     │   │  │
│  │     └─────────────────────────────┘   │  │
│  └───────────────────────────────────────┘  │
│       │              │             │         │
│  ┌────┴────┐  ┌──────┴─────┐  ┌──┴──────┐  │
│  │ SQLite  │  │ File System │  │ rclone  │  │
│  │  (db)   │  │ (docs/files)│  │ (cloud) │  │
│  └─────────┘  └────────────┘  └─────────┘  │
└─────────────────────────────────────────────┘
               │
        ┌──────┴──────┐
        │ Anthropic   │
        │ Claude API  │
        │ (or Bedrock)│
        └─────────────┘
```

## Build Phases

See [00-build-order.md](./00-build-order.md) for the full 17-phase build sequence.

### Critical Path Summary

**Phase 1 → 2 → 3 → 4 → 5** must be sequential:

1. **Foundation** -- Express server, SQLite, path utilities, env config
2. **Auth** -- Users table, bcrypt, JWT, middleware chain
3. **Files** -- Project directories, upload/download, safePath, file tree
4. **Claude CLI** -- node-pty spawning, session management, system prompt injection
5. **Chat** -- WebSocket server, React chat UI, streaming, message rendering

Everything after Phase 5 extends the core and can be parallelized.

### Parallel Work Streams

After the critical path, these streams can proceed independently:

**Stream A: Knowledge & Content**
- Phase 6: Knowledge base (doc serving, preview, download)
- Phase 16: Report publisher (PPTX, PDF generation)

**Stream B: Automation**
- Phase 8: Skills & workflows (SKILL.md parser, React Flow editor)
- Phase 9: Scheduling (cron, execution logging)

**Stream C: Integrations**
- Phase 10: Git integration
- Phase 11: Cloud drives (OAuth, rclone)
- Phase 12: MCP framework (21 services)

**Stream D: Admin & Analytics**
- Phase 13: Admin portal (users, analytics)
- Phase 15: AI provider management (Bedrock)

**Stream E: Specialty Features**
- Phase 7: Onboarding flow
- Phase 14: Meeting transcription

## Implementation Risks

| Risk | Impact | Mitigation |
|------|--------|-----------|
| Claude CLI version changes | Breaking changes in CLI interface | Pin CLI version in Dockerfile, test upgrades |
| node-pty compatibility | Platform-specific build issues | Use Docker for consistent builds |
| SQLite concurrency limits | Performance under multi-user load | Single-tenant design limits exposure, busy_timeout helps |
| rclone stability | Cloud drive access failures | Health monitoring, auto-remount, degraded state handling |
| Large knowledge bases | Memory/performance issues | File tree caching, pagination, streaming |
| Docker image size | Slow deployments | Multi-stage build, BuildKit caching |
| MCP ecosystem changes | Breaking protocol changes | Version-pin MCP packages |

## Validation Checklist

### Phase 1 Complete When:
- [ ] Express server starts on configurable port
- [ ] SQLite database initializes with full schema
- [ ] Health check endpoint responds
- [ ] Environment variables load correctly
- [ ] Path utilities resolve correctly in Docker and local

### Phase 2 Complete When:
- [ ] First user can register and becomes admin
- [ ] Subsequent registration is blocked
- [ ] Login returns valid JWT
- [ ] Protected routes reject unauthenticated requests
- [ ] Localhost bypass works for internal calls

### Phase 3 Complete When:
- [ ] Files upload to correct project directory
- [ ] File tree loads and displays hierarchy
- [ ] File download works for all supported types
- [ ] Path traversal attempts are blocked
- [ ] File delete with confirmation works

### Phase 4 Complete When:
- [ ] Claude CLI spawns via node-pty
- [ ] System prompt injections are appended correctly
- [ ] Model selection works (Claude direct + Bedrock)
- [ ] Permission mode configuration applies
- [ ] Session directories created and managed

### Phase 5 Complete When:
- [ ] WebSocket connection established from browser
- [ ] User message sent and response streamed back
- [ ] Tool calls displayed in collapsible groups
- [ ] Markdown with code highlighting renders correctly
- [ ] Session history saved and loadable
- [ ] Multiple concurrent sessions work

### Full System Complete When:
- [ ] All 17 phases pass their individual checklists
- [ ] Docker build succeeds (multi-stage, <2GB image)
- [ ] Container starts and passes health check
- [ ] Login → onboarding → chat → file upload → skill run works end-to-end
- [ ] Admin can create users, configure AI provider, view analytics
- [ ] Scheduled prompts fire and log results
- [ ] Cloud drive mounts and file access works
- [ ] Git operations work within the container

## Migration Notes

### From Existing Deployment

When migrating an existing Sasha instance:

1. **Database:** Copy `sasha.db` file to new container's `/app/data/` volume
2. **Files:** Copy `/home/sasha/all-project-files/` to new volume
3. **Skills:** Copy `.claude/skills/` directory
4. **Config:** Transfer environment variables (API keys, secrets)
5. **Cloud drives:** Re-authorize OAuth connections (tokens are encrypted with container-specific key)

### Data Portability

- Database is a single SQLite file (portable)
- Knowledge base is plain markdown files (portable)
- Skills are markdown files (portable)
- Cloud drive tokens must be re-authorized
- Session data can be discarded without impact
