xp_nix/xp_server/CLAUDE.md

12 KiB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

XP Nix is a productivity tracking and gamification system designed for Linux desktop environments, supporting both Hyprland and Sway window managers. It transforms daily computer usage into a gamified experience by monitoring activity patterns and providing real-time feedback through an XP (experience points) system.

Window Manager Support

Hyprland: Full feature support including visual desktop enhancements, idle monitoring, and activity detection Sway: Core functionality with idle monitoring and activity detection (visual enhancements disabled by design) Detection: Automatic runtime detection via environment variables (HYPRLAND_INSTANCE_SIGNATURE, SWAYSOCK)

Commands

Development

  • dart run bin/xp_nix.dart - Run the main application server
  • dart run bin/xp_nix.dart --help - Show command line options
  • dart run bin/xp_nix.dart --db custom.db --port 8081 - Run with custom database and port
  • dart test - Run all tests
  • dart test test/specific_test.dart - Run a specific test file
  • dart analyze - Run static analysis and linting
  • dart pub get - Install dependencies

Interactive Commands (while running)

Once the server is running, these commands are available in the terminal:

  • stats - Show current productivity stats
  • test [level] - Test theme for specific level
  • restore - Restore desktop backup
  • refresh - Refresh base config from current system config
  • build - Build Flutter dashboard and copy to static files
  • help - Show available commands

Nix Environment

This project uses Nix flakes for development environment management. The flake provides Dart SDK and SQLite with proper library paths configured:

  • nix develop - Enter development environment with Dart and SQLite

Architecture Overview

Core Components

ProductivityMonitor (lib/src/monitors/productivity_monitor.dart) - Central orchestrator that:

  • Coordinates activity detection, idle monitoring, and desktop enhancement
  • Calculates XP rewards based on activity types and time multipliers
  • Manages level progression and achievement system
  • Supports both event-driven (via IActivityDetector) and legacy polling modes
  • Broadcasts updates via WebSocket for real-time dashboard updates

DashboardServer (lib/src/web/dashboard_server.dart) - Web server providing:

  • RESTful API endpoints for stats, achievements, activities, and configuration
  • Real-time WebSocket connections for live updates
  • Serves Flutter-built dashboard from static files
  • Configurable port (default: 8080)

DatabaseManager (lib/src/database/database_manager.dart) - SQLite database operations for:

  • Daily stats tracking (XP, focus time, meeting time, level)
  • Activity events with duration and metadata
  • Application classifications (user-defined)
  • Achievements and focus sessions
  • Theme change history and streak tracking

Dependency Injection & Testing

The codebase uses dependency injection through interfaces to enable both production and testing modes:

Interfaces (lib/src/interfaces/):

  • IActivityDetector - Window/application activity detection
  • IIdleMonitor - User idle state monitoring
  • IDesktopEnhancer - Desktop theme/visual enhancements
  • ITimeProvider - Time operations (for testing time manipulation)
  • IWindowManager - Window manager operations abstraction

Hyprland Implementations:

  • HyprlandActivityDetector - Uses hyprctl activewindow for activity detection
  • IdleMonitor - Uses hypridle for idle state monitoring
  • HyprlandEnhancer - Full desktop theming and visual enhancements
  • HyprlandManager - Window manager operations via hyprctl

Sway Implementations:

  • SwayActivityDetector - Uses swaymsg -t get_tree for activity detection
  • SwayIdleMonitor - Uses swayidle for idle state monitoring
  • SwayEnhancer - Notifications-only enhancer (no visual changes)
  • SwayManager - Window manager operations via swaymsg

Factory Classes (lib/src/factories/):

  • IdleMonitorFactory - Creates appropriate idle monitor for detected window manager
  • ActivityDetectorFactory - Creates appropriate activity detector for detected window manager
  • DesktopEnhancerFactory - Creates appropriate enhancer for detected window manager
  • WindowManagerFactory - Creates appropriate window manager interface

Test Mocks (lib/src/testing/):

  • MockActivityDetector - Controllable activity simulation
  • MockIdleMonitor - Controllable idle state simulation
  • MockDesktopEnhancer - No-op desktop enhancement for testing
  • MockTimeProvider - Controllable time for testing
  • MockWindowManagerDetector - Test scenarios for different window managers

Activity Classification System

ActivityEventType enum categorizes activities:

  • coding - Development work (10 XP/min base)
  • focusedBrowsing - Research and documentation (6 XP/min base)
  • collaboration - Team communication (7 XP/min base)
  • meetings - Video conferences and calls (3 XP/min base)
  • misc - General productivity (2 XP/min base)
  • uncategorized - Unknown activities (1 XP/min base)

Classification Logic:

  • Uses user-defined application classifications stored in database
  • Fallback categorization based on application names and window titles
  • Tracks unclassified applications for manual categorization

XP & Gamification System

XP Calculation:

  • Base XP per minute varies by activity type
  • Time-based multipliers from configuration:
    • Deep work hours (1.5x): 09:00-11:00, 14:00-16:00
    • Late night penalty (0.8x): 22:00-06:00
  • Focus session bonuses: 60min (+100 XP), 120min (+200 XP), 180min (+500 XP)

Level System:

  • 100 XP per level progression
  • Visual desktop themes applied at different levels
  • Achievement system with level, focus, and session-based rewards

