     1→#!/usr/bin/env python3
     2→"""
     3→Workspace Manager API Server
     4→Port: 9004
     5→Provides REST API for monitoring disk usage, executing cleanups, and managing backups
     6→"""
     7→
     8→from flask import Flask, jsonify, request
     9→from flask_cors import CORS
    10→import subprocess
    11→import json
    12→import os
    13→import re
    14→from datetime import datetime
    15→
    16→app = Flask(__name__)
    17→CORS(app)
    18→
    19→# Constants
    20→HOME = os.path.expanduser('~')
    21→ARCHIVE_DIR = os.path.join(HOME, 'Archive')
    22→ICLOUD_PATH = os.path.join(HOME, 'Library/Mobile Documents/com~apple~CloudDocs')
    23→
    24→# ============================================================================
    25→# UTILITY FUNCTIONS
    26→# ============================================================================
    27→
    28→def get_dir_size(path, max_depth=5, current_depth=0, visited=None):
    29→    """
    30→    Calcula tamanho de diretório recursivamente com proteção
    31→    """
    32→    if visited is None:
    33→        visited = set()
    34→
    35→    if current_depth >= max_depth:
    36→        return 0
    37→
    38→    try:
    39→        real_path = os.path.realpath(path)
    40→        if real_path in visited:
    41→            return 0
    42→        visited.add(real_path)
    43→
    44→        if not os.path.exists(path):
    45→            return 0
    46→
    47→        if os.path.isfile(path):
    48→            return os.path.getsize(path)
    49→
    50→        total = 0
    51→        for entry in os.scandir(path):
    52→            if entry.name == 'Archive':  # Skip Archive
    53→                continue
    54→            try:
    55→                if entry.is_symlink():
    56→                    continue
    57→                if entry.is_file():
    58→                    total += entry.stat().st_size
    59→                elif entry.is_dir():
    60→                    total += get_dir_size(entry.path, max_depth, current_depth + 1, visited)
    61→            except (PermissionError, OSError):
    62→                continue
    63→        return total
    64→    except (PermissionError, OSError):
    65→        return 0
    66→
    67→def format_size(bytes_size):
    68→    """
    69→    Converte bytes para formato legível
    70→    """
    71→    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
    72→        if bytes_size < 1024.0:
    73→            return f"{bytes_size:.2f} {unit}"
    74→        bytes_size /= 1024.0
    75→    return f"{bytes_size:.2f} PB"
    76→
    77→def get_last_cleanup_date():
    78→    """
    79→    Lê última data de cleanup do CLEANUP-LOG.md
    80→    """
    81→    try:
    82→        log_path = os.path.join(HOME, 'CLEANUP-LOG.md')
    83→        if os.path.exists(log_path):
    84→            with open(log_path, 'r') as f:
    85→                content = f.read()
    86→                # Procurar por data no formato "**Cleanup executado em:** 2025-12-13"
    87→                match = re.search(r'\*\*Cleanup executado em:\*\* (\d{4}-\d{2}-\d{2})', content)
    88→                if match:
    89→                    return match.group(1)
    90→        return None
    91→    except:
    92→        return None
    93→
    94→# ============================================================================
    95→# HEALTH & INFO ENDPOINTS
    96→# ============================================================================
    97→
    98→@app.route('/health')
    99→def health():
   100→    """Health check endpoint"""

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

#!/usr/bin/env python3
"""
Workspace Manager API Server
Port: 9004
Provides REST API for monitoring disk usage, executing cleanups, and managing backups
"""

from flask import Flask, jsonify, request
from flask_cors import CORS
import subprocess
import json
import os
import re
from datetime import datetime

app = Flask(__name__)
CORS(app)

# Constants
HOME = os.path.expanduser('~')
ARCHIVE_DIR = os.path.join(HOME, 'Archive')
ICLOUD_PATH = os.path.join(HOME, 'Library/Mobile Documents/com~apple~CloudDocs')

# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================

def get_dir_size(path, max_depth=5, current_depth=0, visited=None):
    """
    Calcula tamanho de diretório recursivamente com proteção
    """
    if visited is None:
        visited = set()

    if current_depth >= max_depth:
        return 0

    try:
        real_path = os.path.realpath(path)
        if real_path in visited:
            return 0
        visited.add(real_path)

        if not os.path.exists(path):
            return 0

        if os.path.isfile(path):
            return os.path.getsize(path)

        total = 0
        for entry in os.scandir(path):
            if entry.name == 'Archive':  # Skip Archive
                continue
            try:
                if entry.is_symlink():
                    continue
                if entry.is_file():
                    total += entry.stat().st_size
                elif entry.is_dir():
                    total += get_dir_size(entry.path, max_depth, current_depth + 1, visited)
            except (PermissionError, OSError):
                continue
        return total
    except (PermissionError, OSError):
        return 0

def format_size(bytes_size):
    """
    Converte bytes para formato legível
    """
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if bytes_size < 1024.0:
            return f"{bytes_size:.2f} {unit}"
        bytes_size /= 1024.0
    return f"{bytes_size:.2f} PB"

def get_last_cleanup_date():
    """
    Lê última data de cleanup do CLEANUP-LOG.md
    """
    try:
        log_path = os.path.join(HOME, 'CLEANUP-LOG.md')
        if os.path.exists(log_path):
            with open(log_path, 'r') as f:
                content = f.read()
                # Procurar por data no formato "**Cleanup executado em:** 2025-12-13"
                match = re.search(r'\*\*Cleanup executado em:\*\* (\d{4}-\d{2}-\d{2})', content)
                if match:
                    return match.group(1)
        return None
    except:
        return None

# ============================================================================
# HEALTH & INFO ENDPOINTS
# ============================================================================

@app.route('/health')
def health():
    """Health check endpoint"""


98:@app.route('/health')
107:@app.route('/')
132:@app.route('/api/disk/overview')
165:@app.route('/api/disk/cache')
210:@app.route('/api/cleanup/cache', methods=['POST'])
279:@app.route('/api/cleanup/monthly', methods=['POST'])
327:@app.route('/api/icloud/status')
383:@app.route('/api/icloud/backups')
427:@app.route('/api/projects/overview')
485:@app.route('/api/stats/summary')


Perfect! Now let me create a comprehensive summary. Let me also check the notification service and dashboard views briefly:


Bash

head -50 /Users/neog/Apps/macOS/NEOGHub/NEOGCommand/Services/ProcessManager/ServiceManager.swift | tail -30

