Skip to content

james19hadley/pulse-monolith-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

467 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

⬛ Pulse Monolith Bot

πŸ€– Telegram Bot: @PulseMonolith_bot
🌐 Web Dashboard: Configured via your custom domain (e.g., https://<your-webhook-domain>/app)

[!NOTE] Quest System Status: The core project structure (Epics, sub-projects, parent-child nesting) and standalone tasks are fully functional. The gamified RPG-style "Dopamine Quests" layer (elevating tasks into daily focus slots with custom visual rewards) is partially implemented and under active fine-tuning.

Pulse Monolith is a high-fidelity, cognitive-psychology-driven AI accountability partner and deep work tracker. Built specifically to support personality profiles (like INFJ/Fi) that resist rigid, manager-style management, Pulse operates as a dry, factual, objective mirror of reality.

Instead of traditional checkboxes and bureaucratic to-do lists that induce guilt-spirals, Pulse allows users to log their day in free-form natural language. It manages focus sessions, triggers calm "soft pings" with automated notification cleanup, and publishes daily "Kompromat" reports to a dedicated private Telegram channel.


πŸ—ΊοΈ System Architecture Overview

graph TD
    A["Telegram User Message"] --> B["FastAPI Webhook / Polling"]
    B --> C["FIFO User Lock Queue"]
    C --> D["Intent Router: Fast / Cheap LLM"]
    D -->|CHAT_OR_UNKNOWN| E["Conversational Engine"]
    D -->|LOG_WORK / SESSION_CONTROL / etc| F["AI Tool Calling: Heavy LLM"]
    F -->|Python Tool Executions| G["SQLAlchemy DB Operations"]
    G --> H[("SQLite / Postgres DB")]
    F --> I["ActionLog / Undo State"]
    B --> J["Celery Beat Scheduler"]
    J --> K["Background Jobs: Catalyst Heartbeat, Stale Session Killer, Evening Report"]
    K --> L["Telegram Bot APIs"]
Loading

🧠 Core Philosophy & Design Principles

1. The Anti-Secretary

Pulse is not a general-purpose virtual assistant. It will not buy your groceries, check the weather, or set alarms. Its sole focus is tracking focused work blocks and driving long-term projects forward. Conversations are kept concise, objective, and devoid of emotional fluff or cheerleader phrasing.

2. Witcher-like Goal Hierarchy

To prevent cognitive paralysis from massive, long-term goals (e.g., "Learn C++ for 1000 hours"), Pulse separates storage from daily presentation:

  • The Epic (Main Questline): The grand vision tracked in the database, but hidden from daily reports to avoid paralysis.
  • The Quest (Sub-Project): A finite, actionable project (e.g., "Build a text RPG - 30 hours"). This is the primary visualization layer.
  • The Next Action (Step): A granular, immediate milestone (e.g., "Read pointers chapter - 1 hour") used to prompt the user during idle periods.

3. Project Unification

Pulse rejects the concept of infinite, streak-heavy habits (e.g., "Read daily forever"). Instead, everything is represented as a Project with definitive boundaries (e.g., "50 Days of Portuguese" or "100 km of Running"). All progress accumulates over the user's lifetime, avoiding the demoralizing feeling of broken streaks.

4. Absolute Honesty & Project 0

Pulse tracks time inside bounded Sessions. If a work block lasts 8 hours, but only 3 hours of focused project work are reported, the remaining 5 hours are mathematically allocated to Project 0 (Operations / Routine) or logged as unaccounted-for time. This shows a realistic picture of focus efficiency.


🧭 Core System Mechanics

1. Session-Based Tracking

Pulse monitors active work sessions. Outside of a session, the user's life is private.

  • Start Session: User commands /start_session or says "Starting work block." The background heartbeat begins.
  • End Session: User commands /end_session. Pulse calculates total duration, sums up focused work logs, assigns the difference to Project 0, and returns a summary.

2. Catalyst Mechanism (Soft Pings)

During an active session, if no updates are logged within a threshold (e.g., 60 minutes), the system sends a nudge using the project's registered next_action.

  • Ping Replacement (UX Guard): Pulse deletes the previously unanswered ping before sending a new one. This ensures that opening Telegram after hours reveals a single calm question, rather than a wall of shame-inducing notifications.

3. Concurrency Safety (FIFO User-Level Locking)

To prevent database corruption when a user sends multiple rapid messages, Pulse implements a per-user FIFO queue. When processing an event, the system locks the user's ID (is_processing = True), and subsequent messages are queued, ensuring transactions execute sequentially.

4. Time-Zone & Time-Blindness Safety

Large Language Models are notoriously unreliable with dates, time zones, and math. The LLM in Pulse is strictly prohibited from generating absolute timestamps. It only extracts raw durations (e.g., duration_minutes: 40), and the Python backend maps this to localized datetimes based on the user's database-registered timezone.


πŸ’Ύ Database Schema & Nesting Logic

Pulse supports a hierarchical parent-child project layout with dual-metric aggregation:

[Life Folder]
    └── [Health Folder]
            └── [Sport Folder]
                    β”œβ”€β”€ [Pushups Habit] (Custom unit: reps)
                    └── [Running Habit] (Custom unit: km)

Metrics Isolation Rules

  • Global Aggregation (Time Bubbles Up): Time logged to any child project recursively aggregates and bubbles up to all parents.
  • Local Isolation (Units Stay Scoped): Custom units (e.g., pages, repetitions) remain scoped strictly to the target child project.
  • Aggregation Types:
    • sum (Default): Parent progress is the sum of sub-projects.
    • boolean_all (Composite): Parent is completed daily only if all active child projects meet their individual daily targets.

πŸ“ Repository Directory Layout

pulse-monolith-bot/
β”œβ”€β”€ .github/workflows/   # CI/CD deployment pipelines
β”œβ”€β”€ docs/                # Project documentation & architectural notes
β”‚   β”œβ”€β”€ explanation/     # Core philosophies, memory pipelines, testing policies
β”‚   β”œβ”€β”€ reference/       # Databases, menus, architecture mapping, backlogs
β”‚   └── sprints/         # Master index and logs of sprints 01-60
β”œβ”€β”€ scripts/             # Infrastructure management scripts (deployment, hooks)
β”œβ”€β”€ src/                 # Main Python codebase
β”‚   β”œβ”€β”€ ai/              # Multi-LLM provider registry, intent router, tools
β”‚   β”œβ”€β”€ bot/             # Telegram views, handlers, state machines, and keyboards
β”‚   β”œβ”€β”€ core/            # Application configuration, personas, security, constants
β”‚   β”œβ”€β”€ db/              # SQLAlchemy schemas and database sessions
β”‚   β”œβ”€β”€ scheduler/       # Celery configuration, async tasks, pings, reports
β”‚   β”œβ”€β”€ scripts/         # Offline tests, doc auditors, migration scripts
β”‚   β”œβ”€β”€ web/             # Web API routes, template rendering, auth controllers
β”‚   β”œβ”€β”€ main.py          # FastAPI + aiohttp Webhook entry point
β”‚   └── worker.py        # Celery background job runner
β”œβ”€β”€ Caddyfile            # Production reverse proxy and SSL configuration
β”œβ”€β”€ docker-compose.yml   # Docker multi-container setup (Bot, Web, Redis, DB)
└── requirements.txt     # Python application dependencies

πŸ› οΈ Installation & Setup

Prerequisites

  • Python 3.13+
  • Redis (for Celery broker)
  • PostgreSQL (for production) or SQLite (for local MVP)

Local Configuration

  1. Clone the repository and initialize a virtual environment:
    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
  2. Create and configure your .env file:
    cp .env.example .env
  3. Generate a secure ENCRYPTION_KEY for API credentials:
    python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
    Paste the generated string into your .env file under ENCRYPTION_KEY.

Running the Application Locally

  • Start Webhook / Polling Bot:
    python3 src/main.py
  • Start Celery Worker & Beat Scheduler:
    celery -A src.worker.celery_app worker --loglevel=info
    celery -A src.worker.celery_app beat --loglevel=info

πŸ§ͺ Testing & Quality Assurance

1. Documentation Semantic Anchor Audit

We enforce a strict pre-push hook ensuring that code anchors match the global map. To run the validation manually:

python3 src/scripts/audit_docs.py

2. Offline Functional Tests

Pulse includes a simulated integration testing framework that mocks Telegram APIs and runs standard user flows (creating projects, logging sessions, logging work, backdating progress) against an offline sqlite database and LLM emulator:

PYTHONPATH=. TELEGRAM_BOT_TOKEN="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" ENCRYPTION_KEY="k68-q_UqA8z4Jq5a34_2e5P5z2Q3R4S5T6U7V8W9X0Y=" ADMIN_PASSWORD="temporary_test_password" python3 src/scripts/run_bot_tests.py

3. Load & Stress Tests

To simulate concurrent traffic and evaluate user lock mechanisms:

PYTHONPATH=. python3 src/scripts/run_stress_tests.py

πŸš€ Production Deployment

Pulse Monolith runs inside a Dockerized container stack, with Caddy acting as the reverse proxy and SSL manager. We support two deployment strategies:

1. Local-First Deploy (Recommended)

Deploys the codebase directly from your developer laptop using rsync and SSH, ensuring the server runs your local updates without requiring a Git push:

./deploy_local.sh

2. CI/CD GitOps Deploy

Pushed changes to main will automatically trigger a GitHub Actions run to validate the test suite, then SSH into the VPS and execute:

bash scripts/deploy.sh

πŸ”’ Security Hardening

  • API Key Encryption: User-supplied API keys for Google GenAI or OpenAI are encrypted at rest inside the database using Fernet symmetric encryption.
  • Caddy HTTP Headers: Hardened security policy headers configured in the Caddyfile.
  • Memory Limits: Docker containers are configured with strict resource and memory limitations to prevent OOM vulnerabilities.

About

Pulse Monolith Bot

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors