Mobile AppsБесплатно

Spartanec - Личный тренер, Telegram Bot

AI-Powered Behavioral Discipline Training via Telegram

~45 минСреднийREADME
TypeScriptExpressPostgreSQLTelegrafReplicateNext.js

Ценность

Вайбкодинг

15 ч

Строк кода

15 000+

Аналог у студии

от 75 000 ₽

Экономия на токенах

≈ 2 000 ₽

Инструкция из репозитория

HARDLINE Training System

AI-Powered Behavioral Discipline Training via Telegram

HARDLINE is not a fitness app. It is a behavioral discipline enforcement system with AI agents that tracks accountability, adapts workouts, analyzes lifestyle patterns, and predicts user outcomes.


🎯 Core Philosophy

  • Discipline over motivation: Factual feedback, no fluff
  • Accountability enforced: Missed reports = penalties
  • AI-driven adaptation: Pain-aware, recovery-first approach
  • Predictive insights: See future outcomes based on current behavior
  • Cold, analytical tone: Direct consequences, not cheerleading

🏗️ Architecture Overview

HARDLINE/
├── src/                    # Backend (Node.js + TypeScript)
│   ├── agents/            # Modular AI agent system
│   │   ├── CoreTrainerAgent.ts
│   │   ├── AnalystAgent.ts
│   │   ├── RecoveryAgent.ts
│   │   ├── AccountabilityAgent.ts
│   │   └── FutureProjectionAgent.ts
│   ├── services/          # Business logic layer
│   │   ├── WorkoutService.ts
│   │   ├── DisciplineService.ts
│   │   └── PredictionService.ts
│   ├── routes/            # Express API routes
│   │   ├── workouts.ts
│   │   └── reports.ts
│   ├── bot/               # Telegram bot handlers
│   │   └── telegram.ts
│   ├── database/          # PostgreSQL connection + schema
│   │   ├── connection.ts
│   │   └── schema.sql
│   ├── types/             # TypeScript interfaces
│   │   └── index.ts
│   └── index.ts           # Main entry point
│
├── miniapp/               # Telegram Mini App (Next.js)
│   ├── src/
│   │   ├── app/          # Next.js app router
│   │   │   ├── layout.tsx
│   │   │   ├── page.tsx
│   │   │   └── globals.css
│   │   └── components/    # React components
│   │       ├── DisciplineScore.tsx
│   │       ├── TodayWorkout.tsx
│   │       ├── QuickReport.tsx
│   │       └── Predictions.tsx
│   ├── package.json
│   └── next.config.js
│
├── package.json
├── tsconfig.json
├── .env.example
└── README.md

🤖 AI Agent System

1. CoreTrainerAgent

Responsibilities:

  • Daily workout generation based on user state
  • Task communication (cold, factual tone)
  • Adaptive workout planning
  • Accountability enforcement
  • User feedback provision

Key Methods:

  • generateDailyTask() - Creates personalized daily workout
  • provideFeedback() - Analyzes user report, returns factual response
  • sendReminder() - Enforces compliance

2. AnalystAgent

Responsibilities:

  • Track sleep, pain, fatigue, stress over time
  • Behavioral pattern analysis
  • Trend detection (improving/declining)
  • Risk scoring (injury, burnout)

Key Methods:

  • analyzeUserPatterns() - Calculate 7-day health metrics
  • detectAnomalies() - Flag sudden pain spikes, sleep deprivation

Outputs:

  • Pain trend: increasing | stable | decreasing
  • Recovery score: 0-100
  • Injury risk: low | medium | high
  • Burnout risk: low | medium | high

3. RecoveryAgent

Responsibilities:

  • Spine-safe workout adaptations
  • Progressive overload logic
  • Pain-based training reduction

Key Methods:

  • assessRecoveryNeed() - Determine if deload required
  • calculateProgressiveOverload() - Check if ready to increase intensity
  • generateSpineSafeModifications() - Modify exercises for pain management

Adaptation Logic:

  • Pain ≥7 → Rest day
  • Pain 5-6 → Deload by 30-40%
  • Pain 3-4 → Deload by 20%
  • High fatigue → Reduce duration
  • High injury risk → Preventive deload

4. AccountabilityAgent

Responsibilities:

  • Proof verification (text/photo/video metadata)
  • Consistency scoring
  • Missed report penalties
  • Streak tracking

Key Methods:

  • verifyProof() - Basic proof analysis
  • calculateConsistencyScore() - 0-100 based on completion rate
  • processMissedReport() - Apply discipline penalty
  • awardConsistencyBonus() - Reward milestone streaks

Scoring Formula:

Consistency = (Report Rate × 60%) + (Workout Rate × 40%)
Completion = Completed Workouts / Assigned Workouts × 100
Punctuality = On-Time Reports / Total Reports × 100

Total Discipline Score = 
  Consistency × 35% + 
  Completion × 35% + 
  Punctuality × 30%

Penalty System:

  • Missed report: -5 points (configurable)
  • Streak broken: Reset to 0

Bonus System:

  • 7-day streak: +5 points
  • 14-day streak: +10 points
  • 30-day streak: +20 points

5. FutureProjectionAgent

Responsibilities:

  • Predict user state in 30/90 days
  • Scenario modeling (consistent vs inconsistent)
  • Outcome forecasting
  • Confidence scoring

Key Methods:

  • generatePrediction() - Calculate future state based on scenario
  • compareScenarios() - Side-by-side comparison of different paths

Scenarios:

  1. Consistent: Perfect compliance → +0.5 discipline/day, injury risk low
  2. Inconsistent: Poor compliance → -0.3 discipline/day, injury risk high
  3. Current Trend: Extrapolate from recent behavior

Outputs:

  • Predicted discipline score
  • Predicted fitness level
  • Predicted injury risk
  • Confidence level (0-1)
  • Reasoning factors

🗄️ Database Schema

Key Tables:

users

  • Profile data (age, weight, height, fitness level)
  • Injury history, spine condition
  • Onboarding information

daily_reports

  • Sleep hours/quality
  • Pain level (0-10)
  • Fatigue, stress levels
  • Workout completion status
  • Proof data (text/photo/video)
  • Submission time (on-time flag)

workouts

  • Name, description, difficulty
  • Exercise list (JSON)
  • Duration, focus areas
  • Spine-safe flag

workout_sessions

  • User assignment
  • Scheduled date
  • Completion status
  • Adaptations applied
  • Performance metrics

health_metrics

  • 7-day averages (pain, sleep, fatigue, stress)
  • Trends (increasing/stable/decreasing)
  • Recovery score
  • Risk flags (injury, burnout)

discipline_scores

  • Total score (0-100)
  • Component scores (consistency, completion, punctuality)
  • Streaks (current, longest)
  • Penalties/bonuses

predictions

  • Target date (30/90 days ahead)
  • Scenario type
  • Predicted outcomes
  • Confidence level
  • Reasoning factors

agent_logs

  • Agent actions and decisions
  • LLM interactions (prompts, responses, tokens)
  • Success/failure tracking

🚀 Setup Instructions

Prerequisites

  • Node.js 20+
  • PostgreSQL 14+
  • Telegram Bot Token (BotFather)
  • OpenAI API Key

1. Clone and Install

cd Spartan
npm install
cd miniapp && npm install

2. Database Setup

# Create database
createdb hardline

# Run schema
psql hardline < src/database/schema.sql

3. Environment Configuration

# Backend
cp .env.example .env
# Edit .env with your credentials

# Mini App
cd miniapp
cp .env.local.example .env.local
# Edit .env.local with API URL

Required Variables:

# Telegram
TELEGRAM_BOT_TOKEN=your_bot_token

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/hardline

