# Syntaxis - Architecture Guide

Detailed technical architecture and implementation guide for the Syntaxis system, including comprehensive task management and feature implementation.

---

## 📐 System Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    User Interfaces                          │
├──────────────────────────┬──────────────────────────────────┤
│   Terminal UI (TUI)      │     Web Dashboard (React/Vue)    │
│   - ratatui 0.25         │     - Responsive design          │
│   - crossterm 0.27       │     - Advanced filtering         │
│   - Vim-style keys       │     - Mouse & keyboard           │
└──────────────────────────┴──────────────────────────────────┘
           │                              │
           └──────────────┬───────────────┘
                          │
        ┌─────────────────▼────────────────────┐
        │    REST API Server (Axum)            │
        │    - syntaxis-api                    │
        │    - Authentication & validation     │
        │    - Rate limiting & metrics         │
        └─────────────────┬────────────────────┘
                          │
        ┌─────────────────▼────────────────────┐
        │   Application Core                   │
        │   - syntaxis-core                    │
        │   - Phase, Tool, Checklist mgmt      │
        │   - Project state management         │
        └─────────────────┬────────────────────┘
                          │
        ┌─────────────────▼────────────────────┐
        │   Data Layer                         │
        │   - SQLite/PostgreSQL/SurrealDB      │
        │   - Configuration files (TOML)       │
        └──────────────────────────────────────┘
```

---

## 🗂️ Crate Organization

### Core Components

#### `syntaxis-core` - Domain Logic
The heart of the system, containing all business logic:

**Modules:**
- **`phase.rs`**: Phase management (creation, transitions, validation)
- **`tool.rs`**: Tool management (enable/disable, dependencies)
- **`checklist.rs`**: Checklist tracking (per-phase progress)
- **`config.rs`**: Configuration management (TOML parsing)
- **`error.rs`**: Error handling with custom error types

**Responsibilities:**
- State management
- Validation rules
- Business logic enforcement

#### `syntaxis-api` - REST API Server
HTTP interface for all clients (TUI, Dashboard):

**Modules:**
- **`handlers.rs`**: Endpoint handlers for projects, tasks, checklists
- **`models.rs`**: API request/response models (DTOs)
- **`middleware.rs`**: CORS, logging, rate limiting
- **`db.rs`**: Database connection and queries

**Endpoints:**
```
GET    /api/projects               # List all projects
GET    /api/projects/:id           # Get project details
POST   /api/projects               # Create project
GET    /api/projects/:id/status    # Get project status
GET    /api/projects/:id/security  # Security assessment
GET    /api/projects/:id/checklists# Get tasks/checklists
POST   /api/projects/:id/checklists# Create task
```

#### `syntaxis-tui` - Terminal Interface
Ratatui-based TUI for command-line users:

**Modules:**
- **`app.rs`**: Application state machine
- **`ui.rs`**: Rendering functions
- **`events.rs`**: Keyboard/terminal events
- **`api.rs`**: HTTP client to REST API
- **`types.rs`**: Data models (DTOs, enums)
- **`main.rs`**: Event loop and initialization

#### `syntaxis-dashboard` - Web Interface
Web-based dashboard for team collaboration:

**Modules:**
- **`components/`**: React/Vue components
- **`filters.rs`**: Filtering engine
- **`types.rs`**: Shared data models
- **`api.rs`**: HTTP client

---

## 🎯 Task Management Implementation

### Data Models

#### Priority and Type Enums

**File**: `crates/syntaxis-tui/src/types.rs`

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TaskPriority {
    Critical,  // 🔴 - Exit code: 0
    High,      // 🟠 - Exit code: 1
    Medium,    // 🟡 - Exit code: 2 (default)
    Low,       // 🟢 - Exit code: 3
}

impl Default for TaskPriority {
    fn default() -> Self {
        Self::Medium
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TaskType {
    Feature,        // ⭐
    BugFix,        // 🐛
    Documentation, // 📚
    Testing,       // ✔
    Deployment,    // 🚀
    Maintenance,   // 🔧
}

impl Default for TaskType {
    fn default() -> Self {
        Self::Feature
    }
}
```

#### Extended ChecklistItemDto

```rust
pub struct ChecklistItemDto {
    pub id: String,
    pub task_id: String,
    pub description: String,
    pub completed: bool,
    pub completed_at: Option<String>,
    pub created_at: String,
    #[serde(default)]
    pub priority: TaskPriority,    // NEW - with default
    #[serde(default, rename = "type")]
    pub task_type: TaskType,       // NEW - with default
}
```

