"College isn't short on time. It's short on attention."
AxeP is a protocol that redirects attention, rewards focus, and treats every student's cognitive bandwidth as a liquid asset. This repository is a monorepo containing the edge daemon, backend server, and web frontend necessary to run the AxeP ecosystem.
AxeP consists of five active sub-projects working in tandem:
| Directory | Component | Description |
|---|---|---|
/axep |
Mobile App (Flutter + Kotlin) | Android companion app — real-time focus tracking, CL computation, LLM-powered quizzes, and QR-based laptop pairing. |
/daemon |
Edge Node (Go) | Runs locally on the user's laptop to track OS telemetry and calculate Cognitive Liquidity (CL) metrics. |
/server |
Backend (FastAPI) | The central core handling users, real-time WebSocket communication, token exchange, and persistence. |
/web |
Frontend (Next.js) | The user-facing dashboard for trading attention, joining study rooms, viewing focus analytics, and device pairing. |
/shared |
Shared Contracts | Shared TypeScript types ensuring data contract sync between the frontend and backend. |
The Edge Daemon measures focus without invading privacy. It evaluates:
- Input Entropy: Keystroke mapping to determine if input looks like productive typing vs gaming/chatting.
- Switch Velocity: How often the user switches between windows.
- Idle Fragmentation: Periods of inactivity.
These heuristic signals are distilled into a CL float between
0.0and1.0and synced to the backend to rate focus quality.
Students are rewarded with tokens for maintaining high CL. These tokens can be traded on the integrated Attention Exchange order book, allowing users to buy and sell "attention shares" of their study sessions.
Join real-time, topic-based rooms (e.g., #physics-101) with other students. The room aggregates the CL of all participants into a live leaderboard. Milestones are reached when the room's collective focus holds steady, rewarding everyone with token drops.
The daemon tracks negative CL patterns to identify burnout. It triggers 'Liberty Windows'—enforced, guilt-free recovery breaks that prevent fatigue from cascading.
The Flutter-based Android companion app brings the full AxeP experience to mobile. It runs entirely on-device (offline-first) and optionally syncs to the laptop via WebSocket.
| Layer | Technology |
|---|---|
| Framework | Flutter (Dart SDK ^3.7.2) |
| Native | Kotlin (Android, minSdk 26, targetSdk 35) |
| Database | SQLite via sqflite (local, 6-hour TTL) |
| LLM | Gemini 2.5 Flash (REST API) |
| QR Scanning | mobile_scanner ^5.2.3 |
| WebSocket | web_socket_channel ^2.4.0 |
┌─────────────────────────────────────────────────┐
│ Flutter UI │
│ SessionSetup → SessionActive → Dashboard │
│ PairingScreen (QR) │ SyncScreen (WebSocket) │
├─────────────────────────────────────────────────┤
│ Service Layer (Dart) │
│ SessionManager │ CognitiveEngine │ LlmService │
│ TrackingService │ SyncService │ DatabaseHelper │
├─────────────────────────────────────────────────┤
│ Platform Channel Bridge │
│ MethodChannel("com.axep/tracking") │
│ EventChannel("com.axep/app_switches") │
│ EventChannel("com.axep/typing_events") │
├─────────────────────────────────────────────────┤
│ Native Kotlin Layer │
│ UsageStatsManager (3s polling, app switches) │
│ AccessibilityService (typing + screen text) │
│ Foreground Service (persistent tracking) │
│ Notification Channels (quiz, distraction) │
└─────────────────────────────────────────────────┘
The mobile CL engine mirrors the daemon's formula, adapted for phone usage patterns:
| Signal | Source | Weight |
|---|---|---|
|
Keyboard Entropy ( |
AccessibilityService (TYPE_VIEW_TEXT_CHANGED) |
α = 0.25 |
|
Screen-switch Velocity ( |
UsageStatsManager (3-second polling) | β = 0.45 |
|
Idle Fragmentation ( |
Combined typing + switch timestamps | γ = 0.30 |
Additional derived metrics:
-
Burnout Signal (
$B_s$ ) — Ratio of failed recovery attempts after CL warnings - Attention Tokens — Earned at 2/min when CL ≥ 70; decayed at 0.5/min when CL < warning
- Attention ROI — Quality-weighted focus per unit time
- Background service using Android
UsageStatsManagerwith 3-second polling - Tracks every app switch with
fromApp → toApptransition, timestamp, and productive/distracted classification - Productive apps selected by the user at session start — everything else counts as distraction
- Automatic filtering of system packages (launcher, systemui, Nothing-specific packages)
When the user switches to a distraction app (3+ times), AxeP generates a contextual quiz from the productive content they were just reading:
- Screen text is captured via AccessibilityService from productive apps
- Text snapshots are sent to Gemini with a quiz-generation prompt
- A quick multiple-choice question is delivered as a system notification (not an in-app popup)
- Falls back to a general knowledge quiz if no productive text is captured
| Trigger | Condition | Action |
|---|---|---|
| Quiz notification | 3+ distracted app switches | Gemini-generated quiz from screen text |
| CL warning cooldown | CL drops below 40 | 15-minute cooldown period + notification |
| Burnout detection |
|
"Take a real break" notification |
| High distraction rate | ≥ 35% distracted switches (min 5 total) | Cooldown + rate notification |
During cooldown, all interventions are paused — no quiz spam, no additional warnings.
The phone and laptop pair via QR code for real-time sync:
- Web app at
/pairgenerates a QR containing{sessionId, serverUrl}with the laptop's LAN IP (auto-detected via/api/lan-ip) - Phone scans using
mobile_scanner(QR-only mode,DetectionSpeed.noDuplicates) - Both sides connect to the same WebSocket channel on the FastAPI server
- Session telemetry (CL, switches, alerts) streams to the laptop dashboard in real time
[Select Productive Apps] → [Start Session] → [Background Tracking]
↓ ↓
AccessibilityService CL computed every 2s
+ UsageStats start App switches logged
↓ ↓
[Distraction detected] [CL snapshot history]
↓ ↓
Quiz / Cooldown / Burnout [End Session] → DB cleared
| Permission | Purpose |
|---|---|
PACKAGE_USAGE_STATS |
App switch tracking via UsageStatsManager |
BIND_ACCESSIBILITY_SERVICE |
Typing heuristics + screen text extraction |
CAMERA |
QR code scanning for device pairing |
FOREGROUND_SERVICE |
Persistent background tracking |
POST_NOTIFICATIONS |
Quiz and distraction notifications (Android 13+) |
INTERNET |
Gemini API calls + WebSocket sync |
QUERY_ALL_PACKAGES |
Listing installed apps for productive app picker |
- No keystroke content — only inter-key timing intervals for entropy calculation
- No screen pixels — AccessibilityService reads semantic text nodes, not visual content
- SQLite is ephemeral — all local data is cleared when a session ends; 6-hour TTL on all records
- No network required — CL computation and tracking work entirely offline; sync is optional
This project requires Docker, Go, Python 3.10+, Node.js, and optionally Flutter (for mobile development) installed on your system.
A one-command setup script is provided at the root:
# Windows (PowerShell)
.\setup.ps1
# Linux / macOS
chmod +x setup.sh && ./setup.shThe script auto-detects your platform, checks all dependencies, starts Docker infrastructure, and launches every service.
The backend requires PostgreSQL and Redis. A docker-compose.yml is provided at the root:
# From the root directory:
docker-compose up -dNote: Ensure ports 5432 and 6379 are available.
Navigate to /server and bootstrap the Python environment.
cd server
# Create and activate a virtual environment
python -m venv venv
source venv/bin/activate # Or `venv\Scripts\activate` on Windows
# Install dependencies
pip install -r requirements.txt
# Create .env file
cp .env.example .env
# Run the server (default port: 8000)
uvicorn app.main:app --reload --port 8000Backend Environment Config (
server/.env): ConfigureDATABASE_URL(default:postgresql+asyncpg://postgres:postgres@localhost:5432/axep),REDIS_URL,JWT_SECRET_KEY, andJWT_ALGORITHM=HS256.
Navigate to /web to build and serve the React dashboard.
cd web
# Install Node dependencies
npm install
# Run the development server
npm run devFrontend Environment Config (
web/.env.local): EnsureNEXT_PUBLIC_API_URLpoints to your backend instance (e.g.,http://localhost:8000).
The daemon runs locally to collect telemetry and push it to the server.
cd daemon
# Build the Go application
go build ./...
# Run the daemon from the src folder
cd src
go run . --debugNote: The daemon creates a separate local SQLite database at daemon/local_db/axep_edge.db for offline telemetry caching.
The Android companion app requires Flutter SDK ^3.7.2.
cd axep
# Get Flutter dependencies
flutter pub get
# Run on a connected Android device or emulator
flutter run
# Build release APK
flutter build apk --releaseFirst-time setup on the phone:
- Grant Usage Access permission (Settings → Apps → Special access)
- Enable AxeP Accessibility Service (Settings → Accessibility)
- Grant Notification permission (Android 13+)
- Grant Camera permission (for QR scanning)
The app works fully offline. To pair with the laptop, ensure both devices are on the same Wi-Fi network and open the web frontend.
The FastAPI backend exposes the following primary endpoints. You can view the interactive Swagger documentation by navigating to http://localhost:8000/docs while the server is running.
POST /register: Register a new user (username,password,display_name).POST /login: Receives a standard OAuth2 password request and returns an access token.
POST /: Start a new study session (subject: str).GET /: List the current user's history of focus sessions.GET /{id}: Retrieve details of a specific session.PATCH /{id}: (Used by Daemon) Update the ongoing session'savg_clortotal_focus_minutes.POST /{id}/end: Mark the session as completed and calculate final rewards.
GET /orderbook/{session_id}: Fetch the live ask/bid order book for a given session.POST /orders: Place a newbuy,sell, orshortorder (session_id,side,price,quantity).DELETE /orders/{order_id}: Cancel an active order.GET /trades/{session_id}: Fetch localized trade execution history.GET /candles/{session_id}: Fetch OHLCV data for charting the token price of a session.
GET /: List all active rooms, optionally filtered by?topic=.POST /: Create a new study room (name,topic_tag).POST /{id}/join: Join a room, optionally inghost_mode(hidden from leaderboard).POST /{id}/leave: Exit the active room.GET /{id}/leaderboard: Fetch the live focus rankings of room members.GET /{id}/milestones: Retrieve unlocked and upcoming token reward milestones.
GET /balance: Get the user's current token balance.POST /transfer: Send tokens to another user (to_username,amount).GET /history: Fetch deposit, withdrawal, and trade token transaction logs.
GET /aroi: Get Attention Return on Investment analytics.GET /weekly: Request a compiled weekly summary of focus metrics.
ws/exchange/{session_id}: Live broadcast stream for orderbook and trade execution ticks.ws/room/{room_id}: Live broadcast for room leadership positional changes and nudges.ws/pair/{session_id}: Device pairing channel — phone and web connect to the same session ID and exchange handshake messages.
GET /api/lan-ip: Returns the laptop's LAN IPv4 address for QR code generation.
- No screen pixel capture: Only foreground window metadata is analyzed.
- No keystroke content logging: Only timing heuristics are used to calculate input entropy; the letters typed are never stored.
- Local computation: Granular telemetry stays strictly on-device; only aggregated CL float metrics leave the edge node to sync with the server.
- No keystroke content: Only inter-key timing intervals (millisecond deltas) are used for entropy — typed characters are never recorded.
- No screenshots or screen recording: Text is read via AccessibilityService semantic nodes, not visual screen capture.
- Productive text stays ephemeral: Captured screen text is sent only to Gemini for quiz generation and is never persisted on any server.
- SQLite is session-scoped: All local data (switches, typing events, sessions) is deleted when a session ends; records have a 6-hour TTL.
- Offline-first: CL computation, tracking, and interventions run entirely on-device. Network is only needed for Gemini quizzes and optional laptop sync.