Compare commits

..

12 commits

Author SHA1 Message Date
Claude
60e7eadb1e Add portable distribution build system
Zero-install Windows distribution:
- Embeddable Python 3.12 (no installer needed)
- SQLite default (already in codebase)
- Pre-built frontend bundled
- Cross-downloads Windows wheels on Linux build host
- start.bat launcher: extract, double-click, done
- 22MB zip / 61MB extracted
- No Docker, no Python install, no admin rights
- Data stays in the portable folder (USB-stick friendly)
2026-09-20 23:22:24 +00:00
Claude
9ab9135ca2 Review and fix documentation errors across all install guides
Linux fixes:
- NodeSource: setup_lts.x does not exist, replaced with setup_22.x
- Added sudo apt install nodejs as simplest Ubuntu 26.04 option
- nvm version pinned to v0.40.1 (widely verified)
- Added auth token note for Gemini SSE config
- USERNAME placeholders clarified with whoami hint
- systemd service section now covers venv installs

Windows fixes:
- DILIGENCE_PATH placeholder replaced with auto-resolving PowerShell
  using double-quoted here-strings and -replace for JSON backslashes
- Claude Desktop config now sets both standard and Store paths in one block
- Added auth token note for Gemini SSE config
- ChatGPT config path caveated (varies by version)
2026-08-03 08:01:22 +00:00
Claude
aba8d42123 Add Linux installation guide with all AI agent options
Covers Debian/Ubuntu, Fedora, Arch. Includes:
- Gemini CLI (recommended free: 1000 req/day, SSE direct)
- Claude Desktop (official Linux beta via apt, stdio)
- ChatGPT/Codex CLI (paid only, noted as unavailable on Linux)
- Built-in AI Coach (free API keys + Ollama offline)
- systemd service for auto-start
- venv vs system-wide install options
- No tzdata needed (Linux has system timezone DB)
2026-08-03 06:44:44 +00:00
Claude
37c152060a Comprehensive Windows install guide with all AI agent options
Covers four AI integration paths:
- Gemini CLI (recommended free: 1000 req/day, SSE+stdio)
- Claude Desktop (free account, stdio only)
- ChatGPT Desktop (paid only, stdio)
- Built-in AI Coach (simplest: free API keys from OpenRouter/Groq/
  Google AI Studio/Hugging Face/Ollama)

Includes full troubleshooting table for all known Windows issues.
2026-08-03 06:42:02 +00:00
Claude
c1f01ea72f Add installation guides: Giordano fix + full Windows install
- docs/GIORDANO-FIX.md: step-by-step for next session with Giordano
- docs/INSTALL-WINDOWS.md: complete clean install guide for any Windows machine
2026-08-03 06:22:11 +00:00
Claude
b63e5f7f5b Switch from mcp SDK to standalone fastmcp package
The mcp SDK v2.0.0 (2026-07-28) renamed FastMCP to MCPServer
and removed the mcp.server.fastmcp import path entirely.
The standalone fastmcp package (PrefectHQ, v3.x) is the actively
maintained framework with identical @mcp.tool() decorator API.

- pyproject.toml: [mcp] extra now requires fastmcp>=3.0.0
- server.py: import changed from mcp.server.fastmcp to fastmcp
- mcp_stdio.py: unchanged (imports from diligence.mcp.server)
2026-08-03 03:53:23 +00:00
Claude
00fcc9f0c6 Pin mcp<2.0.0: v2 removed FastMCP from mcp.server.fastmcp
MCP SDK v2.0.0 extracted FastMCP into a separate package,
breaking the import at mcp.server.fastmcp.FastMCP. Pin to
v1.x until the server code is updated for the v2 API.
2026-08-03 03:45:18 +00:00
Claude
8aab7c0c4a Add stdio MCP launcher for Claude Desktop
Claude Desktop's config file only supports stdio transport.
This script launches the MCP server in stdio mode, connecting
to the already-running Diligence backend at localhost:8000.
2026-08-03 03:33:42 +00:00
Claude
aeb0b438cc Fix Windows crash: add tzdata dependency, harden timezone fallback
On Windows, Python's zoneinfo module has no system timezone database.
Without the tzdata package, ZoneInfo('UTC') raises ZoneInfoNotFoundError,
crashing both /api/points/today and /api/nutrition/today (Home and Keto
pages show 'failed to load').

Two fixes:
1. Add tzdata>=2024.1 to pyproject.toml dependencies so pip install
   pulls it automatically
2. Harden dates.py with _safe_tz() that falls back to datetime.timezone.utc
   (always available, no tzdata needed) as the ultimate fallback
2026-08-03 02:20:57 +00:00
Claude
3beca1ca2f Add missing schema migrations for timezone columns
Existing databases (from pre-July-5 installs) were missing:
- users.timezone (v4.2)
- nutrition_goals.diet_style and timezone_str (v4.3)

create_all only adds these to brand-new databases. The migration
system now detects and adds them on startup, matching the pattern
used for all other schema additions.
2026-08-03 02:12:44 +00:00
Claude
62a5d3bfcb docs: add bibliography and source index for seed data
12 sources documented with URLs, licenses, record counts,
fields used, provenance notes, and citation info.
Licensing summary table confirms exercise + food libraries
are fully redistributable (MIT + public domain).
2026-07-19 02:26:38 +00:00
Claude
2ff0b1c6ce feat: add seed data — 2,079 exercises + 8,068 foods with lifestyle pattern tags
Exercise library:
- Merged hasaneyldrm/exercises-dataset (1,324, MIT, 10 languages)
  with yuhonas/free-exercise-db (873, public domain)
- 112 overlap exercises enriched from both sources
- Unified schema: body_part, equipment, target_muscle, force,
  level, mechanic, multilingual instructions
- Categories: strength (1,871), flexibility (105), plyometrics (60), cardio (43)

Food library:
- Merged USDA Foundation Foods (363) + SR Legacy (7,793)
- 25 USDA categories, 99% macronutrient completeness
- Lifestyle pattern tags: Mediterranean, DASH, Blue Zones,
  plant-based, anti-inflammatory, keto
- Framed as lifestyle choices, not weight loss schemes

See data/seed/INVENTORY.md for full details.
2026-07-19 02:22:56 +00:00
19 changed files with 835093 additions and 17 deletions

4
.gitignore vendored
View file

@ -29,3 +29,7 @@ Thumbs.db
# Content (scraped recipes — not for distribution)
content/
# Portable build artifacts
portable/build/
portable/dist/

176
data/seed/BIBLIOGRAPHY.md Normal file
View file

