# NexusCLI Design Principles - Three Pillars

**Version**: 0.1.0
**Created**: 2025-11-17
**Status**: Core Requirements

---

## 🎯 Three Pillars

NexusCLI is built on **three fundamental principles**:

```
┌─────────────────────────────────────────────────────────┐
│                                                         │
│  1. LIGHTWEIGHT    2. PORTABLE         3. CHATGPT UI   │
│                                                         │
│  • Minimal deps    • Linux native      • Chat style    │
│  • Low memory      • Termux support    • Streaming     │
│  • Fast startup    • ARM64/x86_64      • Markdown      │
│  • Single binary   • No systemd req    • Mobile-first  │
│                                                         │
└─────────────────────────────────────────────────────────┘
```

---

## 🪶 Pillar 1: LIGHTWEIGHT

### Philosophy
**"Zero bloat. Maximum efficiency."**

Every dependency, every line of code must justify its existence.

### Requirements

#### Backend
- **Max dependencies**: 10 npm packages
- **Memory footprint**: < 50MB idle
- **Startup time**: < 1 second
- **Binary size**: < 20MB (if bundled)

**Allowed Dependencies**:
```json
{
  "express": "^4.18.2",        // HTTP server (minimal)
  "cors": "^2.8.5",            // CORS middleware
  "node-pty": "^1.0.0",        // PTY spawning (only in wrapper)
  "uuid": "^9.0.0"             // Job ID generation
}
```

**Forbidden**:
- ❌ Heavy ORMs (Sequelize, TypeORM)
- ❌ GraphQL servers
- ❌ Webpack/complex bundlers (use esbuild if needed)
- ❌ Lodash (use native JS)

#### Frontend
- **Bundle size**: < 500KB gzipped
- **Framework**: React (already familiar from NexusChat)
- **Build tool**: Vite (fast, minimal config)
- **UI library**: None (custom CSS or Tailwind CDN)

**Optimization**:
```javascript
// vite.config.js
export default defineConfig({
  build: {
    minify: 'esbuild',
    rollupOptions: {
      output: {
        manualChunks: undefined, // Single chunk for small apps
      }
    }
  }
})
```

#### Storage
- **No databases**: SQLite only if absolutely needed
- **Prefer**: JSON files (like NexusChat session-manager)
- **Max file size**: 10MB per job result

---

## 📱 Pillar 2: PORTABLE (Linux + Termux)

### Philosophy
**"Run anywhere. Zero platform lock-in."**

Must work on desktop Linux, VPS servers, AND Android Termux.

### Target Platforms

| Platform | Arch | Package Manager | Priority |
|----------|------|-----------------|----------|
| **Ubuntu/Debian** | x86_64 | apt + npm | High |
| **Termux (Android)** | aarch64 | pkg + npm | **Critical** |
| **Alpine Linux** | x86_64 | apk + npm | Medium |
| **Raspberry Pi** | armv7l | apt + npm | Low |

### Termux Compatibility Requirements

#### 1. No systemd
**Problem**: Termux doesn't have systemd

**Solution**: Use process managers or tmux
```bash
# Instead of systemd service
tmux new-session -d -s nexuscli 'npm run start'

# Or use PM2 (if user wants)
pm2 start backend/server.js --name nexuscli
```

#### 2. Storage Paths
**Problem**: Termux uses non-standard paths

**Termux Filesystem**:
```
$PREFIX = /data/data/com.termux/files/usr
$HOME = /data/data/com.termux/files/home
```

**Configuration**:
```javascript
// config.js
const isTermux = process.env.PREFIX?.includes('com.termux');

const PATHS = isTermux ? {
  storage: `${process.env.HOME}/.nexuscli/jobs`,
  config: `${process.env.HOME}/.nexuscli/config.json`,
  logs: `${process.env.HOME}/.nexuscli/logs`,
} : {
  storage: '/var/lib/nexuscli/jobs',
  config: '/etc/nexuscli/config.json',
  logs: '/var/log/nexuscli',
};
```

#### 3. Port Configuration
**Problem**: Termux typically uses high ports (> 1024)

**Default Ports**:
- Control Plane: `4000` (configurable via env)
- Wrapper: `5000` (configurable via env)

```javascript
const PORT = process.env.NEXUSCLI_PORT || 4000;
```

#### 4. Network Access
**Problem**: Termux may be behind NAT/firewall

**Solution**: Support reverse tunnels (like SA56Work in CLAUDE.md)
```bash
# Wrapper on Termux device
ssh -R 4000:localhost:4000 vps3 -N &

# Control plane accessible via VPS3
curl http://vps3:4000/health
```

### Installation (One Command)

**Linux**:
```bash
curl -fsSL https://cli.wellanet.dev/install.sh | bash
```

**Termux**:
```bash
pkg install nodejs
npm install -g nexuscli
nexuscli start
```

**From Source** (both):
```bash
git clone https://github.com/dag/nexuscli
cd nexuscli
npm install
npm start
```