Achievements:

  • Level-based: Rising Star (L5), Productivity Warrior (L10), Focus Master (L15), Legendary Achiever (L25)
  • Focus-based: Deep Focus (4h), Focus Titan (8h)
  • Session-based: Session Master (5+ sessions)
  • Meeting-based: Communication Pro (3h meetings)

Configuration Management

ConfigManager (lib/src/config/config_manager.dart):

  • Loads from config/xp_config.json
  • Manages XP multipliers, achievement definitions, focus bonuses
  • Supports runtime configuration updates via web API

Key Configuration Sections:

  • xp_rewards - Base multipliers and time-based modifiers
  • achievements - Achievement definitions and rewards
  • level_system - XP per level and max level
  • monitoring - Polling intervals and thresholds
  • logging - Log levels and file management

Web Dashboard & API

Dashboard Features:

  • Real-time stats display with WebSocket updates
  • Activity timeline and XP breakdown charts
  • Achievement gallery and progress tracking
  • Application classification management
  • Configuration editor
  • Log viewer with filtering

API Endpoints:

  • GET /api/stats - Current day statistics
  • GET /api/stats/history?days=7 - Historical stats
  • GET /api/achievements - All achievements
  • GET /api/activities?limit=100 - Recent activities
  • GET /api/focus-sessions - Focus session history
  • GET /api/xp-breakdown - XP breakdown by activity type
  • GET /api/classifications - Application classifications
  • POST /api/classifications - Save application classification
  • GET /api/config - Current configuration
  • POST /api/config - Update configuration

WebSocket Events:

  • level_up - Level progression notifications
  • achievement_unlocked - Achievement notifications
  • stats_update - Real-time stats updates
  • xp_breakdown_update - XP distribution updates
  • focus_session_complete - Focus session completions

Flutter Dashboard Build System

DashboardBuilder (lib/src/build/dashboard_builder.dart):

  • Builds Flutter dashboard from ../xp_dashboard directory
  • Copies built web files to lib/src/web/static/
  • Accessible via build command while server is running
  • Requires Flutter to be available in system PATH

Testing Strategy

Test Structure

  • Unit Tests: Individual component testing with mocks
  • Integration Tests: WebSocket and database integration
  • Simulation Tests: Complete work day scenarios
  • Configuration Tests: Hyprland config parsing

Key Test Files

  • test/xp_nix_test.dart - Main productivity monitor tests
  • test/websocket_integration_test.dart - WebSocket functionality
  • test/simulation/ - Work day simulation scenarios
  • test/deep_idle_test.dart - Idle detection edge cases
  • test/hyprland_config_parser_test.dart - Configuration parsing
  • test/sway_integration_test.dart - Sway window manager integration tests

Testing Utilities

  • test/create_golden_db.dart - Creates test database with sample data
  • Time manipulation via MockTimeProvider for deterministic testing
  • Activity simulation via MockActivityDetector for scenario testing

System Requirements & Compatibility

Window Manager Requirements

Hyprland Environment:

  • hyprctl - Window management and querying
  • hypridle - Idle detection and monitoring
  • Environment: $HYPRLAND_INSTANCE_SIGNATURE must be set

Sway Environment:

  • swaymsg - Window management and querying
  • swayidle - Idle detection and monitoring
  • Environment: $SWAYSOCK must be set

Optional Dependencies:

  • notify-send - Desktop notifications (both window managers)
  • mako or dunst - Enhanced notification daemons (Sway)

Feature Comparison

Feature Hyprland Sway Notes
Activity Detection Uses hyprctl vs swaymsg
Idle Monitoring Uses hypridle vs swayidle
Visual Enhancements Disabled by design for Sway
Desktop Theming Config modifications disabled
Notifications Level-up and achievement alerts
WebSocket API Full dashboard functionality
Database Tracking Identical functionality

Runtime Detection

The system automatically detects your window manager at startup:

  1. Environment Variables: Checks $HYPRLAND_INSTANCE_SIGNATURE and $SWAYSOCK
  2. Process Detection: Falls back to checking available commands
  3. Graceful Degradation: Uses appropriate implementations or fallbacks

Development Workflow

Initial Setup

  1. dart pub get - Install dependencies
  2. dart run bin/xp_nix.dart - Start server (auto-detects window manager)
  3. Visit http://localhost:8080 for dashboard

Making Changes

  1. Run tests: dart test
  2. Check analysis: dart analyze
  3. Test with custom database: dart run bin/xp_nix.dart --db test.db
  4. Build dashboard: Use build command at runtime command flutter build web in ../xp_dashboard

Configuration Changes

  • Edit config/xp_config.json for XP rules and achievements
  • Use refresh command to reload configuration
  • Test theme changes with test [level] command
  • Use restore command if desktop theme issues occur

Roadmap Integration

The project roadmap includes ambitious enhancements:

  • Cursor-following XP numbers - RPG-style floating damage numbers
  • Dual currency shop system - XP points and real-world reward tokens
  • Enhanced celebrations - Full-screen level-up animations
  • Environmental feedback - Focus-based ambient changes
  • Real-world purchase integration - Automated reward fulfillment

Current architecture supports these extensions through:

  • Modular desktop enhancement system
  • Extensible notification framework
  • Configurable reward and achievement system
  • Database schema designed for expansion