Initializing
Back to Projects
Year2024
DomainFullstack
AccessOpen Source
Complexity0 / 10
NestJSNext.jsPostgreSQLRedisTauriAIPlugin SystemPersonal OSMonorepo
FullstackArchived

4ME - Personal OS (Productivity OS)

A unified, plugin-based "Operating System" for personal life management integrating productivity tracking, health monitoring, AI intelligence, and finance management with multi-platform support.

Parsing system architecture diagram...

Technology Stack

LayerTechnologyVersion/Details
FrontendNext.js14.2.35
Backend FrameworkNestJS11.1.11
Desktop AppTauriv2
DatabasePostgreSQL15 (Port 5433)
Cache/QueueRedisLatest
Object StorageMinIOLatest
AIGoogle Gemini@google/genai 1.34.0
SyncYjs13.6.29
State ManagementTanStack QueryLatest
MonorepoTurboLatest
Package Managernpm10.2.4
Browser ExtensionVite + CRXJSv7.3.1

Purpose and Philosophy

4ME (Personal OS) represents an ambitious vision to create a unified "operating system" for personal life management. Unlike single-purpose productivity tools, 4ME integrates time tracking, health monitoring, AI assistance, finance management, and activity logging into a cohesive plugin-based architecture.

The core philosophy centers on "UI as Lens" - the interface serves merely as a window into the underlying data and capabilities, with all logic residing in the backend kernel. This design enables multiple client applications (web, desktop, browser extensions) to share the same functionality without duplication.

Core Design Principles

  1. Microkernel Architecture: The core system provides fundamental resources (Storage, AI, Events) to lightweight plugins that can be dynamically discovered and loaded. Each plugin operates in its own sandbox, isolated by user identity at the database level.
  1. AI-First Intelligence: The system includes a built-in AI layer (context.ai) supporting Google Gemini with Vector Memory (RAG) for contextual understanding and persistent knowledge.
  1. Offline-First with Sync: Using Yjs CRDTs for conflict-free data synchronization, the system maintains local-first capabilities while enabling multi-device harmony through WebSocket-based real-time replication.
  1. Privacy-Centric: Automated PII redaction (emails, IPs, secrets), local-first AI processing, and AES-GCM end-to-end encryption for sync data ensure user privacy.
  1. Plugin Sandbox: Each plugin operates in strict isolation at the database level, ensuring data security and enabling future multi-tenant capabilities.

Architecture Deep Dive

Monorepo Structure

code
4ME/
├── apps/
│   ├── core-api/               # NestJS Backend (The Kernel)
│   │   ├── src/
│   │   │   ├── plugins/       # Plugin loader & registry
│   │   │   ├── auth/          # JWT authentication
│   │   │   ├── ai/            # Gemini AI integration
│   │   │   ├── sync/           # Yjs CRDT sync gateway
│   │   │   └── plugins/       # Individual plugin modules
│   │   └── prisma/            # Database schema
│   │
│   ├── web/                    # Next.js Frontend (The Shell)
│   │   ├── src/app/          # App Router pages
│   │   ├── components/        # React components
│   │   └── lib/              # Utilities & API client
│   │
│   ├── desktop/               # Native Desktop (Tauri v2)
│   │   ├── src/              # Rust + React
│   │   └── tauri.conf.json   # Tauri configuration
│   │
│   ├── cli/                   # Hardened CLI Power Tool
│   │   └── src/              # TypeScript CLI
│   │
│   ├── vscode-extension/      # VS Code Extension
│   │   └── src/              # Extension & Activity tracking
│   │
│   └── chrome-extension/      # Chrome Extension (Manifest V3)
│       └── src/              # Browser activity tracker

├── packages/
│   └── plugin-sdk/            # TypeScript contracts for plugins

├── plugins/
│   ├── time-tracker/          # Time tracking, invoicing, forecasting
│   ├── life-log/             # Passive activity recording
│   ├── system-health/        # Real-time system monitoring
│   ├── appearance/           # Theme engine with customization
│   └── hello-world/          # Basic proof of concept

└── docker-compose.yml         # Infrastructure

Plugin System Architecture

The plugin system follows a microkernel pattern:

typescript
// Plugin SDK Interface
interface Plugin {
  name: string;
  version: string;
  routes?: RouteDefinition[];
  apiHandlers?: ApiHandler[];
  permissions: string[];
  init(context: PluginContext): Promise<void>;
}

// Core API loads plugins dynamically
async function loadPlugins() {
  const plugins = await PluginRegistry.discover();
  for (const plugin of plugins) {
    await plugin.init(coreContext);
    router.register(plugin.routes);
  }
}

Each plugin is a standalone package with:

  • Routes: Express/NestJS route handlers
  • API: REST endpoints for the feature
  • Permissions: Sandboxed capability definitions

AI Layer Implementation

The system integrates Google Gemini for AI capabilities:

typescript
// AI Service with RAG support
class AIService {
  private model: GenerativeModel;
  private vectorStore: VectorStore;
  
  async chat(prompt: string, context: UserContext) {
    // Retrieve relevant context from vector store
    const relevantDocs = await this.vectorStore.similaritySearch(prompt);
    
    // Build enhanced prompt with context
    const enhancedPrompt = this.buildPrompt(prompt, relevantDocs);
    
    // Generate response
    const response = await this.model.generateContent(enhancedPrompt);
    return response.text();
  }
}

Sync System

Offline-first synchronization using Yjs CRDTs:

typescript
// WebSocket Sync Gateway
@WebSocketGateway('/sync', { namespace: 'sync' })
class SyncGateway {
  @SubscribeMessage('sync')
  handleSync(client: Socket, payload: Uint8Array) {
    // Apply CRDT update
    const doc = this.getDocument(client.userId);
    doc.applyUpdate(payload);
    
    // Broadcast to other clients
    client.broadcast.to(client.room).emit('sync', payload);
  }
}

Key features:

  • Conflict Resolution: Last-input-wins merging
  • IndexedDB Persistence: Local state resilience
  • React Hooks: useSync, useSyncedMap, useSyncedArray

Key Features and Functionality

1. Time Tracker Plugin

Comprehensive time management:

  • Start/Stop task tracking
  • Project and tag management
  • AI Productivity Analysis (V2)
  • Zombie Entry Cleanup (auto-detect stale entries)
  • PDF Invoicing with professional templates
  • Revenue forecasting with multi-currency support (USD, INR)

2. Life Log Plugin

Passive activity recording:

  • Automatic activity timeline
  • Event timeline visualization
  • Integration with desktop and browser extensions

3. System Health Plugin

Real-time monitoring:

  • CPU and Memory tracking
  • Database health checks
  • Redis status monitoring
  • MinIO storage metrics
  • Plugin health verification

4. Desktop Companion

Native Tauri application:

  • Active window tracking
  • Hardened CSP (Content Security Policy)
  • Notarization-ready build for macOS

5. VS Code Extension

Native development tool:

  • Precise path-based activity tracking
  • Tier 1 Intelligence integration
  • Context-aware time tracking

6. Chrome Extension

Browser-based tracking:

  • Manifest V3 compliant
  • Activity tracker for browser deep work
  • CRXJS-based bundling

7. AI Intelligence Features

  • Chat Interface: /ai/chat endpoint for conversational AI
  • Vector Memory: RAG-based persistent knowledge
  • Local Model Versioning: Self-learning system with automated retraining
  • Semantic Search: Meaning-based search of activity history

8. Finance Engine

  • Professional PDF invoicing
  • Revenue forecasting
  • Multi-currency support (USD, INR)
  • Financial analytics dashboard

9. Security Features

  • JWT Authentication: Secure token-based auth
  • AES-GCM Encryption: End-to-end encryption for sync
  • PII Redaction: Automated redaction of emails, IPs, secrets
  • Per-User Sandboxing: Database-level data isolation

10. CLI Power Tool

Hardened command-line interface:

  • JWT-based secure login
  • Authenticated status commands
  • System health verification

Database Models (Prisma)

The system uses comprehensive data modeling:

prisma
// User & Auth
model User {
  id            String   @id @default(uuid())
  email         String   @unique
  passwordHash  String
  name          String?
  settings      Json?
  createdAt     DateTime @default(now())
}

// Time Tracking
model Project {
  id          String   @id @default(uuid())
  name        String
  color       String?
  userId      String
  tasks       Task[]
  timeEntries TimeEntry[]
}

// Activity Logging
model ActivityLog {
  id          String   @id @default(uuid())
  userId      String
  action      String
  metadata    Json?
  timestamp   DateTime @default(now())
}

// Plugins
model PluginConfig {
  id        String   @id @default(uuid())
  pluginId  String
  userId    String
  config    Json
}

Infrastructure Configuration

Docker Compose setup:

yaml
services:
  postgres:
    image: postgres:15-alpine
    ports:
      - "5433:5432"  # Avoid port conflicts

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

  minio:
    image: minio/minio
    ports:
      - "9000:9000"
      - "9001:9001"

Development and Operations

Running the Application

bash
# Install dependencies
npm install

# Start infrastructure
docker compose up -d

# Build project
npm run build

# Start Core API
node apps/core-api/dist/apps/core-api/src/main.js

# Start Web Frontend
npm run dev --filter=web

# Desktop App
cd apps/desktop
npm run tauri dev

Verification Scripts

bash
# Verify Phase 1 (Auth & API)
npm run verify-phase1

# Verify PII Redaction
npm run verify-pii

CLI Usage

bash
# Login
node apps/cli/dist/main.js login [email protected] password

# Check status
node apps/cli/dist/main.js status

Lessons Learned and Best Practices

What Worked Well

  1. Plugin Architecture: Dynamic plugin loading enables easy feature extension
  2. Yjs CRDTs: Provides robust offline-first synchronization
  3. Multi-Platform: Single backend serves web, desktop, and extensions
  4. Tauri: Native desktop experience with small binary size
  5. Prisma ORM: Type-safe database operations across multiple clients
  6. Turbo Monorepo: Efficient build caching and task orchestration

Areas for Enhancement

  1. Plugin SDK: Could be more streamlined with better documentation
  2. Offline-First: More robust conflict resolution needed for complex scenarios
  3. AI Integration: Could benefit from more LLM providers (Anthropic, OpenAI)
  4. Testing: Comprehensive test coverage needed for production readiness
  5. Performance: Bundle size optimization for desktop app

Key Architectural Decisions

  • Microkernel Pattern: Core provides essential services, plugins extend functionality
  • Database-Level Isolation: Each user's data sandboxed at schema level
  • Event-Driven Architecture: BullMQ for async job processing
  • TypeScript Everywhere: Full-stack type safety from backend to extensions
  • CRDT Conflict Resolution: Yjs handles merge conflicts transparently

Security Architecture

PII Redaction Implementation

The system includes automated PII detection and redaction across all data stores:

typescript
// PII Detection patterns
const PII_PATTERNS = {
  email: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
  ipv4: /(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/g,
  phone: /\b\d{10,}\b/g,
  creditCard: /\b(?:\d{4}[- ]?){3}\d{4}\b/g,
  secret: /(?:api[_-]?key|secret[_-]?token|password)\s*[=:]\s*["']?([\w-]{20,})["']?/gi
};

class DataSanitizer {
  sanitize(input: string): string {
    let result = input;
    for (const [type, pattern] of Object.entries(PII_PATTERNS)) {
      result = result.replace(pattern, `[REDACTED_${type.toUpperCase()}]`);
    }
    return result;
  }
}

JWT Token Management

Secure token-based authentication with automatic rotation:

typescript
// Token generation with short-lived access tokens
class TokenService {
  generateAccessToken(user: User): string {
    return jwt.sign(
      { sub: user.id, email: user.email, type: 'access' },
      process.env.JWT_SECRET,
      { expiresIn: '15m' }
    );
  }

  generateRefreshToken(user: User): string {
    return jwt.sign(
      { sub: user.id, type: 'refresh', jti: uuid() },
      process.env.JWT_SECRET,
      { expiresIn: '7d' }
    );
  }
}

Plugin Development Guide

Creating a Custom Plugin

Developers can create new plugins by implementing the Plugin interface:

typescript
// plugins/my-custom-plugin/src/index.ts
import { Plugin, PluginContext } from '@4me/plugin-sdk';

export const myPlugin: Plugin = {
  name: 'my-custom-plugin',
  version: '1.0.0',
  description: 'Custom plugin for specialized functionality',
  
  permissions: [
    { resource: 'data', actions: ['read', 'write'] },
    { resource: 'ai', actions: ['read'] }
  ],

  routes: [
    {
      method: 'GET',
      path: '/my-plugin/status',
      handler: async (req, res) => {
        const status = await getPluginStatus(req.user.id);
        res.json(status);
      }
    }
  ],

  async init(context: PluginContext) {
    console.log(`Initializing ${this.name} for user ${context.userId}`);
    await this.registerEventHandlers(context);
  }
};

Performance Optimization Strategies

Database Query Optimization

Prisma queries optimized with select, include, and batch operations:

typescript
// Optimized data fetching
class TimeEntryService {
  async getEntriesWithProjects(userId: string, dateRange: DateRange) {
    return this.prisma.timeEntry.findMany({
      where: {
        userId,
        startTime: { gte: dateRange.start, lte: dateRange.end }
      },
      include: {
        project: { select: { id: true, name: true, color: true } },
        tags: true
      },
      orderBy: { startTime: 'desc' }
    });
  }
}

Caching Strategy

Multi-layer caching with Redis for API responses:

typescript
class CacheService {
  async getOrSet<T>(key: string, factory: () => Promise<T>, ttl: number): Promise<T> {
    const cached = await this.redis.get(key);
    if (cached) return JSON.parse(cached);
    
    const value = await factory();
    await this.redis.setex(key, ttl, JSON.stringify(value));
    return value;
  }
}

Conclusion

4ME (Personal OS) represents an ambitious, comprehensive approach to personal productivity management. The plugin-based architecture, AI-first design, and multi-platform support create a unified ecosystem for managing all aspects of personal and professional life.

While the project is now archived, it demonstrates sophisticated engineering patterns including:

  • Microkernel plugin architecture
  • CRDT-based synchronization
  • Multi-client support (web, desktop, extensions)
  • AI integration with vector memory
  • Privacy-centric security design

The project serves as a reference implementation for building comprehensive personal productivity systems with modern technologies.

Architecture Feedback

Spotted a potential optimization or antipattern? Let me know.

Submit a Technical Suggestion