### Architecture: Minimal Dependencies

**Native Tools Only**:
- ✅ `bash` (always available)
- ✅ `node` (npm install)
- ✅ `git` (optional, for updates)

**No Custom Binaries**:
- ❌ No Docker dependency
- ❌ No database servers
- ❌ No additional runtimes (Python, Ruby, etc.)

---

## 💬 Pillar 3: CHATGPT-STYLE UI

### Philosophy
**"Conversation, not configuration."**

Users interact via natural chat interface, not complex dashboards.

### UI Paradigm

**ChatGPT Model**:
```
┌──────────────────────────────────────────────┐
│  NexusCLI                          [User] ▼  │
├──────────────────────────────────────────────┤
│                                              │
│  ┌──────────────────────────────────────┐   │
│  │ 🤖 System                            │   │
│  │ Welcome to NexusCLI. 3 nodes online. │   │
│  │ Type a command or ask what to do.    │   │
│  └──────────────────────────────────────┘   │
│                                              │
│  ┌──────────────────────────────────────┐   │
│  │ 👤 You                               │   │
│  │ Run 'systemctl status nginx' on all  │   │
│  │ production nodes                     │   │
│  └──────────────────────────────────────┘   │
│                                              │
│  ┌──────────────────────────────────────┐   │
│  │ 🤖 NexusCLI                          │   │
│  │ Executing on 3 nodes:                │   │
│  │                                      │   │
│  │ [prod-001] ✅ nginx active (running) │   │
│  │ [prod-002] ✅ nginx active (running) │   │
│  │ [prod-003] ⚠️  nginx inactive (dead) │   │
│  │                                      │   │
│  │ 2/3 nodes healthy. Check prod-003?  │   │
│  └──────────────────────────────────────┘   │
│                                              │
│  ┌──────────────────────────────────────┐   │
│  │ Type your command or question...     │   │
│  └──────────────────────────────────────┘   │
└──────────────────────────────────────────────┘
```

### Key Features

#### 1. Conversational Interface

**Natural Language Input** (future AI enhancement):
```
User: "Check if nginx is running on all nodes"
System: "Executing: systemctl status nginx"
```

**For MVP**: Direct command input
```
User: "systemctl status nginx"
System: "Select nodes: [all] [prod-001, prod-002] [staging-*]"
```

#### 2. Streaming Responses

**Real-time Output** (SSE from wrapper):
```
🔧 Executing on prod-001...
   ● nginx.service - A high performance web server
      Loaded: loaded (/lib/systemd/system/nginx.service)
      Active: active (running) since...
✅ Completed (exit code: 0)
```

**Progressive Rendering**:
- Status updates appear as they happen
- No "loading..." spinners - show actual work
- Collapsible sections for tool output

#### 3. Markdown Support

**Code Blocks**:
````markdown
```bash
systemctl status nginx
```

**Output:**
```
● nginx.service - running
  Active: active (running)
```
````

**Syntax Highlighting**: Prism.js or highlight.js (CDN, no bundle)

#### 4. Mobile-First Design

**Responsive Layout**:
```css
/* Mobile (Termux on phone) */
@media (max-width: 768px) {
  .chat-message {
    font-size: 14px;
    padding: 12px;
  }
  .input-box {
    position: fixed;
    bottom: 0;
    width: 100%;
  }
}

/* Desktop */
@media (min-width: 769px) {
  .chat-container {
    max-width: 800px;
    margin: 0 auto;
  }
}
```

**Touch-Friendly**:
- Large tap targets (44x44px minimum)
- Swipe gestures for navigation
- No hover-only interactions

### Component Structure

```jsx
// App.jsx
<ChatContainer>
  <Header>
    <Logo />
    <NodeStatus online={3} total={5} />
  </Header>

  <MessageList>
    {messages.map(msg => (
      <Message
        role={msg.role}        // 'user' | 'assistant' | 'system'
        content={msg.content}  // Markdown string
        streaming={msg.streaming}
      />
    ))}
  </MessageList>

  <InputBox
    onSubmit={handleSubmit}
    placeholder="Type command or ask a question..."
  />
</ChatContainer>
```

### Streaming Implementation

**Frontend** (same pattern as NexusChat):
```javascript
async function executeCommand(command, nodeIds) {
  // Create job
  const { jobId } = await fetch('/api/v1/jobs', {
    method: 'POST',
    body: JSON.stringify({ command, nodeIds }),
  }).then(r => r.json());

  // Stream output
  const eventSource = new EventSource(`/api/v1/jobs/${jobId}/stream`);

  eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);

    if (data.type === 'output_chunk') {
      appendToMessage(data.text); // Incremental update
    }

    if (data.type === 'status') {
      showStatus(data.category, data.message, data.icon);
    }

    if (data.type === 'done') {
      markComplete();
      eventSource.close();
    }
  };
}
```

---

