Product Vision
DisciplineOS is not a study app. It is an accountability operating system — built to enforce, monitor, and sustain the behavioral discipline that high-stakes competitive exam aspirants need to succeed over months and years of preparation.
Traditional study platforms assume students are self-motivated. DisciplineOS assumes the opposite: that most aspirants need external structure, real-time feedback, intelligent nudges, and psychological pressure to stay on track.
No two students share the same automation schedule. Every message, reminder, and evaluation is tuned to each student's own wake time, habits, and goals.
Natural language replies are parsed by OpenAI to extract topics studied, hours completed, emotional state, and productivity signals — no forms required.
Loss aversion, streak rewards, and weekly promotions/demotions create behavioral pressure that makes skipping study sessions feel costly.
Long-term consistency tracking, burnout detection, weak subject heatmaps, and focus score trends surface insights that students can't see themselves.
n8n workflows trigger Telegram messages, log data to Google Sheets/PostgreSQL, invoke OpenAI, compute scores, and update leaderboards — with zero manual intervention.
Built to grow from 10 students to 10,000. Multi-tenant architecture, per-user isolation, and a React dashboard allow admin and student access at scale.
Core Design Principle
User Journey
The complete lifecycle of a student from onboarding to long-term accountability.
Student fills onboarding form (HTML or Google Form). Provides name, Telegram username, phone, exam type, daily target hours, wake time, sleep time, preferred study slots, weak subjects, weekly goals, consistency level, and timezone. Data is auto-saved to Google Sheets / PostgreSQL and a unique user_id is assigned.
The Personalized Automation Engine reads the student's profile and generates a unique daily schedule: morning accountability time (wake + 15 min), mid-day check-in times every 2 hours, evening review time, and night summary time. These schedules are stored per-student and drive all automation triggers.
Student receives a personalized Good Morning message on Telegram. Bot asks: today's target, focus subject, planned study hours, and energy level (1–5). Student replies in natural language. AI extracts structured data and logs it as the day's DailyPlan entry.
Bot sends progress check-ins every 2 hours within the student's active window. Asks: completed topics, current focus level, break status, test performance. Student replies freely ("Completed Polity Chapter 3" / "Taking a 15-minute break"). AI logs structured FocusSession entries.
Bot initiates end-of-day review. Asks: total hours studied, what was completed, what was skipped, tomorrow's plan, and overall mood. AI computes DailyScore (0–100) and updates StreakHistory. If the student fails the minimum threshold, streak is broken and penalty applied.
System evaluates the week: were target hours met on ≥4 days? Was 60%+ completion maintained? If yes → student advances to next week's schedule. If no → student repeats the same week. If 3+ failures → full streak reset. Leaderboard updated. AI generates a personalized weekly feedback report.
AI monitors patterns across sessions: detects low consistency (3-day drops), burnout signals (energy < 2 for 2+ days), distraction patterns (short sessions, incomplete logs), and weak subject recurrence. Triggers motivational nudges, break recommendations, or adaptive plan suggestions.
Workflow Architecture
DisciplineOS is composed of five interconnected system layers. Each layer has a distinct responsibility and communicates via event-driven triggers.
Event Flow Overview
Every student message triggers a Telegram webhook that n8n is subscribed to. n8n receives the payload with chat_id, user_id, and raw message text.
n8n queries the Users table via chat_id to retrieve the student's profile, current streak, today's plan, and last activity timestamp.
The raw message + student context is sent to OpenAI GPT-4. The AI extracts: study_topic, duration_minutes, productivity_score (1–10), emotional_signal, break_type, test_score. Returns structured JSON.
Parsed data is written to IncomingMessages, StudyLogs, and FocusSessions tables. Running daily totals are updated in DailySchedules.
Score Calculator evaluates updated daily logs and computes the DailyScore. If study hours ≥ threshold or significant progress logged, streak eligibility flag is updated.
n8n triggers a follow-up Telegram message to acknowledge the update, provide encouragement or correction, and optionally ask the next check-in question.
Database Schema
Complete relational schema for DisciplineOS. All tables follow a PostgreSQL-first design with Google Sheets as the MVP fallback.
Users Table
| Field | Type | Key | Description |
|---|---|---|---|
| user_id | UUID | PK | Unique identifier, auto-generated on registration |
| full_name | VARCHAR(255) | Student's full name | |
| telegram_username | VARCHAR(100) | IDX | Telegram @username for bot delivery |
| telegram_chat_id | BIGINT | IDX | Telegram chat ID for sending messages programmatically |
| phone | VARCHAR(20) | Phone number (optional) | |
| exam_type | ENUM | UPSC / NEET / JEE / PSC / CODING / OTHER | |
| daily_target_hours | DECIMAL(4,2) | Student's self-declared daily study goal | |
| wake_time | TIME | Used to calculate morning accountability trigger | |
| sleep_time | TIME | Defines end of active automation window | |
| timezone | VARCHAR(50) | IANA timezone string e.g. Asia/Kolkata | |
| weak_subjects | TEXT[] | Array of subject names | |
| consistency_level | SMALLINT | Self-reported 1–5 at registration | |
| current_streak | INTEGER | Live streak count (days) | |
| longest_streak | INTEGER | Historical best streak | |
| status | ENUM | ACTIVE / INACTIVE / AT_RISK / BANNED | |
| created_at | TIMESTAMPTZ | Registration timestamp |
DailySchedules Table
| Field | Type | Key | Description |
|---|---|---|---|
| schedule_id | UUID | PK | Auto-generated |
| user_id | UUID | FK → Users | Foreign key to student |
| date | DATE | IDX | Specific date of this schedule |
| planned_hours | DECIMAL(4,2) | Target hours declared in morning check-in | |
| actual_hours | DECIMAL(4,2) | Running total computed from StudyLogs | |
| focus_subject | VARCHAR(100) | Primary subject for the day | |
| tasks_planned | INTEGER | Number of tasks declared | |
| tasks_completed | INTEGER | Completed tasks count (updated live) | |
| completion_pct | DECIMAL(5,2) | tasks_completed / tasks_planned × 100 | |
| streak_qualified | BOOLEAN | True if daily minimums are met | |
| daily_score | SMALLINT | Computed 0–100 score | |
| energy_level | SMALLINT | Morning-declared 1–5 |
StudyLogs Table
| Field | Type | Key | Description |
|---|---|---|---|
| log_id | UUID | PK | |
| user_id | UUID | FK → Users | |
| schedule_id | UUID | FK → DailySchedules | Links to the day's schedule |
| subject | VARCHAR(100) | AI-extracted subject name | |
| topic | TEXT | Specific topic studied | |
| duration_minutes | INTEGER | Duration in minutes (AI-extracted) | |
| productivity_score | SMALLINT | AI-assessed 1–10 | |
| raw_message | TEXT | Original student message | |
| logged_at | TIMESTAMPTZ | When the log was recorded |
StreakHistory Table
| Field | Type | Key | Description |
|---|---|---|---|
| streak_id | UUID | PK | |
| user_id | UUID | FK → Users | |
| streak_start | DATE | First day of streak | |
| streak_end | DATE | Last day (null if ongoing) | |
| streak_length | INTEGER | Number of qualifying days | |
| end_reason | ENUM | DAILY_MISS / WEEKLY_PENALTY / MANUAL_RESET |
Additional Tables
- session_id (PK), user_id (FK), schedule_id (FK)
- start_time, end_time, duration_minutes
- session_type: DEEP_WORK / BREAK / TEST / REVISION
- focus_score (AI computed 1–10)
- notes (AI-extracted summary)
- week_id (PK), user_id (FK), week_start_date
- total_hours, avg_daily_hours
- days_met_minimum, completion_avg_pct
- week_score (0–100), promoted (BOOLEAN)
- ai_feedback (TEXT), leaderboard_rank
- review_id (PK), user_id (FK), date
- total_hours_actual, mood_score (1–5)
- skipped_topics (TEXT[]), tomorrow_plan
- ai_summary, ai_coaching_note
- review_submitted_at (TIMESTAMPTZ)
- leaderboard_id (PK), user_id (FK)
- week_rank, all_time_rank
- discipline_score, focus_score, recovery_score
- streak_badge, consistency_tier
- updated_at (TIMESTAMPTZ)
Automation Flow Design
The automation engine is built on n8n. Each student has an independently scheduled set of workflows that fire based on their personal profile. No two students share the same cron schedule.
Personalized Trigger Calculation
n8n Workflow Architecture
Triggered by: Google Form submission or HTTP POST from onboarding form. Actions: Parse form data → Create Users record → Generate DailySchedule template → Register personalized cron jobs in n8n → Send Welcome Telegram message with orientation instructions.
Triggered by: Per-student cron (wake_time + 15 min). Actions: Fetch student profile → Generate personalized Good Morning message → Send via Telegram Bot API → Create empty DailySchedule record for today → Set session state = MORNING_PENDING.
Triggered by: Telegram webhook on any message. Actions: Identify user by chat_id → Fetch current session_state → Route to appropriate sub-workflow (morning_response / check_in_response / night_review_response) → Call OpenAI parser → Store structured log → Compute running score → Send acknowledgment.
Triggered by: Three per-student crons (wake + 2h, 4h, 6h). Actions: Fetch today's DailySchedule → Check if student has already responded to last ping → If yes: send next question. If no: send gentle reminder + "Still studying?" message → Update PromptLogs.
Triggered by: Per-student cron (sleep_time - 30 min). Actions: Compile day summary from StudyLogs → Send review message asking final totals + mood + tomorrow plan → Set session_state = NIGHT_REVIEW → After response: compute DailyScore → Update StreakHistory → Check streak eligibility.
Triggered by: Weekly cron every Sunday at 11:59 PM (per student timezone). Actions: Aggregate 7 days of DailySchedules → Compute WeeklyPerformance → Run streak penalty logic → Determine promotion/retention → Update Leaderboard → Send AI-generated weekly report via Telegram.
Triggered by: Global cron every 4 hours. Actions: Query all ACTIVE users → Check last_activity_at → If > 26 hours and no morning response: send re-engagement message → If > 48 hours: mark status = AT_RISK → If > 72 hours: notify admin and pause automation.
AI Processing Pipeline
OpenAI GPT-4 acts as the understanding layer between raw student messages and structured database records.
AI Parser — System Prompt Architecture
AI Coaching Prompt Architecture
AI Processing Events
Every inbound Telegram message is parsed to extract structured study data. Fires on every student reply.
AI contextualizes the daily score: explains why the student scored X and what they should adjust tomorrow.
Fires weekly. Detects multi-day trends: consistent weak spots, session length patterns, subject neglect.
Fires when energy score ≤ 2 for 2+ consecutive days. Generates a special recovery message with revised lighter targets.
Streak Engine Logic
The streak system is the psychological core of DisciplineOS. It creates loss aversion, rewards consistency, and enforces minimum standards through a strict rule engine.
Daily Streak Qualification Rules
Streak Calculation Algorithm
Streak Status States
Streak Visualization (30-day sample)
■ Qualified ■ Miss ■ At Risk
Recovery System
Weekly Progression Logic
- Met daily minimum on ≥ 4 of 7 days
- Average completion ≥ 60% for the week
- No weekly penalty triggered
- Receives "Level Up" badge and next week tasks
- Failed daily minimum on ≥ 4 days
- Average completion < 60%
- Repeats same week's syllabus/tasks
- AI generates revised lighter schedule
Daily Accountability Logic
The daily cycle is a structured sequence of Telegram interactions designed to keep students accountable from morning to night.
Daily Score Formula
Daily Prompt Sequence
"Good morning [Name]! 🌅 Day [N] of your UPSC journey. What's your target for today? (Hours + focus subject + energy level 1-5)"
"[Name], first check-in! What have you covered so far? Any topics completed?"
"Midday check! How's the focus? Any breaks taken? What's your current study count?"
"Afternoon update — are you on track for today's goal? Feeling any burnout?"
"2 hours left in your window. Final push — what's remaining on today's list?"
"Day complete! Final report: total hours? What did you nail? What did you skip? Mood? Tomorrow's plan? Your streak is [N] days 🔥"
Missed Check-in Escalation
Gentle re-send: "Hey! Just checking — did you see my earlier message?"
Motivational pressure: "Your streak is at risk if you don't check in today. 5 minutes is all it takes."
Loss framing: "No response yet. If your night review isn't submitted, today won't count toward your streak."
Weekly Evaluation Logic
Every Sunday night, the Weekly Evaluator runs per-student. It determines promotion, calculates week score, updates leaderboard, and generates AI feedback.
Week Score Formula
Weekly Decision Matrix
| Days Met Minimum | Avg Completion | Streak Status | Outcome |
|---|---|---|---|
| 5–7 days | ≥ 70% | Active | PROMOTED + Bonus Badge |
| 4 days | ≥ 60% | Active | PROMOTED |
| 4 days | < 60% | Any | RETAINED — Repeat Week |
| 3 days | Any | Any | RETAINED + AT_RISK Flag |
| 0–2 days | Any | Any | RETAINED + Full Streak Reset |
Weekly AI Report Contents
- Total hours studied vs target
- Best and worst performing subjects
- Consistency score breakdown
- Productivity trend (↑ ↓ →)
- Subject neglect detection
- Burnout risk assessment
- Next week recommended adjustments
- Motivational message with streak context
Leaderboard & Gamification
The gamification layer transforms daily discipline into a competitive, rewarding experience with ranks, badges, and meaningful scores.
Score Components
Streak Badges
7-day streak. First milestone. "You've planted the seed of habit."
21-day streak. Habit formation zone. "21 days of pure discipline."
45-day streak. Unstoppable. "Nothing can stop your momentum now."
90-day streak. Elite level. "3 months of unwavering consistency."
180-day streak. Rare. "Half a year. The true definition of discipline."
365-day streak. One of a kind. "A year of daily discipline. You are unstoppable."
Burnout Detection Logic
AI Coaching Layer
The AI coaching layer operates as a passive monitor that surfaces actionable insights when patterns emerge across days and weeks.
Triggered after 3 consecutive below-minimum days. AI sends a pattern-awareness message: "You've missed your goal 3 days in a row. Here's a recovery plan."
Monitors energy level + emotional signal across messages. When exhaustion patterns appear, AI reduces targets and recommends rest proactively.
Short sessions (<30 min), many break logs, low productivity scores for 2+ days → AI flags distraction and suggests focus techniques (Pomodoro, etc).
Cross-references user-declared weak subjects against actual study logs. If a weak subject hasn't appeared in logs for 3+ days, AI nudges the student to address it.
After a hard week, AI generates a revised week plan that redistributes topics based on what was missed, with realistic lower daily targets to rebuild momentum.
AI generates context-aware messages that reference the student's own streak, exam date, and progress — never generic. "You're 27 days from your UPSC Prelims target date."
Edge Cases
| Edge Case | Detection | System Response |
|---|---|---|
| Student doesn't respond to morning ping | No incoming message within 2h of morning trigger | Send 3-level escalation reminders. Mark day as AT_RISK after 3rd miss. |
| Student reports false hours | Productivity score inconsistent with claimed duration (AI flags anomalies) | AI scores low for productivity, reducing overall daily score. Flag for admin review after 3 anomalies. |
| Timezone change | Student updates timezone in profile | Recalculate all cron triggers for that student. Do not restart streak. |
| Exam date passed | exam_date field in Users crosses current date | Pause automation. Send congratulations + results check-in message. Offer new exam enrollment. |
| Student explicitly says they're sick | AI detects health keywords (sick, fever, hospital, unwell) | Grant a 1-day "health break" — day excluded from streak calculation. Max 2 per month. |
| Duplicate messages sent | n8n workflow fires twice due to cron overlap | Idempotency check on PromptLogs: if a prompt of the same type was sent within 30 min, skip second send. |
| OpenAI API failure | API returns 500 or timeout | Retry 3×. If all fail: store raw message as-is in IncomingMessages with ai_processed = false. Reprocess in background queue within 1 hour. |
| Student sends unrelated message | AI classification: no study data extracted | AI responds naturally ("Got it! Let me know when you start your next session.") — no log created. |
| Long inactivity (3+ days) | last_activity_at > 72 hours | Mark INACTIVE. Stop all pings. Send re-engagement message. Admin notification. Manual review required to reactivate. |
Failure Recovery System
All critical system components have failure recovery paths designed to ensure no data is lost and no student is left in a broken state.
- All workflows wrapped in try/catch nodes
- Failed executions logged to Errors table with payload
- Dead Letter Queue for failed messages
- Admin Telegram alert on 3+ failures in 1 hour
- Automatic retry with exponential backoff (1s, 5s, 30s)
- Circuit breaker: disable AI if 5+ failures in 10 min
- Fallback: store raw message, flag ai_processed = false
- Batch reprocess job runs every 60 minutes
- Graceful degradation: daily scores computed without AI if needed
- Retry up to 5× with 10-second intervals
- Rate limit detection: queue messages with delay
- Bot blocked: mark user as TELEGRAM_BLOCKED, pause automation
- Log all send attempts in PromptLogs (sent/failed/queued)
- PostgreSQL: daily automated backups to S3
- Read replicas for leaderboard/analytics queries
- Connection pool monitoring with auto-restart
- Google Sheets: interim fallback for MVP phase
Scalability Plan
Scaling Tiers
| Tier | Students | Stack | Key Changes |
|---|---|---|---|
| MVP | 1 – 50 | n8n + Google Sheets + OpenAI | All-in-one, single server, sheets as DB |
| Growth | 50 – 500 | n8n + PostgreSQL + Redis | Migrate to PostgreSQL, add Redis queues, per-student cron optimization |
| Scale | 500 – 5000 | + React Dashboard + Docker Compose | Multi-container deployment, read replicas, message queue for Telegram |
| Enterprise | 5000+ | Kubernetes + CDN + Analytics | K8s autoscaling, tenant isolation, analytics data warehouse, admin portal |
Performance Bottlenecks & Solutions
- Replace individual crons with Redis-backed priority queue
- n8n polls queue; workers pick up due tasks
- Group students by timezone bucket (±30 min) for efficiency
- Target: <2s message delivery latency per student
- Cache common phrase patterns (avoid redundant API calls)
- Batch low-priority parsing jobs during off-peak hours
- Fine-tune a smaller model on study log data over time
- Target: 60% reduction in API spend by 1000 users
Security Considerations
All student data is accessed via user_id. No cross-student data exposure. Row-level security enforced in PostgreSQL using RLS policies.
Telegram Bot Token, OpenAI API Key, and DB credentials stored in Docker secrets or HashiCorp Vault. Never in environment variables in production.
Telegram webhook verified via X-Telegram-Bot-Api-Secret-Token header. Webhook endpoint only accepts HTTPS requests from Telegram IP ranges.
Raw messages purged after 90 days. Aggregated scores and streaks retained indefinitely. Students can request full data export (GDPR-ready structure).
n8n dashboard behind VPN or IP whitelist. All admin operations require 2FA. n8n credentials encrypted at rest using AES-256.
All admin actions (streak overrides, manual resets, status changes) logged to an immutable AuditLogs table with actor_id, action, and timestamp.
Production Deployment Architecture
MVP Deployment (Docker Compose)
Infrastructure Stack
- VPS: DigitalOcean / Hetzner (4GB RAM, 2 vCPU)
- Docker Compose orchestration
- n8n: automation engine + webhook receiver
- PostgreSQL: primary data store
- Redis: queues and caching
- Nginx: reverse proxy + SSL (Let's Encrypt)
- Kubernetes (K3s or EKS)
- React Dashboard (Vercel / CloudFront)
- PostgreSQL with read replicas (RDS)
- Redis cluster for multi-node queuing
- Analytics: ClickHouse + Metabase
- CI/CD: GitHub Actions → Docker Hub → K8s
Future SaaS Expansion Plan
DisciplineOS is built from day one with multi-tenancy in mind. The path to a full SaaS product is incremental and implementation-ready.
SaaS Roadmap
Manual onboarding via form. Single n8n instance. Google Sheets as database. Validate core accountability loop and streak psychology. Collect feedback aggressively.
Migrate to PostgreSQL. Add payment via Razorpay. Create batch enrollment (cohort model — 20 students per cohort). Build basic admin dashboard for monitoring student health scores. Introduce weekly leaderboard.
Student self-registration portal. Subscription billing (₹499/month). React dashboard for students (streak calendar, score charts, weak subject heatmap). Admin panel for mentor intervention. Exam-specific personas (UPSC mode vs NEET mode).
White-label offering for coaching institutes. Multi-mentor support (each mentor manages a group). AI study resource recommendations. Integration with YouTube playlists, PDFs, and test series. Mobile app (React Native). Analytics API for coaching institutes.
Monetization Model
₹299–₹799/month per student. Tiered based on features (basic accountability vs full AI coaching vs mentor support).
₹50–₹150/student/month for coaching institutes using DisciplineOS as a white-label platform for their enrolled students.
Platform commission (15–20%) on sessions booked between students and independent mentors discovered through DisciplineOS.
System Documentation v1.0 · Production-Grade · Built for Scale