@ -0,0 +1,176 @@
# Diligence Content Compendium — Bibliography & Source Index
**Compiled:** 2026-07-19
**Repo:** `subo.littlefake.com/scot/fitness-rewards`
**Path:** `data/seed/`
---
## Exercise Data Sources
### 1. hasaneyldrm/exercises-dataset
- **URL:** https://github.com/hasaneyldrm/exercises-dataset
- **License:** MIT (exercise data — names, categories, body parts, equipment, targets, muscle groups, multilingual instructions)
- **Media license:** Gym Visual proprietary — GIFs/images removed from repo (Jun 2026) due to conflicting ownership claims. `media_id` references retained but point to no bundled assets. Separate license required from https://gymvisual.com/ for any visual media use.
- **Version:** Commit `225b17d` (data-only, post-media-removal)
- **Records:** 1,324 exercises
- **Languages:** English, Spanish, Italian, Turkish, Russian, Chinese, Hindi, Polish, Korean, French
- **Fields used:** id, name, category, body_part, equipment, instructions (dict by language), instruction_steps, muscle_group, secondary_muscles, target, media_id
- **Attribution:** Dataset created for the LogPress app. Per NOTICE.md, exercise data is MIT; any media use requires Gym Visual attribution (© Gym Visual — https://gymvisual.com/) and compliance with their Terms & Conditions.
- **Stars:** ~15.7K (Jul 2026)
- **Provenance note:** Co-authored commits with Claude Opus 4.8 visible in git history. Data appears derived from ExerciseDB / exercisedb.io with Gym Visual media, restructured and translated.
### 2. yuhonas/free-exercise-db
- **URL:** https://github.com/yuhonas/free-exercise-db
- **License:** Unlicense (public domain)
- **Records:** 873 exercises
- **Languages:** English only
- **Fields used:** name, force (push/pull/static), level (beginner/intermediate/expert), mechanic (compound/isolation), equipment, primaryMuscles, secondaryMuscles, instructions (array of steps), category, images, id
- **Attribution:** Originally derived from exercises.json. Public domain, no attribution required.
- **Images:** 873 exercises have image references (relative paths like `Exercise_Name/0.jpg`, `Exercise_Name/1.jpg`). Images are bundled in the repo under `exercises/` — static position photos, not animated GIFs.
- **Provenance note:** Community-maintained. Exercises stored as individual JSON files in `exercises/` directory.
### 3. Unified exercise library (compiled)
- **File:** `data/seed/unified-exercise-library.json`
- **Records:** 2,079 unique exercises
- **Composition:** 1,206 unique to hasaneyldrm + 761 unique to free-exercise-db + 112 merged from both
- **Merge logic:** Name-matched (case-insensitive). Overlapping exercises enriched with force/level/mechanic from free-exercise-db and multilingual instructions from hasaneyldrm. Equipment and body part terms normalized to a controlled vocabulary. Deterministic UUIDs generated from source+id hash.
- **Index file:** `data/seed/exercise-index.json` — grouped by body_part, equipment, and category for fast lookup.
---
## Food & Nutrition Data Sources
### 4. USDA FoodData Central — Foundation Foods
- **URL:** https://fdc.nal.usda.gov/download-datasets
- **Download:** `FoodData_Central_foundation_food_json_2026-04-30.zip`
- **License:** U.S. Government work, public domain (no copyright)
- **Records:** 363 foods (after filtering 32 null entries from 395 total)
- **Release date:** April 30, 2026
- **Description:** Lab-analyzed nutrient profiles for commonly consumed foods. Highest-quality USDA data — each food has analytically determined values from multiple samples across different locations and time periods.
- **Fields used:** fdcId, description, foodCategory, foodNutrients (per-nutrient: name, amount, unitName), foodPortions (portionDescription, gramWeight), publicationDate
- **Nutrients extracted:** 22 key nutrients per food (calories, protein, fat, carbs, fiber, sugar, sodium, calcium, iron, magnesium, potassium, zinc, vitamins A/C/D/B12, folate, saturated/mono/polyunsaturated fat, cholesterol, water)
- **Citation:** U.S. Department of Agriculture, Agricultural Research Service. FoodData Central, 2026. fdc.nal.usda.gov.
### 5. USDA FoodData Central — SR Legacy
- **URL:** https://fdc.nal.usda.gov/download-datasets
- **Download:** `FoodData_Central_sr_legacy_food_json_2018-04.zip`
- **License:** U.S. Government work, public domain (no copyright)
- **Records:** 7,793 foods
- **Release date:** April 2018 (final release of the Standard Reference database)
- **Description:** The USDA National Nutrient Database for Standard Reference, Legacy Release. Comprehensive nutrient data for ~8,000 food items. Superseded by Foundation Foods and FNDDS for new analyses but remains the most complete single-file whole-food reference.
- **Categories (25):** Beef Products (954), Vegetables (814), Baked Products (518), Lamb/Veal/Game (464), Poultry (383), Beverages (366), Sweets (358), Fruits (355), Baby Foods (345), Pork (336), Fast Foods (312), Dairy/Egg (291), Legumes (290), Finfish/Shellfish (264), Soups/Sauces (254), Fats/Oils (216), Breakfast Cereals (195), Cereal Grains/Pasta (181), Snacks (176), Sausages/Luncheon Meats (167), American Indian/Alaska Native Foods (165), Nuts/Seeds (137), Restaurant Foods (109), Meals/Entrees/Sides (81), Spices/Herbs (63)
- **Citation:** U.S. Department of Agriculture, Agricultural Research Service. USDA National Nutrient Database for Standard Reference, Legacy Release. Available at fdc.nal.usda.gov.
### 6. Unified food library (compiled)
- **File:** `data/seed/unified-food-library.json`
- **Records:** 8,068 foods
- **Composition:** 363 from Foundation Foods (priority) + 7,705 from SR Legacy (gap-fill). Foundation Foods take precedence when both datasets contain the same food.
- **Lifestyle pattern tagging:** Each food tagged with applicable eating patterns based on category membership and keyword matching. Patterns: Mediterranean, DASH, Blue Zones, plant-based, anti-inflammatory, keto. Keto tag additionally filtered by carbs ≤ 10g/100g.
- **Nutrient completeness:** calories 96%, protein 99%, fat 99%, carbs 99%, fiber 90%
- **Index file:** `data/seed/food-index.json` — grouped by USDA category and lifestyle pattern.
---
## Lifestyle Content Sources (Crawled)
The following were crawled 2026-07-19 using ttp-crawler on subo for lifestyle eating framing and pattern descriptions. Stored in `/home/claude/diligence-content/food/crawled/` (not in git — reference material for future content generation).
### 7. Harvard T.H. Chan School of Public Health — The Nutrition Source
- **URLs:**
- https://nutritionsource.hsph.harvard.edu/healthy-eating-plate/
- https://nutritionsource.hsph.harvard.edu/what-should-you-eat/
- **Content:** Healthy Eating Plate guidelines, food group recommendations, evidence-based eating guidance
- **Quality:** Full content retrieved (38KB + 7KB)
- **License:** Educational/research use. Content © The President and Fellows of Harvard College.
- **Use:** Reference for lifestyle pattern descriptions and evidence-based food group framing.
### 8. Harvard Health Publishing
- **URLs:**
- https://www.health.harvard.edu/staying-healthy/mindful-eating
- https://www.health.harvard.edu/staying-healthy/foods-that-fight-inflammation
- **Content:** Mindful eating practices, anti-inflammatory food lists and principles
- **Quality:** Full articles retrieved (13KB each)
- **License:** Content © Harvard Health Publishing. Reference use only.
- **Use:** Framing eating as mindfulness practice; anti-inflammatory pattern food lists.
### 9. National Heart, Lung, and Blood Institute (NHLBI)
- **URL:** https://www.nhlbi.nih.gov/education/dash-eating-plan
- **Content:** DASH Eating Plan overview — food groups, serving sizes, principles
- **Quality:** Good overview retrieved (4KB)
- **License:** U.S. Government work, public domain
- **Use:** DASH pattern definition and food group serving guidance.
### 10. NutritionFacts.org
- **URL:** https://nutritionfacts.org/topics/plant-based-diets/
- **Content:** Plant-based diet research summaries, topic index with 74 linked posts
- **Quality:** Rich content (27KB)
- **License:** Content by Michael Greger, M.D. Reference use only.
- **Use:** Plant-based pattern evidence base and food recommendations.
### 11. Blue Zones (Dan Buettner / Blue Zones LLC)
- **URLs attempted:** https://www.bluezones.com/recipes/food-guidelines/ (blocked — 403)
- **Content recovered via web search:** Blue Zones food guidelines, 11 principles, longevity diet pillars (plant slant, beans as cornerstone, hara hachi bu, whole grains, seasonal vegetables)
- **Key sources found:**
- Blue Zones Food Guidelines page (blocked but content indexed by search engines)
- NPR: "Eating To Break 100: Longevity Diet Tips From The Blue Zones" (Apr 2015)
- NASM: "The Blue Zone Diet: What to Eat to Live Longer"
- News-Medical.net: "The Principles of the Blue Zone Diet" (Feb 2024)
- **Reference:** Buettner, D. (2012). The Blue Zones: 9 Lessons for Living Longer. National Geographic. Buettner, D. & Skemp, S. (2016). Blue Zones: Lessons From the World's Longest Lived. American Journal of Lifestyle Medicine, 10(5), 318-321.
- **Use:** Blue Zones pattern definition and food recommendations.
### 12. Oldways Preservation Trust
- **URLs:**
- https://oldwayspt.org/traditional-diets/mediterranean-diet
- https://oldwayspt.org/traditional-diets/asian-diet
- https://oldwayspt.org/traditional-diets/african-heritage-diet
- **Content:** Traditional diet pyramid descriptions (thin — JS-heavy site returned minimal text)
- **Quality:** Limited (40-69 words per page via curl)
- **License:** Content © Oldways Preservation Trust. Reference use only.
- **Use:** Mediterranean, Asian Heritage, and African Heritage diet pattern framing. Would benefit from manual review or Playwright crawl for full content.
---
## Sources Considered but Not Included
| Source | Reason |
|--------|--------|
| Nutrola Open Food Nutrition Dataset (500K+ foods, CC BY-SA 4.0) | GitHub repo `nutrola/open-food-nutrition-dataset` returned 404. May be private or renamed. Worth revisiting — would add branded food data. |
| OpenNutrition (300K+ foods, TSV) | Download endpoint returned HTML, not data file. API may require auth or different URL. |
| Open Food Facts (4M+ products) | Already integrated in Diligence via API (search_food MCP tool). Bulk download available at https://world.openfoodfacts.org/data but 8GB+ compressed — too large for seed data. |
| Google Nutrition5k (5,006 dishes, CC 4.0) | Visual/ML research dataset — dish photos with nutrition. Useful for future image-based food logging, not for seed library. |
| USDA FNDDS (Food and Nutrient Database for Dietary Studies) | 64MB JSON — survey-oriented, maps to What We Eat In America. Useful for meal composition research but too specialized for seed data. |
| USDA Branded Foods (3.1GB) | 400K+ branded products. Too large for seed; better served by live API (USDA FoodData Central API or Open Food Facts). |
| ExRx.net exercise database | Copyrighted. Excellent reference for exercise technique but not redistributable. |
| ACE (American Council on Exercise) exercise library | Copyrighted. Professional reference, not open data. |
| NSCA exercise database | Copyrighted. Academic/professional use, not open data. |
---
## Licensing Summary
| Source | License | Redistribution | Attribution required |
|--------|---------|---------------|---------------------|
| hasaneyldrm exercise data | MIT | ✅ Yes | MIT notice |
| hasaneyldrm exercise media | Gym Visual proprietary | ❌ Separate license needed | © Gym Visual |
| free-exercise-db | Unlicense (public domain) | ✅ Yes | None |
| USDA Foundation Foods | U.S. Gov't public domain | ✅ Yes | Courtesy citation |
| USDA SR Legacy | U.S. Gov't public domain | ✅ Yes | Courtesy citation |
| Harvard content | © Harvard | ❌ Reference only | Full citation |
| NHLBI content | U.S. Gov't public domain | ✅ Yes | Courtesy citation |
| NutritionFacts.org content | © Michael Greger | ❌ Reference only | Full citation |
| Blue Zones content | © Blue Zones LLC | ❌ Reference only | Full citation |
**Bottom line:** The compiled exercise library (MIT + public domain data) and food library (USDA public domain) are fully redistributable under MIT/public domain terms. The crawled lifestyle content is reference material for generating original descriptions — not for direct reproduction.

185
data/seed/INVENTORY.md Normal file
View file

@ -0,0 +1,185 @@
# Diligence Content Compendium — Inventory
**Generated:** 2026-07-19
**Purpose:** Pre-loaded content for the Diligence fitness + lifestyle app
**Location:** `/home/claude/diligence-content/` on subo
---
## Exercise Library
**Path:** `exercises/`
**Status:** ✅ COMPILED — ready for integration
### Datasets merged
| Source | License | Exercises | Languages | Unique fields |
|--------|---------|-----------|-----------|---------------|
| hasaneyldrm/exercises-dataset | MIT | 1,324 | 10 (en, es, it, tr, ru, zh, hi, pl, ko, fr) | muscle_group, media_id |
| yuhonas/free-exercise-db | Public domain | 873 | 1 (en) | force, level, mechanic |
### Unified library
- **File:** `exercises/unified-exercise-library.json` (2,079 exercises)
- **Index:** `exercises/exercise-index.json` (grouped by body_part, equipment, category)
- Overlap: 112 exercises (enriched from both sources)
- Unique from hasaneyldrm: 1,206
- Unique from free-exercise-db: 761
### Schema per exercise
```json
{
"id": "UUID (deterministic from source+id)",
"source_id": "original ID",
"sources": ["hasaneyldrm", "free-exercise-db"],
"name": "3/4 Sit-Up",
"slug": "3-4-sit-up",
"category": "strength|cardio|flexibility|plyometrics",
"body_part": "core|legs|arms|back|chest|shoulders|neck|cardio",
"equipment": "bodyweight|dumbbell|barbell|cable|machine|...",
"target_muscle": "abs",
"secondary_muscles": ["hip flexors"],
"force": "push|pull|static",
"level": "beginner|intermediate|expert",
"mechanic": "compound|isolation",
"instructions": {"en": ["step 1", "step 2"], "es": [...], ...},
"tips": null,
"media_id": "0001"
}
```
### Coverage
| Dimension | Count |
|-----------|-------|
| Strength | 1,871 |
| Flexibility | 105 |
| Plyometrics | 60 |
| Cardio | 43 |
| Bodyweight | 411 |
| Dumbbell | 403 |
| Barbell | 306 |
| Beginner-tagged | 523 |
| Intermediate-tagged | 293 |
| Expert-tagged | 57 |
### Media status
The hasaneyldrm dataset originally included GIFs from Gym Visual, but they were removed due to ownership disputes. The data now ships with `media_id` references only. Options for media:
1. License from Gym Visual directly (commercial use)
2. Generate descriptions + prompt-based illustrations
3. Link to YouTube/free video demonstrations
4. Community-contributed (user-uploaded form videos)
---
## Food & Lifestyle Library
**Path:** `food/`
**Status:** ✅ COMPILED — ready for integration
### USDA Foundation Foods (Apr 2026)
- **File:** `food/usda-foundation/` — 363 foods, detailed nutrient profiles
- Source: USDA FoodData Central, public domain
- Very high quality, lab-verified nutrients
### USDA SR Legacy (Apr 2018)
- **File:** `food/usda-sr-legacy/` — 7,793 foods, comprehensive categories
- Source: USDA FoodData Central, public domain
- Complete USDA reference dataset for whole/common foods
### Unified food library
- **File:** `food/unified-food-library.json` (8,068 foods)
- **Index:** `food/food-index.json` (grouped by category + lifestyle pattern)
- 25 USDA categories, 99% nutrient completeness for macros
### Lifestyle pattern tags
Each food is tagged with applicable eating patterns — framed as lifestyle choices, not diets:
| Pattern | Foods tagged | Philosophy |
|---------|-------------|------------|
| DASH | 4,252 (52%) | Heart health through balanced whole foods |
| Mediterranean | 3,127 (38%) | Traditional regional eating, olive oil, seafood, plants |
| Keto | 2,455 (30%) | Low-carb, high-fat whole foods |
| Blue Zones | 2,210 (27%) | Longevity-focused: beans, greens, whole grains |
| Plant-based | 2,102 (26%) | Whole food, plant-forward eating |
| Anti-inflammatory | 1,909 (23%) | Foods that reduce chronic inflammation |
| Untagged | 2,341 (29%) | General foods, processed items, baby foods |
### Crawled lifestyle content
**Path:** `food/crawled/` — evidence-based content from health sources
| Source | Topic | Quality |
|--------|-------|---------|
| Harvard T.H. Chan | Healthy Eating Plate | ✅ Full content (38KB) |
| Harvard T.H. Chan | What Should I Eat? | ✅ Good overview (7KB) |
| Harvard Health | Mindful Eating | ✅ Full article (13KB) |
| Harvard Health | Anti-inflammatory Foods | ✅ Full article (13KB) |
| NutritionFacts.org | Plant-Based Diets | ✅ Rich content (27KB) |
| NHLBI | DASH Eating Plan | ✅ Good overview (4KB) |
| Blue Zones (web search) | Food Guidelines | ✅ Via search results |
| Oldways | Mediterranean/Asian/African Heritage | ⚠️ Thin (JS-heavy site) |
### Nutrients per 100g (schema)
```json
{
"calories": 160,
"protein_g": 2.0,
"fat_g": 14.7,
"carbs_g": 8.5,
"fiber_g": 6.7,
"sugar_g": 0.7,
"sodium_mg": 7,
"calcium_mg": 12,
"iron_mg": 0.6,
"potassium_mg": 485,
"vitamin_c_mg": 10,
"saturated_fat_g": 2.1,
"cholesterol_mg": 0
}
```
---
## Integration Plan (Proposed)
### Phase 1: Exercise Library
1. Add `ExerciseLibrary` model to Diligence (new table)
2. Migration script to load unified-exercise-library.json
3. New MCP tool: `search_exercises(query, body_part?, equipment?, level?)`
4. Frontend: exercise browser with category/equipment filters
5. Link exercises to activity logging (select from library, not free-text)
### Phase 2: Food Library
1. Add `FoodLibrary` model (or extend existing FoodLog with lookup)
2. Migration to load unified-food-library.json
3. Lifestyle pattern browsing: "Show me Mediterranean foods"
4. New MCP tool: `browse_foods(pattern?, category?)`
5. Frontend: lifestyle pattern explorer (not calorie counter)
### Phase 3: Lifestyle Patterns
1. Curated pattern guides (from crawled content + search data)
2. "What's your eating style?" onboarding question
3. Pattern-aware meal suggestions
4. Seasonal food recommendations
5. Multi-language support (exercise instructions already in 10 languages)
---
## Files on disk
```
/home/claude/diligence-content/
├── INVENTORY.md ← this file
├── exercises/
│ ├── exercises-dataset.json ← raw hasaneyldrm (17MB)
│ ├── exercises-schema.json ← schema
│ ├── free-exercise-db/ ← raw yuhonas (873 files)
│ ├── unified-exercise-library.json ← MERGED (2,079 exercises)
│ ├── exercise-index.json ← lookup index
│ ├── analyze.py ← analysis script
│ └── merge.py ← merge script
├── food/
│ ├── usda-foundation/ ← USDA Foundation (363 foods)
│ ├── usda-sr-legacy/ ← USDA SR Legacy (7,793 foods)
│ ├── unified-food-library.json ← MERGED (8,068 foods)
│ ├── food-index.json ← lookup index
│ ├── build-food-library.py ← build script
│ └── crawled/ ← lifestyle content (18 files)
```

43784
data/seed/exercise-index.json Normal file

File diff suppressed because it is too large Load diff

265219
data/seed/food-index.json Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -218,6 +218,24 @@ async def run_migrations():
"ALTER TABLE users ADD COLUMN is_admin BOOLEAN DEFAULT FALSE"
))
# v4.2: Add timezone to users
if "users" in tables and "timezone" not in columns.get("users", []):
await conn.execute(text(
"ALTER TABLE users ADD COLUMN timezone VARCHAR(50) DEFAULT 'UTC'"
))
# v4.3: Add diet_style and timezone_str to nutrition_goals
if "nutrition_goals" in tables:
ng_cols = columns.get("nutrition_goals", [])
if "diet_style" not in ng_cols:
await conn.execute(text(
"ALTER TABLE nutrition_goals ADD COLUMN diet_style VARCHAR(30) DEFAULT 'strict_keto'"
))
if "timezone_str" not in ng_cols:
await conn.execute(text(
"ALTER TABLE nutrition_goals ADD COLUMN timezone_str VARCHAR(50) DEFAULT 'UTC'"
))
# v4.1: Grant admin to first registered user if none exists
if "users" in tables and "is_admin" in columns.get("users", []):
result = await conn.execute(text(

View file

@ -7,7 +7,7 @@ from __future__ import annotations
import json
import httpx
from mcp.server.fastmcp import FastMCP
from fastmcp import FastMCP
_client: httpx.AsyncClient | None = None

View file

@ -9,22 +9,29 @@ from datetime import date, datetime, timezone
from zoneinfo import ZoneInfo
def _safe_tz(tz_str: str = "UTC"):
"""Resolve a timezone string to a tzinfo, falling back to UTC.
Uses datetime.timezone.utc as the ultimate fallback in case
tzdata is not installed (common on Windows).
"""
try:
return ZoneInfo(tz_str)
except Exception:
try:
return ZoneInfo("UTC")
except Exception:
return timezone.utc
def today_for_user(tz_str: str = "UTC") -> date:
"""Return today's date in the user's timezone."""
try:
tz = ZoneInfo(tz_str)
except (KeyError, Exception):
tz = ZoneInfo("UTC")
return datetime.now(tz).date()
return datetime.now(_safe_tz(tz_str)).date()
def now_for_user(tz_str: str = "UTC") -> datetime:
"""Return the current datetime in the user's timezone (tz-aware)."""
try:
tz = ZoneInfo(tz_str)
except (KeyError, Exception):
tz = ZoneInfo("UTC")
return datetime.now(tz)
return datetime.now(_safe_tz(tz_str))
def day_start_utc(tz_str: str = "UTC") -> datetime:
@ -34,12 +41,9 @@ def day_start_utc(tz_str: str = "UTC") -> datetime:
to filter by the user's local day.
"""
user_today = today_for_user(tz_str)
try:
tz = ZoneInfo(tz_str)
except (KeyError, Exception):
tz = ZoneInfo("UTC")
tz = _safe_tz(tz_str)
local_midnight = datetime(user_today.year, user_today.month, user_today.day, tzinfo=tz)
return local_midnight.astimezone(ZoneInfo("UTC"))
return local_midnight.astimezone(timezone.utc)
def get_week_boundaries(d: date | None = None, tz_str: str = "UTC") -> tuple[date, date]:

104
docs/GIORDANO-FIX.md Normal file
View file

@ -0,0 +1,104 @@
# Giordano Desktop Fix — Next Session
**Date:** 2026-08-03
**Machine:** Windows, AMD Ryzen 3 2200G, 8GB RAM, user `giord`, Python 3.14
**Issue:** Claude Desktop MCP connector fails — wrong MCP package version installed
## Prerequisites
- Diligence app folder at `C:\Users\giord\Downloads\Diligence-main`
- Claude Desktop installed (Microsoft Store version)
- Node.js installed
- `mcp_stdio.py` already in the Diligence-main folder
- Claude Desktop config already set at both paths:
- `%APPDATA%\Claude\claude_desktop_config.json`
- `%LOCALAPPDATA%\Packages\Claude_pzs8sxrjxfjjc\LocalCache\Roaming\Claude\claude_desktop_config.json`
## Step 1 — Clean up old MCP packages
```powershell
cd "$env:USERPROFILE\Downloads\Diligence-main"
pip uninstall mcp mcp-cli fastmcp -y
```
## Step 2 — Fix the import in server.py
The old code imports from the wrong package. Run this once:
```powershell
(Get-Content diligence\mcp\server.py) -replace 'from mcp\.server\.fastmcp import FastMCP', 'from fastmcp import FastMCP' | Set-Content diligence\mcp\server.py
```
## Step 3 — Install the correct packages
```powershell
pip install "fastmcp>=3.0.0"
pip install tzdata
```
## Step 4 — Test the MCP stdio script
```powershell
python mcp_stdio.py
```
- **If it hangs with no output** → success. Ctrl+C to stop.
- **If it throws an error** → paste the traceback.
## Step 5 — Start Diligence
```powershell
python -m diligence
```
Confirm **both** lines appear:
- `Diligence running at http://localhost:8000`
- `MCP: http://localhost:3001/sse`
## Step 6 — Restart Claude Desktop
```powershell
Get-Process *claude* | Stop-Process -Force
```
Reopen Claude Desktop from the Start menu. Look for a tools/hammer icon indicating MCP connected.
## Step 7 — Test
In Claude Desktop, type:
> What's my fitness status today?
Claude should call the `get_context` tool and return fitness data.
Also test a write operation:
> Log a 30 minute workout called Morning Run
---
## Fallback: Built-in AI Coach (no Claude Desktop needed)
If Claude Desktop MCP continues to have issues, use the built-in coach:
1. Go to `http://localhost:8000/agent` in the browser
2. Under "Option 1 — Built-in AI Coach", click **Get key** next to **OpenRouter**
3. Sign up with Google (free, 26 free models available)
4. Copy the API key
5. In Diligence, go to **Settings > Integrations > AI Coaching**
6. Paste the key and select a model
7. Use the **Coach** tab in the bottom nav
This runs entirely inside the app — no external tools needed.
---
## Known Issues on This Machine
| Issue | Fix | Status |
|-------|-----|--------|
| tzdata not in pip dependencies | pip install tzdata manually | Pending GitHub push |
| mcp v2.0.0 removed FastMCP import | Switch to standalone fastmcp package | Fixed in subo repo, pending GitHub |
| GitHub push token expired | Need new PAT with repo scope | Not yet done |
| Migration warning: NOT NULL on point_rules.description | Non-fatal, cosmetic | Low priority |
| PowerShell QuickEdit mode pauses the app | Right-click title bar, Properties, uncheck QuickEdit | Told user |

469
docs/INSTALL-LINUX.md Normal file
View file

@ -0,0 +1,469 @@
# Diligence Fitness — Linux Installation Guide
Complete installation from a clean Linux machine with no dependencies.
Tested on Ubuntu 22.04+, Debian 12+. Most steps work on any distro with
Python 3.10+ and pip.
---
## 1. Install Python and pip
Most Linux distributions include Python 3. Verify:
```bash
python3 --version
pip3 --version
```
If pip is missing:
```bash
# Debian/Ubuntu
sudo apt update && sudo apt install python3-pip python3-venv unzip curl
# Fedora
sudo dnf install python3-pip python3 unzip curl
# Arch
sudo pacman -S python-pip python unzip curl
```
---
## 2. Install Node.js
Required for Gemini CLI. Skip if you only plan to use the built-in AI Coach
(see Section 7d).
```bash
# Debian/Ubuntu — simplest (Ubuntu 26.04 includes Node 22)
sudo apt install -y nodejs npm
# Or via NodeSource for a specific version
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install -y nodejs
# Fedora
sudo dnf install nodejs
# Arch
sudo pacman -S nodejs npm
# Or via nvm (any distro)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
source ~/.bashrc
nvm install --lts
```
Verify:
```bash
node --version
npm --version
```
---
## 3. Download Diligence
```bash
cd ~/Downloads
curl -L -o Diligence.zip https://github.com/DiligenceWorks/Diligence/archive/refs/heads/main.zip
unzip Diligence.zip
cd Diligence-main
```
Or with git (if installed):
```bash
cd ~/Downloads
git clone https://github.com/DiligenceWorks/Diligence.git Diligence-main
cd Diligence-main
```
---
## 4. Install Diligence and dependencies
**Option A — System-wide (simpler):**
```bash
cd ~/Downloads/Diligence-main
pip3 install ".[mcp]" --break-system-packages
```
The `--break-system-packages` flag is required on Ubuntu 23.04+ and Debian 12+
due to PEP 668 (externally managed environments). It is safe for user-level
installs.
**Option B — Virtual environment (cleaner):**
```bash
cd ~/Downloads/Diligence-main
python3 -m venv .venv
source .venv/bin/activate
pip install ".[mcp]"
```
If using a venv, you must activate it (`source .venv/bin/activate`) each time
before running Diligence.
**Note:** Unlike Windows, Linux does not need the `tzdata` pip package. The
system timezone database at `/usr/share/zoneinfo/` is used automatically.
---
## 5. Start Diligence
```bash
cd ~/Downloads/Diligence-main
python3 -m diligence
```
You should see:
```
Diligence running at http://localhost:8000
Data: /home/USERNAME/.diligence
MCP: http://localhost:3001/sse
Press Ctrl+C to stop
```
Open `http://localhost:8000` in your browser. Create an account on the
registration page.
To run in the background:
```bash
nohup python3 -m diligence > diligence.log 2>&1 &
```
---
## 6. Prepare the MCP stdio launcher
Some AI agents (Claude Desktop) require stdio transport. Create the launcher:
```bash
cat > ~/Downloads/Diligence-main/mcp_stdio.py << 'EOF'
from diligence.mcp.server import create_mcp_server
mcp = create_mcp_server(api_url="http://localhost:8000")
mcp.run(transport="stdio")
EOF
```
Test it (Diligence must be running in another terminal):
```bash
cd ~/Downloads/Diligence-main
python3 mcp_stdio.py
```
If it hangs with no output, that is success (stdio waiting for input). Ctrl+C to stop.
---
## 7. Connect an AI Agent
Choose one or more of the following options. All are free.
---
### 7a. Gemini CLI (recommended free option)
**What:** Google's terminal AI agent. 1,000 free requests/day with Google sign-in.
Supports stdio and SSE MCP directly — no bridge needed.
**Requires:** Node.js (Step 2)
**Install:**
```bash
npm install -g @google/gemini-cli
```
**First run — authenticate with Google:**
```bash
gemini
```
Follow the browser prompt to sign in with your Google account. One-time setup.
**Configure MCP:**
Gemini CLI supports SSE directly, so you can point it straight at the running
MCP server — no stdio script needed:
```bash
mkdir -p ~/.gemini
cat > ~/.gemini/settings.json << 'EOF'
{
"mcpServers": {
"diligence": {
"url": "http://localhost:3001/sse"
}
}
}
EOF
```
If your Diligence instance has API token auth enabled (check the Agent page at
`http://localhost:8000/agent`), add headers to the config:
```json
{
"mcpServers": {
"diligence": {
"url": "http://localhost:3001/sse",
"headers": {
"Authorization": "Bearer YOUR_TOKEN_FROM_AGENT_PAGE"
}
}
}
}
```
Alternatively, use the stdio launcher (no token needed — it connects locally):
```json
{
"mcpServers": {
"diligence": {
"command": "python3",
"args": ["mcp_stdio.py"],
"cwd": "/home/USERNAME/Downloads/Diligence-main"
}
}
}
```
Replace `USERNAME` with your actual Linux username (run `whoami` to check).
**Use:**
1. Start Diligence in one terminal (`python3 -m diligence`)
2. Open a second terminal and run `gemini`
3. Type: "What's my fitness status today?"
Gemini CLI will discover the Diligence MCP tools and use them to answer.
---
### 7b. Claude Desktop (free, Debian/Ubuntu only — beta)
**What:** Anthropic's desktop app. Free with a free Claude account.
Official Linux beta released July 9, 2026. Debian/Ubuntu only.
**Requires:** Ubuntu 22.04+ or Debian 12+, free Claude account
**Install:**
```bash
sudo curl -fsSLo /usr/share/keyrings/claude-desktop-archive-keyring.asc \
https://downloads.claude.ai/claude-desktop/key.asc
echo "deb [signed-by=/usr/share/keyrings/claude-desktop-archive-keyring.asc] \
https://downloads.claude.ai/claude-desktop/apt/stable stable main" \
| sudo tee /etc/apt/sources.list.d/claude-desktop.list
sudo apt update && sudo apt install claude-desktop
```
For Fedora, Arch, or other distros, see the community package at
[github.com/aaddrick/claude-desktop-debian](https://github.com/aaddrick/claude-desktop-debian).
**Configure MCP:**
```bash
mkdir -p ~/.config/Claude
cat > ~/.config/Claude/claude_desktop_config.json << 'EOF'
{
"mcpServers": {
"diligence": {
"command": "python3",
"args": ["mcp_stdio.py"],
"cwd": "/home/USERNAME/Downloads/Diligence-main"
}
}
}
EOF
```
Replace `USERNAME` with your actual Linux username (run `whoami` to check).
If using a virtual environment, use the full path to the venv Python:
```json
{
"mcpServers": {
"diligence": {
"command": "/home/USERNAME/Downloads/Diligence-main/.venv/bin/python",
"args": ["mcp_stdio.py"],
"cwd": "/home/USERNAME/Downloads/Diligence-main"
}
}
}
```
**Use:**
1. Start Diligence in a terminal (`python3 -m diligence`)
2. Quit and reopen Claude Desktop
3. Look for a tools/hammer icon indicating MCP is connected
4. Type: "What's my fitness status today?"
---
### 7c. ChatGPT Desktop (not available on Linux)
OpenAI has not released an official ChatGPT Desktop app for Linux as of
August 2026. A sign-up page exists for future availability. Community wrappers
(lencx/ChatGPT, Snap packages) do not support MCP.
If you have a ChatGPT paid plan, you can use the **Codex CLI** instead:
```bash
npm install -g @openai/codex
```
Codex CLI shares MCP configuration and supports stdio servers. Requires a
ChatGPT Plus, Pro, or Team plan.
---
### 7d. Built-in AI Coach (simplest — no extra apps needed)
**What:** AI coaching chat built directly into the Diligence web app. No external
tools, no config files, no MCP setup. Just needs a free API key.
**Free API key providers:**
| Provider | Free tier | Get key |
|----------|-----------|---------|
| OpenRouter | 26 free models | [openrouter.ai/keys](https://openrouter.ai/keys) |
| Groq | Fast Llama inference | [console.groq.com/keys](https://console.groq.com/keys) |
| Google AI Studio | Gemini Flash/Pro | [aistudio.google.com/apikey](https://aistudio.google.com/apikey) |
| Hugging Face | Thousands of models | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
| Ollama | Run LLMs locally, no key needed | [ollama.com](https://ollama.com/) |
**Setup:**
1. Sign up at one of the providers above and copy your API key
2. In the Diligence browser app, go to **Settings > Integrations > AI Coaching**
3. Paste your API key and select a model
4. Use the **Coach** tab in the bottom navigation
**Ollama (fully offline):**
If you want AI coaching without any internet dependency:
```bash
curl -fsSL https://ollama.com/install.sh | sh
ollama pull llama3.1
```
Then configure Diligence AI Coaching to point at `http://localhost:11434`.
No API key needed.
---
## Daily Usage
Each time you want to use Diligence:
```bash
cd ~/Downloads/Diligence-main
python3 -m diligence
```
If using a venv:
```bash
cd ~/Downloads/Diligence-main
source .venv/bin/activate
python3 -m diligence
```
Open `http://localhost:8000` in your browser. The app runs until you press Ctrl+C.
If using an external AI agent (Gemini CLI, Claude Desktop), make sure Diligence
is running first, then open the agent.
---
## Optional: Run as a systemd service
To start Diligence automatically on boot:
```bash
sudo tee /etc/systemd/system/diligence.service << EOF
[Unit]
Description=Diligence Fitness
After=network.target
[Service]
Type=simple
User=$USER
WorkingDirectory=$HOME/Downloads/Diligence-main
ExecStart=$(which python3) -m diligence
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now diligence
```
If using a virtual environment, change `ExecStart` to:
```
ExecStart=/home/USERNAME/Downloads/Diligence-main/.venv/bin/python -m diligence
```
Check status:
```bash
sudo systemctl status diligence
journalctl -u diligence -f
```
---
## Updating
```bash
cd ~/Downloads
rm -rf Diligence-main
curl -L -o Diligence.zip https://github.com/DiligenceWorks/Diligence/archive/refs/heads/main.zip
unzip Diligence.zip
cd Diligence-main
pip3 install ".[mcp]" --break-system-packages
```
Or with git:
```bash
cd ~/Downloads/Diligence-main
git pull origin main
pip3 install ".[mcp]" --break-system-packages
```
Your data is stored in `~/.diligence/` and is preserved across updates.
---
## Troubleshooting
| Symptom | Cause | Fix |
|---------|-------|-----|
| "No module named diligence" | Wrong directory or venv not active | `cd ~/Downloads/Diligence-main` and `source .venv/bin/activate` if using venv |
| "No module named uvicorn" | Dependencies not installed | `pip3 install ".[mcp]" --break-system-packages` |
| "No module named mcp.server.fastmcp" | Wrong MCP SDK version | `pip3 uninstall mcp -y && pip3 install "fastmcp>=3.0.0" --break-system-packages` |
| "externally-managed-environment" | PEP 668 on Ubuntu 23.04+ | Add `--break-system-packages` or use a venv |
| MCP line shows "not available" | Missing MCP extras | `pip3 install ".[mcp]" --break-system-packages` |
| Claude Desktop MCP not loading | Wrong config path | Check `~/.config/Claude/claude_desktop_config.json` exists |
| Gemini CLI "no tools found" | Settings path wrong | Check `~/.gemini/settings.json` has correct `cwd` path |
| Port 8000 already in use | Another service on that port | `python3 -m diligence --port 8080` or stop the conflicting service |

353
docs/INSTALL-WINDOWS.md Normal file
View file

@ -0,0 +1,353 @@
# Diligence Fitness — Windows Installation Guide
Complete installation from a clean Windows machine with no dependencies.
---
## 1. Install Python
Download Python from [python.org/downloads](https://www.python.org/downloads/).
Use the latest **3.12** or **3.13** release (3.14 works but is bleeding edge).
**During installation, check "Add Python to PATH"** — this is critical.
Verify in a new PowerShell window:
```powershell
python --version
```
Should show `Python 3.12.x` or similar.
---
## 2. Install Node.js
Required for Gemini CLI and Claude Desktop MCP bridge. Download the LTS version
from [nodejs.org](https://nodejs.org). Run the installer with defaults.
Verify in a **new** PowerShell window:
```powershell
node --version
```
Skip this step if you only plan to use the built-in AI Coach (see Section 7d).
---
## 3. Download Diligence
Since Git is not required, download as a ZIP:
```powershell
cd "$env:USERPROFILE\Downloads"
Invoke-WebRequest -Uri "https://github.com/DiligenceWorks/Diligence/archive/refs/heads/main.zip" -OutFile Diligence.zip
Expand-Archive Diligence.zip -DestinationPath .
cd Diligence-main
```
---
## 4. Install Diligence and dependencies
Install the app with MCP support and Windows timezone data:
```powershell
cd "$env:USERPROFILE\Downloads\Diligence-main"
pip install ".[mcp]"
pip install tzdata
```
**Note:** The `tzdata` package is required on Windows because Python's `zoneinfo`
module has no system timezone database. Without it, the Home and Keto pages will
show "failed to load."
The `.[mcp]` extra installs the MCP server for AI agent integration. If you
only want the web app without AI features, use `pip install .` instead.
---
## 5. Start Diligence
```powershell
cd "$env:USERPROFILE\Downloads\Diligence-main"
python -m diligence
```
You should see:
```
Diligence running at http://localhost:8000
Data: C:\Users\USERNAME\.diligence
MCP: http://localhost:3001/sse
Press Ctrl+C to stop
```
Open `http://localhost:8000` in your browser. Create an account on the registration page.
**Important:** Do not click inside the PowerShell terminal window while the app is
running. Windows QuickEdit mode will pause the process. To prevent this permanently:
right-click the PowerShell title bar, select Properties, uncheck "QuickEdit Mode."
---
## 6. Prepare the MCP stdio launcher
Some AI agents (Claude Desktop, ChatGPT Desktop) require stdio transport. Create the
launcher script in your Diligence-main folder:
```powershell
Set-Content "$env:USERPROFILE\Downloads\Diligence-main\mcp_stdio.py" @'
from diligence.mcp.server import create_mcp_server
mcp = create_mcp_server(api_url="http://localhost:8000")
mcp.run(transport="stdio")
'@
```
Test it (Diligence must be running in another terminal):
```powershell
cd "$env:USERPROFILE\Downloads\Diligence-main"
python mcp_stdio.py
```
If it hangs with no output, that means success (stdio is waiting for input). Press Ctrl+C to stop.
---
## 7. Connect an AI Agent
Choose one or more of the following options. All are free.
---
### 7a. Gemini CLI (recommended free option)
**What:** Google's terminal AI agent. 1,000 free requests/day with Google sign-in.
Supports stdio and SSE MCP directly — no bridge needed.
**Requires:** Node.js (Step 2)
**Install:**
```powershell
npm install -g @google/gemini-cli
```
**First run — authenticate with Google:**
```powershell
gemini
```
Follow the browser prompt to sign in with your Google account. This is a one-time setup.
**Configure MCP:**
Create or edit the settings file:
```powershell
mkdir "$env:USERPROFILE\.gemini" -ErrorAction SilentlyContinue
$dp = ("$env:USERPROFILE\Downloads\Diligence-main") -replace '\\','\\\\'
@"
{
"mcpServers": {
"diligence": {
"command": "python",
"args": ["mcp_stdio.py"],
"cwd": "$dp"
}
}
}
"@ | Set-Content "$env:USERPROFILE\.gemini\settings.json"
```
**Alternatively**, Gemini CLI supports SSE directly (unlike Claude Desktop), so you
can point it at the running MCP server without the stdio script. If your Diligence
instance has API token auth enabled (check `http://localhost:8000/agent`), include
the token in headers. Open the settings file in Notepad and paste:
```json
{
"mcpServers": {
"diligence": {
"url": "http://localhost:3001/sse",
"headers": {
"Authorization": "Bearer YOUR_TOKEN_FROM_AGENT_PAGE"
}
}
}
}
```
Omit the `headers` block if no token is shown on the Agent page.
**Use:**
1. Start Diligence in one terminal (`python -m diligence`)
2. Open a second terminal and run `gemini`
3. Type: "What's my fitness status today?"
Gemini CLI will discover the Diligence MCP tools and use them to answer.
---
### 7b. Claude Desktop (free, MCP via stdio)
**What:** Anthropic's desktop chat app. Free with a free Claude account.
Only supports stdio MCP via config file (not SSE).
**Requires:** Node.js (Step 2), free Claude account at [claude.ai](https://claude.ai)
**Install:** Download from [claude.ai/download](https://claude.ai/download) or
install from the Microsoft Store. Sign in with your free Claude account.
**Configure MCP:**
Claude Desktop reads its config from different paths depending on install method.
Set both to be safe:
Generate and save the config (this auto-resolves your Downloads path):
```powershell
$dp = ("$env:USERPROFILE\Downloads\Diligence-main") -replace '\\','\\\\'
$json = @"
{
"mcpServers": {
"diligence": {
"command": "python",
"args": ["mcp_stdio.py"],
"cwd": "$dp"
}
}
}
"@
# Standard install path
mkdir "$env:APPDATA\Claude" -ErrorAction SilentlyContinue
$json | Set-Content "$env:APPDATA\Claude\claude_desktop_config.json"
# Microsoft Store install path (set both to be safe)
$storePath = "$env:LOCALAPPDATA\Packages\Claude_pzs8sxrjxfjjc\LocalCache\Roaming\Claude"
if (Test-Path $storePath) { $json | Set-Content "$storePath\claude_desktop_config.json" }
```
**Important:** Do NOT use the "Add custom connector" button in Claude Desktop's UI.
That is for remote MCP servers and may have plan restrictions. The config file
approach above is for local MCP and works on the free plan.
**Use:**
1. Start Diligence in one terminal (`python -m diligence`)
2. Quit Claude Desktop fully (right-click system tray icon > Quit)
3. Reopen Claude Desktop
4. Look for a tools/hammer icon indicating MCP is connected
5. Type: "What's my fitness status today?"
---
### 7c. ChatGPT Desktop (paid plans only)
**What:** OpenAI's desktop app. Supports local stdio MCP servers via config file.
**Requires:** ChatGPT Plus, Pro, or Team plan (not free). Developer Mode enabled.
**Install:** Download from [openai.com/chatgpt/desktop](https://openai.com/chatgpt/desktop).
**Configure MCP:**
MCP configuration is shared between ChatGPT Desktop and OpenAI Codex CLI.
The config file location may vary by version — check OpenAI's documentation
for the current path. As of mid-2026, it is typically at
`%APPDATA%\ChatGPT\chatgpt_config.json`. Use the same JSON format as
Claude Desktop (Section 7b) with your Diligence path.
**Enable Developer Mode:** Settings > Developer Mode > ON
**Use:**
1. Start Diligence in one terminal
2. Restart ChatGPT Desktop
3. Type: "What's my fitness status today?"
---
### 7d. Built-in AI Coach (simplest — no extra apps needed)
**What:** AI coaching chat built directly into the Diligence web app. No external
tools, no config files, no MCP setup. Just needs a free API key.
**Free API key providers:**
| Provider | Free tier | Get key |
|----------|-----------|---------|
| OpenRouter | 26 free models | [openrouter.ai/keys](https://openrouter.ai/keys) |
| Groq | Fast Llama inference | [console.groq.com/keys](https://console.groq.com/keys) |
| Google AI Studio | Gemini Flash/Pro | [aistudio.google.com/apikey](https://aistudio.google.com/apikey) |
| Hugging Face | Thousands of models | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
| Ollama | Run LLMs locally, no key needed | [ollama.com](https://ollama.com/) |
**Setup:**
1. Sign up at one of the providers above and copy your API key
2. In the Diligence browser app, go to **Settings > Integrations > AI Coaching**
3. Paste your API key and select a model
4. Use the **Coach** tab in the bottom navigation
**Ollama (fully offline):**
If you want AI coaching without any internet dependency, install Ollama from
[ollama.com](https://ollama.com/), pull a model (`ollama pull llama3.1`), and
configure the Diligence AI Coaching integration to point at `http://localhost:11434`.
No API key needed.
---
## Daily Usage
Each time you want to use Diligence:
```powershell
cd "$env:USERPROFILE\Downloads\Diligence-main"
python -m diligence
```
Open `http://localhost:8000` in your browser. The app runs until you press Ctrl+C.
If using an external AI agent (Gemini CLI, Claude Desktop, ChatGPT Desktop),
make sure Diligence is running first, then open the agent.
---
## Updating
To get the latest version:
```powershell
cd "$env:USERPROFILE\Downloads"
Remove-Item -Recurse -Force Diligence-main
Invoke-WebRequest -Uri "https://github.com/DiligenceWorks/Diligence/archive/refs/heads/main.zip" -OutFile Diligence.zip
Expand-Archive Diligence.zip -DestinationPath . -Force
cd Diligence-main
pip install ".[mcp]"
pip install tzdata
```
Your data is stored in `~\.diligence\` and is preserved across updates.
---
## Troubleshooting
| Symptom | Cause | Fix |
|---------|-------|-----|
| Home/Keto pages "failed to load" | Missing tzdata | `pip install tzdata` |
| "No module named diligence" | Wrong directory | `cd "$env:USERPROFILE\Downloads\Diligence-main"` |
| "No module named uvicorn" | Dependencies not installed | `pip install ".[mcp]"` |
| "No module named mcp.server.fastmcp" | Wrong MCP SDK version | `pip uninstall mcp -y && pip install "fastmcp>=3.0.0"` |
| App stops when clicking terminal | PowerShell QuickEdit | Right-click title bar > Properties > uncheck QuickEdit |
| Claude Desktop "not valid config" | Config uses `url` not `command` | Use the stdio config (Section 7b) |
| Claude Desktop "Server disconnected" | MCP extras not installed | `pip install ".[mcp]"` and check for `MCP:` line |
| Gemini CLI "no tools found" | Settings path wrong | Check `~/.gemini/settings.json` has correct `cwd` path |
| MCP line shows "not available" | Missing MCP extras | `pip install ".[mcp]"` |

4
mcp_stdio.py Normal file
View file

@ -0,0 +1,4 @@
"""Launch Diligence MCP server in stdio mode for Claude Desktop."""
from diligence.mcp.server import create_mcp_server
mcp = create_mcp_server(api_url="http://localhost:8000")
mcp.run(transport="stdio")

82
portable/README.txt Normal file
View file

@ -0,0 +1,82 @@
DILIGENCE
Self-hosted fitness rewards platform
=====================================
QUICK START (Windows)
---------------------
1. Extract this entire folder to your Desktop or Documents
2. Double-click start.bat
3. Your browser opens to http://localhost:8000
4. Create your account on first visit
That's it. No installation needed.
YOUR DATA
---------
Everything is stored in the "data" folder right here:
- data/data.db — your database (workouts, points, rewards)
- data/.env — your configuration (auto-generated)
Your data never leaves your computer.
To back up, just copy the "data" folder somewhere safe.
To move to another computer, copy this entire Diligence folder.
STOPPING
--------
Press Ctrl+C in the black command window, or just close it.
AI AGENT CONNECTION (Optional)
------------------------------
Diligence includes an MCP connector for AI agents like Claude Desktop.
After starting, the MCP endpoint is at:
URL: http://localhost:3001/sse
Token: (see data/.env, the API_TOKEN line)
Claude Desktop config (claude_desktop_config.json):
{
"mcpServers": {
"diligence": {
"url": "http://localhost:3001/sse",
"headers": {
"Authorization": "Bearer YOUR_API_TOKEN_HERE"
}
}
}
}
SYSTEM REQUIREMENTS
-------------------
- Windows 10 or later (64-bit)
- 150 MB disk space
- 300 MB free RAM
- Any web browser (Edge, Chrome, Firefox)
- No admin rights needed
- No internet needed (except for Strava/Polar sync)
TROUBLESHOOTING
---------------
"Windows protected your PC" (SmartScreen):
Click "More info" then "Run anyway". This appears because the
app is not digitally signed, not because it is harmful.
"Port already in use":
Another program is using port 8000. Close it, or run:
start.bat --port 9000
The window closes immediately:
Open a Command Prompt, navigate to this folder, and type:
start.bat
to see the error message.
LICENSE
-------
MIT License — DiligenceWorks Pte. Ltd.
https://github.com/DiligenceWorks/Diligence

201
portable/build.sh Executable file
View file

@ -0,0 +1,201 @@
#!/bin/bash
# =============================================================================
# Diligence Portable Build Script
# Assembles a zero-install portable distribution for Windows 10 x64
#
# Run this on a Linux build host (subo). It downloads the Windows embeddable
# Python, cross-downloads Windows wheels, and packages everything into a zip
# that the end user extracts and double-clicks start.bat.
#
# Usage: ./build.sh [PYTHON_VERSION]
# Output: dist/Diligence-portable-win64.zip
# =============================================================================
set -euo pipefail
# --- Configuration -----------------------------------------------------------
PYTHON_VERSION="${1:-3.12.10}"
PYTHON_MAJOR_MINOR=$(echo "$PYTHON_VERSION" | cut -d. -f1,2)
PYTHON_TAG=$(echo "$PYTHON_MAJOR_MINOR" | tr -d '.')
APP_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BUILD_DIR="$APP_ROOT/portable/build"
DIST_DIR="$APP_ROOT/portable/dist"
STAGE="$BUILD_DIR/Diligence"
WHEELS_DIR="$BUILD_DIR/wheels"
PYTHON_EMBED_URL="https://www.python.org/ftp/python/${PYTHON_VERSION}/python-${PYTHON_VERSION}-embed-amd64.zip"
OUTPUT_ZIP="$DIST_DIR/Diligence-portable-win64.zip"
echo ""
echo " Diligence Portable Build"
echo " Python: ${PYTHON_VERSION} (embed amd64)"
echo " App root: ${APP_ROOT}"
echo ""
# --- Clean -------------------------------------------------------------------
rm -rf "$BUILD_DIR" "$DIST_DIR"
mkdir -p "$STAGE" "$WHEELS_DIR" "$DIST_DIR"
# --- Step 1: Download embeddable Python --------------------------------------
echo " [1/6] Downloading embeddable Python ${PYTHON_VERSION}..."
curl -sL -o "$BUILD_DIR/python-embed.zip" "$PYTHON_EMBED_URL"
mkdir -p "$STAGE/python"
unzip -q "$BUILD_DIR/python-embed.zip" -d "$STAGE/python"
rm "$BUILD_DIR/python-embed.zip"
# --- Step 2: Configure Python import paths -----------------------------------
echo " [2/6] Configuring Python import paths..."
# The ._pth file controls sys.path for the embeddable Python.
# Paths are relative to the python/ directory.
cat > "$STAGE/python/python${PYTHON_TAG}._pth" << EOF
python${PYTHON_TAG}.zip
.
..
../lib
import site
EOF
# --- Step 3: Download Windows wheels -----------------------------------------
echo " [3/6] Downloading Windows wheels..."
# We download binary wheels for Windows from PyPI using the Linux pip.
# --platform win_amd64 fetches Windows-specific binaries.
# --no-deps because we manage the dependency list explicitly to avoid
# pulling in unnecessary transitive deps.
# Core dependencies (from pyproject.toml)
CORE_DEPS=(
"fastapi>=0.115.0"
"uvicorn>=0.30.0"
"sqlalchemy>=2.0.30"
"aiosqlite>=0.20.0"
"pydantic>=2.10.0"
"pydantic-settings>=2.7.0"
"pydantic-core"
"python-jose>=3.3.0"
"cryptography"
"bcrypt>=4.2.0"
"httpx>=0.27.0"
"python-multipart>=0.0.18"
"tzdata>=2024.1"
)
# Transitive dependencies (required by core deps)
TRANSITIVE_DEPS=(
"annotated-types"
"typing-extensions"
"anyio"
"sniffio"
"idna"
"certifi"
"httpcore"
"h11"
"starlette"
"click"
"jinja2"
"markupsafe"
"ecdsa"
"rsa"
"pyasn1"
"cffi"
"pycparser"
"greenlet"
"python-dotenv"
)
download_wheel() {
local pkg="$1"
# Try platform-specific binary first
pip download \
--platform win_amd64 \
--python-version "$PYTHON_MAJOR_MINOR" \
--only-binary :all: \
--dest "$WHEELS_DIR" \
--no-deps \
"$pkg" 2>/dev/null && return 0
# Fall back to pure-python wheel (no platform restriction needed)
pip download \
--python-version "$PYTHON_MAJOR_MINOR" \
--dest "$WHEELS_DIR" \
--no-deps \
"$pkg" 2>/dev/null && return 0
echo " WARNING: Could not download $pkg"
return 1
}
for pkg in "${CORE_DEPS[@]}" "${TRANSITIVE_DEPS[@]}"; do
download_wheel "$pkg" || true
done
# MCP connector (optional — included if available)
download_wheel "fastmcp>=3.0.0" || echo " (fastmcp unavailable — MCP will be optional)"
# --- Step 4: Extract wheels into lib/ ----------------------------------------
echo " [4/6] Extracting wheels into lib/..."
mkdir -p "$STAGE/lib"
for whl in "$WHEELS_DIR"/*.whl; do
[ -f "$whl" ] || continue
unzip -qo "$whl" -d "$STAGE/lib"
done
# Clean .dist-info (saves space, not needed at runtime)
find "$STAGE/lib" -type d -name "*.dist-info" -exec rm -rf {} + 2>/dev/null || true
# Remove any .tar.gz source dists that snuck in
rm -f "$WHEELS_DIR"/*.tar.gz 2>/dev/null || true
# --- Step 5: Copy application code ------------------------------------------
echo " [5/6] Copying application code..."
# Copy the diligence package (includes pre-built frontend at diligence/frontend/)
cp -r "$APP_ROOT/diligence" "$STAGE/diligence"
# Remove __pycache__
find "$STAGE/diligence" -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
# Copy supporting files
cp "$APP_ROOT/LICENSE" "$STAGE/"
# Create data directory placeholder
mkdir -p "$STAGE/data"
# Copy launchers and README from portable/
cp "$APP_ROOT/portable/start.bat" "$STAGE/"
cp "$APP_ROOT/portable/start.sh" "$STAGE/"
cp "$APP_ROOT/portable/README.txt" "$STAGE/"
# --- Step 6: Package --------------------------------------------------------
echo " [6/6] Creating zip..."
# Use system zip if available, otherwise use Docker Alpine
if command -v zip &>/dev/null; then
cd "$BUILD_DIR"
zip -qr "$OUTPUT_ZIP" Diligence/
cd "$APP_ROOT"
else
echo " (zip not installed — using Docker Alpine)"
sg docker -c "docker run --rm \
-v '$BUILD_DIR':/build \
-v '$DIST_DIR':/dist \
-w /build \
alpine sh -c 'apk add --no-cache -q zip && zip -qr /dist/Diligence-portable-win64.zip Diligence/'"
fi
# --- Report ------------------------------------------------------------------
ZIP_SIZE=$(du -sh "$OUTPUT_ZIP" | cut -f1)
STAGE_SIZE=$(du -sh "$STAGE" | cut -f1)
echo ""
echo " Build complete:"
echo " Zip: $OUTPUT_ZIP ($ZIP_SIZE)"
echo " Extracted size: $STAGE_SIZE"
echo " Python: $PYTHON_VERSION (embed amd64)"
echo ""
echo " Test on Windows:"
echo " 1. Extract zip to any folder"
echo " 2. Double-click start.bat"
echo " 3. Browser opens to http://localhost:8000"
echo ""

36
portable/start.bat Normal file
View file

@ -0,0 +1,36 @@
@echo off
:: ============================================================================
:: Diligence — Self-hosted fitness rewards platform
:: Double-click this file to start. Your browser will open automatically.
:: Press Ctrl+C in this window to stop.
:: ============================================================================
title Diligence
:: Get the directory this script lives in
set "APP_DIR=%~dp0"
:: Data lives alongside the app (portable — no files outside this folder)
set "DATA_DIR=%APP_DIR%data"
:: Tell Python where to find the app and its dependencies
:: (The ._pth file handles most of this, but DATA_DIR needs an env var)
set "DATA_DIR=%DATA_DIR%"
echo.
echo Diligence
echo =========
echo.
echo Starting up... (this may take 10-30 seconds on first run)
echo Your browser will open automatically.
echo.
echo Data folder: %DATA_DIR%
echo Press Ctrl+C to stop.
echo.
:: Run the app using the bundled Python
"%APP_DIR%python\python.exe" -m diligence --data-dir "%DATA_DIR%" %*
:: If we get here, the app exited
echo.
echo Diligence has stopped.
pause

36
portable/start.sh Executable file
View file

@ -0,0 +1,36 @@
#!/bin/bash
# ============================================================================
# Diligence — Self-hosted fitness rewards platform (Mac/Linux)
#
# This launcher is for systems that already have Python 3.11+ installed.
# It uses the bundled dependencies from lib/ but your system Python.
#
# Usage: ./start.sh
# ============================================================================
APP_DIR="$(cd "$(dirname "$0")" && pwd)"
DATA_DIR="$APP_DIR/data"
export PYTHONPATH="$APP_DIR/lib:$APP_DIR:$PYTHONPATH"
echo ""
echo " Diligence"
echo " ========="
echo ""
echo " Starting up..."
echo " Data folder: $DATA_DIR"
echo " Press Ctrl+C to stop."
echo ""
# Try bundled python first, then system python3
if [ -x "$APP_DIR/python/python3" ]; then
"$APP_DIR/python/python3" -m diligence --data-dir "$DATA_DIR" "$@"
elif command -v python3 &>/dev/null; then
python3 -m diligence --data-dir "$DATA_DIR" "$@"
else
echo " ERROR: Python 3 not found."
echo " Install Python 3.11+ or use the pip install path:"
echo " pip install diligence"
echo " diligence"
exit 1
fi

View file

@ -34,6 +34,7 @@ dependencies = [
"bcrypt>=4.2.0",
"httpx>=0.27.0",
"python-multipart>=0.0.18",
"tzdata>=2024.1",
]
[project.optional-dependencies]
@ -41,7 +42,7 @@ postgres = [
"asyncpg>=0.30.0",
]
mcp = [
"mcp[cli]>=1.0.0",
"fastmcp>=3.0.0",
]
dev = [
"pytest>=8.0",