**Backward Compatibility**: Both `priority` and `task_type` use `#[serde(default)]` to maintain compatibility with older API versions that don't return these fields.

### Sort Options Implementation

**File**: `crates/syntaxis-tui/src/app.rs`

```rust
pub(crate) enum TaskSortOption {
    CreatedNewest,   // By creation date, descending
    CreatedOldest,   // By creation date, ascending
    PriorityHighest, // NEW: Critical → High → Medium → Low
    PriorityLowest,  // NEW: Low → Medium → High → Critical
    CompletedFirst,  // Completed first, then pending
    PendingFirst,    // Pending first, then completed
}

impl TaskSortOption {
    pub(crate) fn all() -> Vec<Self> {
        vec![
            Self::CreatedNewest,
            Self::CreatedOldest,
            Self::PriorityHighest,
            Self::PriorityLowest,
            Self::CompletedFirst,
            Self::PendingFirst,
        ]
    }

    pub(crate) fn label(&self) -> &str {
        match self {
            Self::CreatedNewest => "Newest First",
            Self::CreatedOldest => "Oldest First",
            Self::PriorityHighest => "Highest Priority",
            Self::PriorityLowest => "Lowest Priority",
            Self::CompletedFirst => "Completed First",
            Self::PendingFirst => "Pending First",
        }
    }
}
```

### Statistics Calculation

**File**: `crates/syntaxis-tui/src/app.rs`

```rust
impl App {
    pub(crate) fn calculate_statistics(&self) -> (usize, usize, usize, f64) {
        let total = self.tasks.len();
        let completed = self.tasks.iter()
            .filter(|t| t.completed)
            .count();
        let pending = total - completed;
        let completion_percentage = if total > 0 {
            (completed as f64 / total as f64) * 100.0
        } else {
            0.0
        };

        (total, completed, pending, completion_percentage)
    }
}
```

---

## 🔄 Design Patterns

### State Separation (R-STATE-SEPARATION)

Application state is separated from rendering:

```
App State (app.rs)
    ↓
Filtered & Sorted Tasks (in-memory)
    ↓
Rendering Functions (ui.rs)
    ↓
Terminal Output
```

### Enum-Based Filtering (Type-Safe)

Instead of string comparisons, use Rust enums:

```rust
// ❌ NOT idiomatic
if task.priority == "high" { ... }

// ✅ Type-safe with Rust enums
match task.priority {
    TaskPriority::High => { ... }
    _ => { ... }
}
```

### Default Trait Implementation

New fields have sensible defaults for backward compatibility:

```rust
impl Default for TaskPriority {
    fn default() -> Self {
        Self::Medium  // Reasonable default
    }
}
```

---

## 🧪 Testing Strategy

### Test Coverage

All critical paths are tested comprehensively with unit tests across TUI and dashboard components.

### Unit Test Examples

```rust
#[test]
fn test_sort_by_priority_highest() {
    // Verify priority sorting order
}

#[test]
fn test_statistics_calculation() {
    // Verify statistics math
}
```

---

## 🔐 Error Handling

All errors handled with `Result<T, E>` and `?` operator:

```rust
// ✅ Idiomatic Rust
let task = self.tasks.first().ok_or(AppError::NoTasks)?;
```

---

## 📦 Key Dependencies

| Dependency | Version | Purpose |
|------------|---------|---------|
| **ratatui** | 0.25 | Terminal UI framework |
| **crossterm** | 0.27 | Cross-platform terminal |
| **tokio** | 1.x | Async runtime |
| **serde** | 1.0 | Serialization |
| **thiserror** | 2.0 | Error handling |

---

## 🚀 Performance

- **Sorting**: O(n log n) in-place with Rust's native `sort_by()`
- **Filtering**: O(n) single pass through tasks
- **UI Rendering**: Only changed areas redrawn (dirty flag optimization)
- **Memory**: Tasks stored in-memory as Vec for fast access

---

## 🔄 Backward Compatibility

All new fields use `#[serde(default)]` to maintain compatibility with older API versions:

```json
// Old API response (still works with new code)
{
  "id": "task_1",
  "description": "Do something",
  "completed": false,
  "created_at": "2025-11-14"
  // priority & task_type missing → use defaults
}
```

---

**Status**: Production Ready ✅
