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 serverdart run bin/xp_nix.dart --help- Show command line optionsdart run bin/xp_nix.dart --db custom.db --port 8081- Run with custom database and portdart test- Run all testsdart test test/specific_test.dart- Run a specific test filedart analyze- Run static analysis and lintingdart pub get- Install dependencies
Interactive Commands (while running)
Once the server is running, these commands are available in the terminal:
stats- Show current productivity statstest [level]- Test theme for specific levelrestore- Restore desktop backuprefresh- Refresh base config from current system configbuild- Build Flutter dashboard and copy to static fileshelp- 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 detectionIIdleMonitor- User idle state monitoringIDesktopEnhancer- Desktop theme/visual enhancementsITimeProvider- Time operations (for testing time manipulation)IWindowManager- Window manager operations abstraction
Hyprland Implementations:
HyprlandActivityDetector- Useshyprctl activewindowfor activity detectionIdleMonitor- Useshypridlefor idle state monitoringHyprlandEnhancer- Full desktop theming and visual enhancementsHyprlandManager- Window manager operations viahyprctl
Sway Implementations:
SwayActivityDetector- Usesswaymsg -t get_treefor activity detectionSwayIdleMonitor- Usesswayidlefor idle state monitoringSwayEnhancer- Notifications-only enhancer (no visual changes)SwayManager- Window manager operations viaswaymsg
Factory Classes (lib/src/factories/):
IdleMonitorFactory- Creates appropriate idle monitor for detected window managerActivityDetectorFactory- Creates appropriate activity detector for detected window managerDesktopEnhancerFactory- Creates appropriate enhancer for detected window managerWindowManagerFactory- Creates appropriate window manager interface
Test Mocks (lib/src/testing/):
MockActivityDetector- Controllable activity simulationMockIdleMonitor- Controllable idle state simulationMockDesktopEnhancer- No-op desktop enhancement for testingMockTimeProvider- Controllable time for testingMockWindowManagerDetector- 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 modifiersachievements- Achievement definitions and rewardslevel_system- XP per level and max levelmonitoring- Polling intervals and thresholdslogging- 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 statisticsGET /api/stats/history?days=7- Historical statsGET /api/achievements- All achievementsGET /api/activities?limit=100- Recent activitiesGET /api/focus-sessions- Focus session historyGET /api/xp-breakdown- XP breakdown by activity typeGET /api/classifications- Application classificationsPOST /api/classifications- Save application classificationGET /api/config- Current configurationPOST /api/config- Update configuration
WebSocket Events:
level_up- Level progression notificationsachievement_unlocked- Achievement notificationsstats_update- Real-time stats updatesxp_breakdown_update- XP distribution updatesfocus_session_complete- Focus session completions
Flutter Dashboard Build System
DashboardBuilder (lib/src/build/dashboard_builder.dart):
- Builds Flutter dashboard from
../xp_dashboarddirectory - Copies built web files to
lib/src/web/static/ - Accessible via
buildcommand 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 teststest/websocket_integration_test.dart- WebSocket functionalitytest/simulation/- Work day simulation scenariostest/deep_idle_test.dart- Idle detection edge casestest/hyprland_config_parser_test.dart- Configuration parsingtest/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
MockTimeProviderfor deterministic testing - Activity simulation via
MockActivityDetectorfor scenario testing
System Requirements & Compatibility
Window Manager Requirements
Hyprland Environment:
hyprctl- Window management and queryinghypridle- Idle detection and monitoring- Environment:
$HYPRLAND_INSTANCE_SIGNATUREmust be set
Sway Environment:
swaymsg- Window management and queryingswayidle- Idle detection and monitoring- Environment:
$SWAYSOCKmust be set
Optional Dependencies:
notify-send- Desktop notifications (both window managers)makoordunst- 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:
- Environment Variables: Checks
$HYPRLAND_INSTANCE_SIGNATUREand$SWAYSOCK - Process Detection: Falls back to checking available commands
- Graceful Degradation: Uses appropriate implementations or fallbacks
Development Workflow
Initial Setup
dart pub get- Install dependenciesdart run bin/xp_nix.dart- Start server (auto-detects window manager)- Visit
http://localhost:8080for dashboard
Making Changes
- Run tests:
dart test - Check analysis:
dart analyze - Test with custom database:
dart run bin/xp_nix.dart --db test.db - Build dashboard: Use
buildcommand at runtime commandflutter build webin../xp_dashboard
Configuration Changes
- Edit
config/xp_config.jsonfor XP rules and achievements - Use
refreshcommand to reload configuration - Test theme changes with
test [level]command - Use
restorecommand 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