# OpenAI
OPENAI_API_KEY=your_openai_key
OPENAI_MODEL=gpt-4-turbo-preview

# Server
PORT=3000

4. Seed Initial Data (Optional)

// Create sample workouts
import { WorkoutService } from './services/WorkoutService';
import { pool } from './database/connection';

const workoutService = new WorkoutService(pool);
await workoutService.seedWorkouts();

5. Start Backend

npm run dev
# or
npm run build && npm start

6. Start Mini App (Development)

cd miniapp
npm run dev

7. Configure Telegram Bot

  1. Go to @BotFather
  2. Set commands:
workout - View today's workout
report - Submit daily report
stats - View discipline score
prediction - View future projections
help - Show all commands
  1. Set Mini App URL (for production):
/setmenubutton
# Provide your deployed Mini App URL

📱 Telegram Bot Usage

User Flow:

  1. Onboarding (/start/onboard)

    • Age, weight, height
    • Fitness level (beginner/intermediate/advanced)
    • Spine condition
    • Training goals
  2. Daily Workflow

    • Morning: Bot sends workout assignment
    • Evening: User reports with /report
    • Feedback: AI provides cold, factual response
  3. Commands

    • /workout - View today's assigned workout
    • /report - Multi-step report submission
    • /stats - Discipline score breakdown
    • /prediction - 30-day future projection

🎨 Mini App Features

Dashboard Sections:

  1. Discipline Score Card

    • Total score with color coding
    • Component breakdown (consistency, completion, punctuality)
    • Current & longest streak
  2. Today's Workout

    • Workout name, duration
    • Adaptation warnings (if applied)
    • Expandable exercise list
  3. Quick Report

    • One-tap workout completion (Yes/No)
    • Auto-submit with default metrics
    • Full report via bot command
  4. 30-Day Projection

    • Predicted discipline score
    • Injury risk forecast
    • AI-generated analysis

🧪 API Endpoints

Workouts

GET  /api/workouts/:userId/today         # Get today's workout
GET  /api/workouts/:userId/history       # Workout history
POST /api/workouts/:userId/assign        # Manually assign workout
POST /api/workouts/:userId/generate      # AI-generate workout
POST /api/workouts/sessions/:id/complete # Mark completed

Reports

POST /api/reports/:userId                # Submit daily report
GET  /api/reports/:userId/today          # Get today's report
GET  /api/reports/:userId/history        # Report history
GET  /api/reports/:userId/analysis       # Health metrics analysis

🔧 Configuration

Discipline System

MIN_DISCIPLINE_SCORE=0
MAX_DISCIPLINE_SCORE=100
MISSED_REPORT_PENALTY=5
WORKOUT_COMPLETION_BONUS=3

AI Agent Settings

OPENAI_MODEL=gpt-4-turbo-preview
AGENT_TEMPERATURE=0.7
AGENT_MAX_TOKENS=1000

📊 Discipline Score Formula

// Consistency (35% weight)
consistency = (reportRate × 60% + workoutRate × 40%) × 100

// Completion (35% weight)
completion = (completedWorkouts / assignedWorkouts) × 100

// Punctuality (30% weight)
punctuality = (onTimeReports / totalReports) × 100

// Total Score
totalScore = (consistency × 0.35) + (completion × 0.35) + (punctuality × 0.30)

🎯 Progressive Overload Logic

Criteria for progression:

  1. ✅ Last 3 sessions completed successfully
  2. ✅ Average difficulty rating < 7/10
  3. ✅ Injury risk = LOW
  4. ✅ No recent pain spikes

When met: Increase workout difficulty level


🛡️ Recovery-First Rules

Pain-Based Deload

  • Pain 7-10: Complete rest (no training)
  • Pain 5-6: Reduce sets by 30-40%, no spine loading
  • Pain 3-4: Reduce sets by 20%, avoid heavy compounds

Injury Risk Response

  • High risk: Mandatory deload (30% volume reduction)
  • Medium risk: Monitor closely, extra warmup
  • Low risk: Proceed normally