## 🎨 Visual Design

### Color Scheme (ChatGPT-inspired)

```css
:root {
  /* Dark mode (default for CLI users) */
  --bg-primary: #1a1a1a;
  --bg-secondary: #2a2a2a;
  --text-primary: #ececec;
  --text-secondary: #9b9b9b;
  --accent: #667eea;
  --success: #4ade80;
  --warning: #fbbf24;
  --error: #ef4444;

  /* User message */
  --user-bg: #2a2a2a;

  /* Assistant message */
  --assistant-bg: #1f1f1f;
}
```

### Typography

```css
body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI',
               'Roboto', 'Oxygen', 'Ubuntu', sans-serif;
  font-size: 16px;
  line-height: 1.6;
}

code {
  font-family: 'Fira Code', 'Consolas', monospace;
  font-size: 14px;
}
```

---

## 📦 Deployment Models

### 1. Standalone (Termux on Phone)

**Use Case**: Single-user, local commands on phone

```bash
# On Pixel9Pro (Termux)
npm install -g nexuscli
nexuscli start

# Access via browser
am start -a android.intent.action.VIEW -d http://localhost:4000
```

**Architecture**:
```
Termux (Android)
  ├── nexuscli-backend (port 4000)
  ├── Browser (Chrome/Firefox)
  └── Local CLI tools (bash, git, python)
```

### 2. Client-Server (Termux → VPS)

**Use Case**: Control remote servers from phone

```bash
# On Termux (client)
nexuscli connect https://cli.wellanet.dev

# On VPS (server)
nexuscli server --public
```

**Architecture**:
```
Termux (Android) → HTTPS → VPS1 (Control Plane)
                               ↓
                           nexus-wrapper (nodes)
```

### 3. Distributed (Full Infrastructure)

**Use Case**: Production orchestration

```bash
# VPS1: Control Plane
nexuscli server --mode control-plane

# VPS2, VPS3, etc: Wrappers
nexuscli server --mode wrapper --register http://vps1:4000
```

**Architecture**: (same as ARCHITECTURE.md)

---

## 🔒 Security (Lightweight)

### Minimal Auth

**API Keys** (no complex JWT):
```bash
# Generate key
nexuscli generate-key

# Use key
curl -H "X-API-Key: abc123" http://localhost:4000/api/v1/nodes
```

**Config File**:
```json
{
  "apiKeys": [
    {
      "key": "abc123",
      "name": "my-phone",
      "created": "2025-11-17T10:00:00Z"
    }
  ]
}
```

### No Complex RBAC

**Simple Roles**:
- `admin`: Can execute any command
- `readonly`: Can only view job results

**No Per-Node Permissions** (too complex for lightweight)

---

## 📊 Performance Targets (Revised)

| Metric | Target | Priority |
|--------|--------|----------|
| Backend startup | < 500ms | Critical |
| Frontend load | < 2s (3G) | High |
| Memory (idle) | < 50MB | Critical |
| Memory (5 jobs) | < 100MB | High |
| Bundle size | < 500KB gz | Medium |
| SSE latency | < 50ms | High |

---

## 🚀 Implementation Priorities

### Phase 1: MVP (Lightweight + ChatGPT UI)

**Week 1**:
- ✅ Bootstrap done
- [ ] Implement chat UI (React + SSE)
- [ ] Basic job execution (single node)
- [ ] Markdown rendering

**Week 2**:
- [ ] Multi-node support
- [ ] Command history
- [ ] Mobile responsive design

### Phase 2: Portability (Termux Support)

**Week 3**:
- [ ] Termux compatibility testing
- [ ] Path detection (Linux vs Termux)
- [ ] Installation script
- [ ] NPM package publishing

### Phase 3: Polish

**Week 4+**:
- [ ] Syntax highlighting (code blocks)
- [ ] Dark/light theme toggle
- [ ] Export conversation/results
- [ ] Keyboard shortcuts (Ctrl+K, Ctrl+L)

---

## 🎯 Success Criteria

**Lightweight**:
- [x] < 10 npm dependencies (backend)
- [ ] Starts in < 1 second
- [ ] Runs on 512MB RAM VPS

**Portable**:
- [ ] Works on Termux (aarch64)
- [ ] Single `npm install` setup
- [ ] No systemd requirement

**ChatGPT UI**:
- [ ] Chat-style conversation flow
- [ ] Real-time streaming output
- [ ] Markdown + code block rendering
- [ ] Mobile-responsive (320px+)

---

## 📚 Related Documents

- [Architecture Overview](./ARCHITECTURE.md) - System design
- [API Contract](./API_WRAPPER_CONTRACT.md) - API specification
- [NexusChat Analysis](./NEXUSCHAT_ANALYSIS.md) - Reference implementation

---

_Design principles based on: ChatGPT UX + Termux constraints + Production learnings_
_Generated by Claude Code (Sonnet 4.5) - 2025-11-17_