Check ProcessManager end section


     1→import Foundation
     2→import SwiftUI
     3→import UserNotifications
     4→import AppKit
     5→
     6→@MainActor
     7→final class NotificationService: NSObject, ObservableObject {
     8→    static let shared = NotificationService()
     9→
    10→    // MARK: - Published State
    11→    @Published private(set) var isAuthorized: Bool = false
    12→    @Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined
    13→
    14→    // MARK: - Settings (stored in UserDefaults)
    15→    @AppStorage("notifyBudgetAlerts") var notifyBudgetAlerts: Bool = true
    16→    @AppStorage("notifyRunCompleted") var notifyRunCompleted: Bool = true
    17→    @AppStorage("notifyServiceStatus") var notifyServiceStatus: Bool = true
    18→    @AppStorage("notifyConnectionStatus") var notifyConnectionStatus: Bool = false
    19→    @AppStorage("budgetAlertThreshold") var budgetAlertThreshold: Double = 80.0
    20→
    21→    // MARK: - Notification Categories
    22→    enum Category: String {
    23→        case budget = "BUDGET_ALERT"
    24→        case runCompleted = "RUN_COMPLETED"
    25→        case serviceStatus = "SERVICE_STATUS"
    26→        case connection = "CONNECTION_STATUS"
    27→    }
    28→
    29→    // MARK: - Notification Actions
    30→    enum Action: String {
    31→        case viewDetails = "VIEW_DETAILS"
    32→        case dismiss = "DISMISS"
    33→        case openDashboard = "OPEN_DASHBOARD"
    34→        case startService = "START_SERVICE"
    35→        case stopService = "STOP_SERVICE"
    36→    }
    37→
    38→    private let notificationCenter = UNUserNotificationCenter.current()
    39→
    40→    private override init() {
    41→        super.init()
    42→        notificationCenter.delegate = self
    43→        Task {
    44→            await checkAuthorizationStatus()
    45→            await registerCategories()
    46→        }
    47→    }
    48→
    49→    // MARK: - Authorization
    50→
    51→    func requestAuthorization() async -> Bool {
    52→        do {
    53→            let granted = try await notificationCenter.requestAuthorization(options: [.alert, .sound, .badge])
    54→            await MainActor.run {
    55→                self.isAuthorized = granted
    56→            }
    57→            await checkAuthorizationStatus()
    58→            return granted
    59→        } catch {
    60→            print("Notification authorization error: \(error)")
    61→            return false
    62→        }
    63→    }
    64→
    65→    func checkAuthorizationStatus() async {
    66→        let settings = await notificationCenter.notificationSettings()
    67→        await MainActor.run {
    68→            self.authorizationStatus = settings.authorizationStatus
    69→            self.isAuthorized = settings.authorizationStatus == .authorized
    70→        }
    71→    }
    72→
    73→    func openSystemPreferences() {
    74→        if let url = URL(string: "x-apple.systempreferences:com.apple.preference.notifications") {
    75→            NSWorkspace.shared.open(url)
    76→        }
    77→    }
    78→
    79→    // MARK: - Category Registration
    80→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

import Foundation
import SwiftUI
import UserNotifications
import AppKit

@MainActor
final class NotificationService: NSObject, ObservableObject {
    static let shared = NotificationService()

    // MARK: - Published State
    @Published private(set) var isAuthorized: Bool = false
    @Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined

    // MARK: - Settings (stored in UserDefaults)
    @AppStorage("notifyBudgetAlerts") var notifyBudgetAlerts: Bool = true
    @AppStorage("notifyRunCompleted") var notifyRunCompleted: Bool = true
    @AppStorage("notifyServiceStatus") var notifyServiceStatus: Bool = true
    @AppStorage("notifyConnectionStatus") var notifyConnectionStatus: Bool = false
    @AppStorage("budgetAlertThreshold") var budgetAlertThreshold: Double = 80.0

    // MARK: - Notification Categories
    enum Category: String {
        case budget = "BUDGET_ALERT"
        case runCompleted = "RUN_COMPLETED"
        case serviceStatus = "SERVICE_STATUS"
        case connection = "CONNECTION_STATUS"
    }

    // MARK: - Notification Actions
    enum Action: String {
        case viewDetails = "VIEW_DETAILS"
        case dismiss = "DISMISS"
        case openDashboard = "OPEN_DASHBOARD"
        case startService = "START_SERVICE"
        case stopService = "STOP_SERVICE"
    }

    private let notificationCenter = UNUserNotificationCenter.current()

    private override init() {
        super.init()
        notificationCenter.delegate = self
        Task {
            await checkAuthorizationStatus()
            await registerCategories()
        }
    }

    // MARK: - Authorization

    func requestAuthorization() async -> Bool {
        do {
            let granted = try await notificationCenter.requestAuthorization(options: [.alert, .sound, .badge])
            await MainActor.run {
                self.isAuthorized = granted
            }
            await checkAuthorizationStatus()
            return granted
        } catch {
            print("Notification authorization error: \(error)")
            return false
        }
    }

    func checkAuthorizationStatus() async {
        let settings = await notificationCenter.notificationSettings()
        await MainActor.run {
            self.authorizationStatus = settings.authorizationStatus
            self.isAuthorized = settings.authorizationStatus == .authorized
        }
    }

    func openSystemPreferences() {
        if let url = URL(string: "x-apple.systempreferences:com.apple.preference.notifications") {
            NSWorkspace.shared.open(url)
        }
    }

    // MARK: - Category Registration


            port: 9001,
            command: "/usr/bin/python3",
            arguments: ["\(NSHomeDirectory())/Services/servers/log-server.py"],
            workingDirectory: "\(NSHomeDirectory())/Services/servers",
            healthEndpoint: "/health"
        ),
        ServiceDefinition(
            name: "System Monitor",
            port: 5555,
            command: "/usr/bin/python3",
            arguments: ["\(NSHomeDirectory())/Services/servers/system-monitor-server.py"],
            workingDirectory: "\(NSHomeDirectory())/Services/servers",
            healthEndpoint: "/api/system/all"
        ),
        ServiceDefinition(
            name: "WiFi API",
            port: 9002,
            command: "/usr/bin/python3",
            arguments: ["\(NSHomeDirectory())/Services/servers/wifi-api-server.py"],
            workingDirectory: "\(NSHomeDirectory())/Services/servers",
            healthEndpoint: "/health"
        ),
        ServiceDefinition(
            name: "Workspace API",
            port: 9004,
            command: "/bin/bash",
            arguments: ["\(NSHomeDirectory())/Scripts/system/start-workspace-api.sh"],
            workingDirectory: NSHomeDirectory(),
            healthEndpoint: "/health"
        )


Perfect! Now I have enough information to provide a comprehensive summary. Let me create the detailed report:

## NEOG Command macOS App - Complete API Integration & Architecture Summary

I've thoroughly explored the NEOG Command macOS application and the backend services it integrates with. Here's a comprehensive overview of the current architecture and all API endpoints being consumed:

---

## Architecture Overview

The NEOG Command app is a **unified control center for the NEOG ecosystem** built with SwiftUI (macOS 14+, zero external dependencies). It provides real-time monitoring and management of:
- Claude Code (CC) automation ROI tracking
- 4 backend services (system monitor, WiFi scanner, workspace manager, logging)
- 368 web applications
- Global search and keyboard shortcuts

### Core Communication Pattern
- **Base URL:** `http://localhost:9001` (main API server)
- **Session-based:** Actor-based (Swift concurrency)
- **Polling strategy:** Adaptive intervals (3s active, 30s idle)
- **Data format:** JSON with ISO8601 dates
- **CORS:** Enabled on all backend services

---

## Service Integrations & Endpoints

### 1. **Log Server (Port 9001)** - Main API Hub
**File:** `/Users/neog/Services/servers/log-server.py`

This is the primary service integrating CC ROI tracking, budget management, and live session monitoring.

#### CC Tracking Endpoints (used by app):

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/api/cc/roi/summary` | GET | Today's ROI stats (cost, value, profit, ROI%, run count) |
| `/api/cc/roi/all-time` | GET | All-time aggregated statistics |
| `/api/cc/roi/daily?days=N` | GET | Daily breakdown over N days |
| `/api/cc/roi/by-source` | GET | ROI metrics grouped by source (iOS, macOS, CLI, web) |
| `/api/cc/runs?limit=50&offset=0&status=completed` | GET | List CC runs with filters |
| `/api/cc/run/{run_id}` | GET | Get single run details with events |
| `/api/cc/run` | POST | Create new automation run |
| `/api/cc/run/{run_id}/complete` | POST | Mark run as complete with value |
| `/api/cc/run/{run_id}/value` | POST | Update value for existing run |
| `/api/cc/budget` | GET | Budget configuration & current usage |
| `/api/cc/health` | GET | Gate health status (guardrails, budget, heartbeat) |
| `/api/cc/session/current` | GET | Live session data (from cc-live-tracker.py) |

#### Additional CC Endpoints (for future integration):
| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/api/cc/event` | POST | Record individual events within a run |
| `/api/cc/events?run_id=X` | GET | Get events for a run |
| `/api/cc/gate/check` | POST | Pre-flight safety gate check |
| `/api/cc/guardrails` | GET/POST | Get/update safety guardrails |
| `/api/cc/tags` | GET/POST | Manage predefined tags |
| `/api/cc/run/{run_id}/tags` | POST | Tag a run |
| `/api/cc/export` | GET | Export runs as JSON |
| `/api/cc/export/csv` | GET | Export as CSV |
| `/api/cc/insights` | GET | AI-generated insights from runs |
| `/api/cc/forecast` | GET | Forecast future ROI based on trends |
| `/api/cc/achievements` | GET | Milestones and achievements |
| `/api/cc/webhooks` | GET/POST | Webhook management (Slack/Discord) |

#### Data Models:

**CCRun** (CC automation execution):
```swift
- run_id: String (primary)
- session_id: String?
- prompt: String
- source: String (macos_app, ios, web, cli)
- status: RunStatus (pending, running, completed, failed, halted)
- model: String (e.g., "claude-opus-4-5-20251101")
- input_tokens, output_tokens, cache_read_tokens: Int
- cost_usd, value_generated_usd: Double
- startedAt, completedAt: Date
- durationMs: Int?
- toolsUsed, filesModified: [String]?
- errorMessage: String?
- tags: [String]?
- Computed: roi (Double), isSuccessful (Bool)
```

**ROISummary** (today's aggregates):
```swift
- totalCost: Double (cost_usd)
- totalValue: Double (revenue_usd)
- profit: Double
- roiPercent: Double (roi_pct)
- runCount: Int (runs_total)
- successRate: Double (computed from runs_completed / runs_total)
```

**BudgetConfig** (3-Gate system):
```swift
- dailyLimitUsd, monthlyLimitUsd: Double
- maxTokensPerRun: Int
- maxCostPerRunUsd: Double
- alertThresholdPct: Double (default 80%)
- isActive: Bool
- currentDailyUsage, currentMonthlyUsage: Double?
```

**GateHealth** (realtime status):
```swift
- guardrailsOk, budgetOk, heartbeatOk: Bool
- overallHealth: String
- dailyUsage, dailyLimit: Double?
```

#### Database Tables (SQLite at ~/logs.db):
- `cc_runs` - Automation execution history
- `cc_events` - Granular events within runs
- `cc_tags` - Tag definitions (feature, bugfix, refactor, docs, test, devops, research)
- `budget_config` - 3-Gate budget limits
- `guardrails` - Safety rules (block_rm_rf, block_sudo, block_force_push, etc.)
- `logs` - General logging

**Token Pricing (Opus 4.5):**
- Input: $15 per 1M tokens
- Output: $75 per 1M tokens
- Cache read: $1.875 per 1M tokens

---

### 2. **System Monitor Server (Port 5555)**
**File:** `/Users/neog/Services/servers/system-monitor-server.py`

Real-time hardware metrics via `psutil` and macOS `sysctl`.

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/api/system/all` | GET | All system metrics (combined) |
| `/api/system/cpu` | GET | CPU usage, cores, frequency |
| `/api/system/gpu` | GET | GPU info (Apple Silicon M1/M2/M3/M4) |
| `/api/system/memory` | GET | RAM, swap, virtual memory |
| `/api/system/disk` | GET | Storage usage by mount |
| `/api/system/temperature` | GET | Thermal data |
| `/api/system/battery` | GET | Battery status & health |
| `/api/system/network` | GET | Network interfaces & bandwidth |
| `/api/system/processes` | GET | Top processes by CPU/memory |
| `/api/health` | GET | Server health status |

**Data: JSON with real hardware data** (not simulated)

---

### 3. **WiFi API Server (Port 9002)**
**File:** `/Users/neog/Services/servers/wifi-api-server.py`

Scans WiFi networks using Swift CoreWLAN scanner (`/Users/neog/wifi-scanner.swift`).

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/networks` | GET | List connected/visible WiFi networks |
| `/scan?force=true` | GET | Trigger WiFi scan (cached 5s) |
| `/health` | GET | Server health |

**Data:** Network SSID, signal strength (RSSI), security type, channel info

**Caching:** 5-second TTL with cache busting (`force_refresh=true`)

---

### 4. **Workspace Manager API (Port 9004)**
**File:** `/Users/neog/Services/servers/workspace-manager-api.py`
**Launcher:** `~/Scripts/system/start-workspace-api.sh`

Disk usage, cleanup automation, iCloud status, project overview.

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/health` | GET | Server health check |
| `/api/disk/overview` | GET | Home directory disk usage breakdown |
| `/api/disk/cache` | GET | Cache directory sizes (Xcode, npm, pip, etc.) |
| `/api/cleanup/cache` | POST | Clean cache directories (auto-select safe ones) |
| `/api/cleanup/monthly` | POST | Monthly deep cleanup of Archive |
| `/api/icloud/status` | GET | iCloud Drive sync status |
| `/api/icloud/backups` | GET | iCloud backup history & sizes |
| `/api/projects/overview` | GET | Projects directory structure & sizes |
| `/api/stats/summary` | GET | Combined workspace statistics |

**Data:** Disk sizes (formatted), cleanup history, iCloud metadata

---

## macOS App Service Layer Architecture

### 1. **Network Layer** (`Services/Network/`)

**APIClient.swift** - Generic REST client (actor-based):
```swift
- Init with baseURL (default: http://localhost:9001)
- Session config: 30s request timeout, 60s resource timeout
- Custom JSON decoder with flexible date parsing
- Error handling: APIError enum with detailed messages
- Health check endpoint: /health
```

**Endpoint.swift** - Type-safe endpoint definition:
```swift
enum Endpoint {
    case roiSummary, roiAllTime, roiDaily(days: Int), roiBySource
    case runs(limit: Int, offset: Int, status: String?), run(id: String)
    case createRun, completeRun(id: String), updateRunValue(id: String)
    case budget, guardrails, gateCheck, gateHealth
    case health, logs(limit: Int)

    // Computed: path (String), method (GET/POST/PATCH/DELETE)
}
```

### 2. **Integration Layer** (`Services/Integration/`)

**CCTrackingService.swift** - High-level API wrapper:
```swift
// ROI Stats
getROISummary() -> ROISummary
getAllTimeStats() -> AllTimeStats
getDailyStats(days: Int) -> [DailyROIStats]
getROIBySource() -> [SourceROI]

// Runs Management
getRecentRuns(limit, offset, status) -> [CCRun]
getRun(id: String) -> CCRunDetail
createRun(prompt, source) -> CreateRunResponse
completeRun(id, valueGenerated) -> CCRun

// Budget
getBudgetConfig() -> BudgetConfig
getGateHealth() -> GateHealth
```

### 3. **Real-time Layer** (`Services/Realtime/`)

**RealtimeService.swift** - Adaptive polling engine (@MainActor, ObservableObject):
```swift
Polling Strategy:
- Base interval: 5.0 seconds
- Active interval: 3.0 seconds (when data changes)
- Idle interval: 30.0 seconds (after 10 unchanged polls)
- Max idle count: 10 consecutive unchanged fetches

Event Publishers:
- roiUpdated: PassthroughSubject<ROISummary, Never>
- runCreated: PassthroughSubject<CCRun, Never>
- runCompleted: PassthroughSubject<CCRun, Never>
- budgetAlert: PassthroughSubject<BudgetAlert, Never>

Connection States:
- disconnected, connecting, connected, reconnecting, error

Budget Alerts:
- 80%: warning (message: "Approaching daily budget limit")
- 100%: critical (message: "Daily budget exceeded!")
```

### 4. **Consumption Tracking** (`Services/Monitoring/`)

**ConsumptionTracker.swift** - Live Claude Code session monitoring:
```swift
Published State:
- sessionCost, sessionInputTokens, sessionOutputTokens, sessionCacheTokens
- costPerHour, costPerMinute, inputTokensPerMinute, outputTokensPerMinute
- consumptionHistory: [ConsumptionDataPoint] (max 240 points = 2 hours @ 30s intervals)
- recentActivities: [ConsumptionActivity] (max 50)
- liveSessionId, liveSessionActive, liveSessionCost, liveSessionDurationSeconds

Live Session Endpoint:
GET http://localhost:9001/api/cc/session/current -> { active, session_id, cumulative_cost, cumulative_tokens, duration_seconds }

Token Pricing (Opus 4.5):
- Input: $0.000015 per token
- Output: $0.000075 per token
- Cache read: $0.000001875 per token
```

### 5. **Service Management** (`Services/ProcessManager/`)

**ServiceManager.swift** - Start/stop backend services:
```swift
Managed Services:
1. Log Server (9001) - python3 ~/Services/servers/log-server.py
2. System Monitor (5555) - python3 ~/Services/servers/system-monitor-server.py
3. WiFi API (9002) - python3 ~/Services/servers/wifi-api-server.py
4. Workspace API (9004) - bash ~/Scripts/system/start-workspace-api.sh

Features:
- Start/stop individual services
- Check if running (health endpoint)
- Capture stdout/stderr
- Store process info with uptime tracking
- Environment: PYTHONUNBUFFERED=1 for unbuffered output
```

### 6. **Notifications** (`Services/Notifications/`)

**NotificationService.swift** - macOS native notifications:
```swift
Categories:
- BUDGET_ALERT (Approaching/Exceeded budget)
- RUN_COMPLETED (Automation finished)
- SERVICE_STATUS (Service started/stopped)
- CONNECTION_STATUS (API connected/disconnected)

Actions:
- VIEW_DETAILS, DISMISS, OPEN_DASHBOARD, START_SERVICE, STOP_SERVICE

Settings (UserDefaults):
- notifyBudgetAlerts: Bool
- notifyRunCompleted: Bool
- notifyServiceStatus: Bool
- notifyConnectionStatus: Bool
- budgetAlertThreshold: Double (0-100%, default 80%)

Delivery: macOS User Notifications (UNUserNotificationCenter)
```

---

## Data Flow Diagram

```
NEOG Command (macOS)
    ├── AppState (@MainActor ObservableObject)
    │   ├── @Published roiSummary, recentRuns, budgetConfig
    │   ├── selectedCategory (Dashboard, Monitoring, Services, WebApps, Settings)
    │   └── Subscriptions to RealtimeService events
    │
    ├── RealtimeService (Polling Engine)
    │   ├── Adaptive polling: 3s (active) → 30s (idle)
    │   ├── Fetches: ROI Summary + Recent Runs (parallel)
    │   ├── Emits: roiUpdated, runCreated, runCompleted, budgetAlert
    │   └── Error handling: Reconnect with 10s backoff
    │
    ├── CCTrackingService (API Wrapper)
    │   ├── Calls APIClient.request<T>()
    │   └── Parses: ROISummary, [CCRun], BudgetConfig, etc.
    │
    └── APIClient (HTTP Session)
        └── URLSession to http://localhost:9001

Log Server (Port 9001)
├── SQLite Database (~/logs.db)
│   ├── cc_runs (automation history)
│   ├── cc_events (token/cost events)
│   ├── cc_tags, budget_config, guardrails
│   └── logs (general logging)
│
├── REST Endpoints:
│   ├── /api/cc/roi/summary → Aggregates daily cost/value/profit
│   ├── /api/cc/runs → Queries cc_runs table with filters
│   ├── /api/cc/budget → Reads budget_config + calculates usage
│   ├── /api/cc/health → Checks 3 gates (guardrails/budget/heartbeat)
│   └── /api/cc/session/current → Live session from cc-live-tracker.py
│
└── Webhooks: Slack/Discord notifications (configurable)

System Monitor (Port 5555)
├── psutil + macOS sysctl
└── /api/system/all → CPU, GPU, Memory, Disk, Temp, Battery, Network

WiFi API (Port 9002)
├── Swift CoreWLAN Scanner
└── /networks, /scan → WiFi network data

Workspace Manager (Port 9004)
├── Shell commands (du, df, etc.)
└── /api/disk/*, /api/cleanup/*, /api/projects/* → Disk metrics
```

---

## Key Integration Points

### 1. **Keyboard Shortcuts** (Real-time feedback):
```
⌘1-4: Navigate sections (triggers data refresh)
⌘K: Global search
⌘R: Force refresh (RealtimeService.forceRefresh())
⇧⌘S/X: Start/Stop all services
⌘E/⇧⌘E: Export (JSON/CSV)
```

### 2. **Menu Bar Widget**:
- Displays ROI summary, budget usage, services status
- Quick actions without opening main window
- Updates every 30 seconds

### 3. **Notification Deep-linking**:
- Budget alerts → Navigate to Dashboard
- Run completed → Navigate to Monitoring + highlight run
- Service started → Navigate to Services
- Actions trigger via NSNotificationCenter

### 4. **Export Functionality**:
- JSON: Full run details with events
- CSV: Spreadsheet format for analysis
- Summary: Formatted text report

---

## Error Handling & Resilience

**APIError enum:**
```swift
- invalidURL
- invalidResponse
- httpError(statusCode, data)
- decodingError(Error)
- networkError(Error)
```

**RealtimeService:**
- Connection states provide visual feedback
- Auto-reconnect with 10s backoff on errors
- Adaptive polling prevents network spam
- Change detection avoids redundant updates

**Date Parsing (flexible):**
- ISO8601 with fractional seconds
- ISO8601 without fractional seconds
- Simple format: yyyy-MM-dd'T'HH:mm:ss

---

## Summary Statistics

**macOS App:**
- 7 service files (Network, Integration, Realtime, Monitoring, ProcessManager, Notifications)
- 3 main data models (CCModels.swift)
- 0 external dependencies (SwiftUI native)
- 5 main modules (Dashboard, Monitoring, Services, WebApps, Settings)

**Backend Services:**
- 4 active microservices (Log, System Monitor, WiFi, Workspace)
- 50+ REST endpoints (log-server alone has 50+)
- SQLite with 6+ CC-tracking tables
- Adaptive polling, webhook support, multi-format export

**API Consumption:**
- Adaptive polling: 3-30 second intervals
- Concurrent requests: 2 (ROI summary + recent runs)
- Data types: 8+ Decodable models with custom JSON mapping
- Budget alerts: Real-time at 80% and 100% thresholds

This architecture provides a **production-grade automation monitoring system** with real-time feedback, safety guardrails, budget controls, and comprehensive service management.