Burnout Prevention

  • Fatigue ≥8 or Stress ≥8 → Extended rest
  • Recovery score <40 → Deload week

🔮 Prediction Model

Scenario: Consistent (Perfect Compliance)

Discipline: +0.5 points/day (capped at 100)
Fitness: Improves 1 level per 30 days
Injury Risk: LOW

Scenario: Inconsistent (Poor Compliance)

Discipline: -0.3 points/day (min 0)
Fitness: Regresses after 60 days
Injury Risk: HIGH

Scenario: Current Trend

Extrapolate from recent completion rate:
  >70% = positive trajectory
  <50% = negative trajectory

Confidence Calculation:

  • Start: 90%
  • -20% for 90-day predictions
  • -30% if <5 data points
  • -10% if no health metrics

📦 Deployment

Backend (Node.js)

npm run build
npm start

Production checklist:

  • Set NODE_ENV=production
  • Use PostgreSQL connection pooling
  • Enable rate limiting
  • Configure helmet security headers

Mini App (Next.js)

cd miniapp
npm run build
npm start

Deployment options:

  • Vercel (recommended)
  • Railway
  • DigitalOcean App Platform

Configure:

  • NEXT_PUBLIC_API_URL to backend URL
  • Set Telegram Bot Menu Button to Mini App URL

🔐 Security Considerations

  1. Telegram Auth: Verify initData signature in production
  2. Rate Limiting: Enabled on all API routes
  3. SQL Injection: Using parameterized queries
  4. CORS: Configured for Telegram WebApp origin
  5. Environment Variables: Never commit .env files

🧩 Extensibility

Adding New Agents

// 1. Create agent file
import { BaseAgent, AgentContext, AgentResponse } from './BaseAgent';

export class NewAgent extends BaseAgent {
  constructor() {
    super('NewAgent');
  }

  async performAction(context: AgentContext): Promise<AgentResponse> {
    // Implementation
    await this.logAction(context, 'action', input, output, true);
    return { success: true, data: result };
  }
}

// 2. Initialize in telegram.ts
private newAgent: NewAgent;
this.newAgent = new NewAgent();

Adding New Metrics

-- 1. Add column to health_metrics table
ALTER TABLE health_metrics ADD COLUMN new_metric DECIMAL(3,1);

-- 2. Update AnalystAgent.analyzeUserPatterns()
-- 3. Update types/index.ts interface

🐛 Troubleshooting

Bot not responding

# Check if bot is running
curl http://localhost:3000/health

# Verify Telegram token
# Check logs for errors

Database connection errors

# Test connection
psql postgresql://user:password@localhost:5432/hardline

# Check pool configuration in connection.ts

LLM timeout errors

# Increase timeout in agent config
AGENT_MAX_TOKENS=1500

# Reduce temperature for faster responses
AGENT_TEMPERATURE=0.5

📝 License

MIT


🤝 Contributing

This is an MVP. Contributions welcome for:

  • Advanced proof verification (image/video analysis)
  • More sophisticated prediction models
  • Additional workout libraries
  • Nutrition tracking integration

📞 Support

For issues with:

  • Telegram Bot: Check bot token and webhooks
  • Database: Verify schema and migrations
  • AI Agents: Review OpenAI API key and quotas
  • Mini App: Check CORS and Telegram WebApp SDK

Remember: HARDLINE enforces discipline. No motivational fluff. Feedback is factual and consequence-based.

Master Prompt

Скопируйте в Cursor / Claude Code. Каждый copy даёт новый токен; предыдущий действует ещё 48 часов.

v1.0.0

Войдите, чтобы установить

Приложение бесплатное. Нужен аккаунт — выдадим персональный доступ к репозиторию для установки.

Changelog

  • v1.0.0 · 2026-07-16

    Каталожный релиз Spartanec / HARDLINE с private repo placeholders.