{
  "$type": "site.standard.document",
  "bskyPostRef": {
    "cid": "bafyreiegehlo66jb7giy2uvdbb35k6k24kbci32wshxngtkca54ryuzp74",
    "uri": "at://did:plc:7basvtgtkukzhs5nx64oqgvp/app.bsky.feed.post/3midenpmhxfs2"
  },
  "coverImage": {
    "$type": "blob",
    "ref": {
      "$link": "bafkreifgadbntarn5k34a22nc2lprrxpt7ckxzx6xzoi7y2aumn2feepfa"
    },
    "mimeType": "image/png",
    "size": 244392
  },
  "description": "In Part 1, you saw 82% → 98% time in range. But how does it work? This reveals the complete system: 5 components that transform raw sensor data into daily AI coaching. Dexcom API to Neo4j to Claude AI. Real examples, $20/month total. Part 2 of 5.",
  "path": "/ai-coach-part-2/",
  "publishedAt": "2026-03-31T04:46:17.000Z",
  "site": "https://blog.warrenweb.net",
  "tags": [
    "The Transformation",
    "System Architecture",
    "Prompt Engineering",
    "Knowledge Graph",
    "Build Your Own",
    "Teaching Your AI Coach to Cook",
    "Part 1",
    "B",
    "uild Your Own",
    "Day Cluster"
  ],
  "textContent": "* * *\n\n**🤖 _AI Diabetes Coach_ series:**\n— 🚀 Part 1: The Transformation\n➔ 🏗️ Part 2: System Architecture\n— 💭 Part 3: Prompt Engineering\n— 🕸️ Part 4: Knowledge Graph\n_—_ 🔧 Part 5: Build Your Own\n_—_ 🍴 __ Part 6: Teaching Your AI Coach to Cook\n\n* * *\n\nIn Part 1, you saw the transformation: 54% → 96% glucose time in range in 6 months, then 82% → 98% with AI integration. Five perfect 100% days in Week 13, and 45% reduction in daily insulin.\n\nBut how does it actually work? What makes the system run every day without manual intervention? Let me show you the architecture.\n\nThis isn't just theory—this is the actual system running in production. The same architecture that generated yesterday's Day Analysis, spotted my 5-day perfect streak, and provided actionable insights while I launched this series.\n\nBy the end of this post, you'll understand:\n\n  * How the data flows from sensors to insights\n  * Why automation is key (not just helpful)\n  * Which components you can build without coding\n  * What the technical stack actually looks like\n  * How to start building your own version\n\n\n\nThe system has 5 core components:\n\n  1. Calendar Service - Creates the daily note structure (13 files) and maintains temporal relationships in Neo4j\n  2. Health Service - Pulls glucose data from Dexcom API and insulin/meal data from Glooko automatically\n  3. Review Service - Sends 7 days of context to Claude AI and generates the daily analysis\n  4. Knowledge Graph - Connects everything in Neo4j (days, health events, patterns, insights)\n  5. Integration Layer - Python services that orchestrate the flow\n\n\n\nEach component can work standalone, but together they create something greater than the sum of parts: a system that remembers, learns, and coaches—automatically, every morning.\n\nLet's dive into each component...\n\n## Components Overview\n\nThe system has 5 interconnected components that work together to transform raw sensor data into actionable daily insights.\n\n**1. Calendar Service** — Creates the structure\n\n  * Generates 13 interconnected notes every morning at 7 AM\n  * Links them in Neo4j's temporal graph\n  * Provides consistent foundation for automation\n  * Example: Plan, Log, Health, Journal, Review\n\n\n\n**2. Health Service** — Collects the data\n\n  * Pulls 288 glucose readings (every 5 minutes) from Dexcom API\n  * Downloads insulin doses and carbs from Glooko\n  * Merges into comprehensive diabetes review\n  * All automated—no manual screenshot uploads\n\n\n\n**3. Review Service** — Generates the insights\n\n  * Takes health data plus 7 days of context\n  * Sends to Claude AI for pattern analysis\n  * Produces daily PMN (Plus-Minus-Next) coaching\n  * Spots patterns I would miss, and celebrates wins I would forget\n\n\n\n**4. Knowledge Graph** — Connects everything\n\n  * Stores relationships in Neo4j graph database\n  * Enables powerful temporal queries\n  * Reveals correlations: \"Show all days where exercise preceded a low within 12 hours\"\n  * Answers questions you didn't know to ask\n  * Reveals patterns across time\n\n\n\n**5. Integration Layer** — Orchestrates the flow\n\n  * Python services coordinate all components\n  * Handles errors gracefully (retry, fallback, queue)\n  * Runs automatically every morning\n  * Total automation time: ~2 minutes\n\n __The five components work together to transform raw sensor data__ __into actionable daily insights.__\n\nNow let's explore each component in detail...\n\n## Calendar Service: Day Cluster Generator\n\nThe foundation of everything is the Day cluster—13 interconnected notes created every morning.\n\n### Why 13 Files?\n\nMost people use a single daily note. I tried that. It becomes a dumping ground. By splitting into focused files, each has a clear purpose:\n\n  * Day Index - Navigation hub\n  * Day Plan - Intentions (what I plan to do)\n  * Day Log - Reality (what actually happened)\n  * Day Health - Medical tracking\n  * Day Diabetes - Automated analysis\n  * Day Schedule - Calendar + sessions\n  * Day Journal - Reflections\n  * Day Review - AI-generated synthesis\n  * Day Analysis - PMN framework insights\n\n\n\n... and 4 more specialized notes\n\nThe 13 interconnected notes created for March 28, 2026\n\n### The Neo4j Connection\n\nBut here's where it gets powerful: these aren't just files in a folder. They're nodes in a temporal graph.\n\nWhen the system creates 2026-03-28, it:\n\n  1. Creates 13 note nodes in Neo4j\n  2. Links them to 2026-W13 (week)\n  3. Links them to 2026-03 (month)\n  4. Creates PREV/NEXT relationships to adjacent days\n  5. Enables queries like \"show all Saturdays\" or \"find health patterns across weeks\"\n\nDay Cluster structure in Neo4j showing connections to Week, Month, and note components\n\n###\nWhy This Matters\n\nThis structure does three critical things:\n\nFirst, it separates intentions from reality. Plan (future tense) vs Log (past tense). This lets the AI compare what I intended vs what happened, generating insights about execution.\n\nSecond, it creates a consistent location for automation. The Health Service knows where to put diabetes data. The Review Service knows where to find context. Everything has a place.\n\nThird, it enables temporal queries. \"Show me all days where I exercised AND had perfect TIR\" becomes a graph traversal, not manual searching.\n\n### Example Day Cluster (Mar 28) - Series Launch\n\nWhen I ran `pkm-day create 2026-03-28`, the system:\n\n  * Created 13 markdown files in the correct folder\n  * Generated frontmatter with metadata\n  * Created 9 Neo4j nodes and relationships\n  * Connected to the week and month structures\n  * Set up PREV/NEXT links to Mar 27 and Mar 29\n  * Opened the workspace in Obsidian\n\n\n\nTime: 2 seconds.\nManual effort: Zero.\n\nThis consistency is what enables everything else...\n\n## Health Service: Automate Data Collection\n\nEvery morning, the Health Service runs automatically and collects my diabetes data from two sources: Dexcom (glucose) and Glooko (insulin/meals).\n\n### Dexcom API Integration\n\nDexcom provides a production API for developers. The service:\n\n  1. Authenticates using OAuth2 (stores refresh token securely)\n  2. Fetches glucose readings for the previous day (289 data points)\n  3. Downloads alert data (lows, highs, sensor issues)\n  4. Pulls exercise and meal events (manually logged in app)\n  5. Generates a comprehensive PDF report\n\n\n\nAll of this happens programmatically. No manual login, no\nscreenshot uploads, no copy-paste.\n\n### Glooko Data Extraction\n\nGlooko is trickier—they offer an API, but my access request for personal data hasn't been approved (after 6 weeks). So the system:\n\n  1. Uses Playwright (browser automation) to log in\n  2. Navigates to the date range (previous day)\n  3. Downloads the CSV export (insulin doses, carb counts)\n  4. Generates and saves the PDF report\n  5. Logs out cleanly\n\n\n\nYes, this is more fragile than an API. But Glooko has the insulin data from my Omnipod 5 pump, and that's critical for analysis.\n\n### Data Normalization\n\nRaw data isn't useful. The service merges and normalizes:\n\n  * Glucose readings (every 5 minutes, 288 points)\n  * Insulin doses (bolus + basal, 24u total)\n  * Meals (with carb counts and descriptions)\n  * Exercise events (activity type, duration, heart rate)\n  * Timeline creation (hourly breakdowns, period analysis)\n\n\n\nExample output from series launch day (Mar 28):\n\nAverage: 133 mg/dL\nRange: 90-183 TIR: 98% (standard), 82% (tight)\nInsulin: 24u (14u bolus, 9u basal)\nMeals: 3 (56g total carbs)\nExercise: 30 min lawn mowing (113 BPM avg)\n\n### Example: Day Diabetes Note\n\nThe automated review includes three key sections:\n\n### Glucose Timeline\n\n _Color-coded chart showing meals, insulin, and glucose response_\n\nDaily glucose timeline with meal markers and insulin doses\n\n### Meal & Insulin Timeline\n\n _Every meal with carbs, insulin dose, and glucose change_\n\nComplete meal log with carbs, insulin, and glucose response\n\n### Period Analysis\n\n _6-hour blocks showing TIR by time of day_\n\nTime in range analysis by 6-hour periods\n\nThis automated note becomes the foundation for AI analysis...\n\n### The Generated Review\n\nAll this data becomes the Day Diabetes note—a comprehensive markdown document with:\n\n  * Embedded glucose charts (matplotlib-generated)\n  * Meal timeline with insulin doses\n  * Hourly and period breakdowns\n  * Alert analysis\n  * Pattern observations section (for manual notes)\n\n\n\nThis note becomes the foundation for the AI analysis.\n\n### Why Automation Matters\n\nManual approach (what I used to do):\n\n  * Screenshot Dexcom Clarity (5 min)\n  * Screenshot Glooko reports (5 min)\n  * Paste into note (5 min)\n  * Review and annotate (15 min)\n  * Total: 30 minutes daily\n\n\n\n### What's Automated vs Manual\n\n**Fully Automated:**\n\n  * Glucose data fetch (Dexcom API)\n  * Insulin data fetch (Glooko automation)\n  * Data parsing and merging - Statistical calculations\n  * Chart generation\n  * Markdown note creation\n\n\n\n**Semi-Automated:**\n\n  * Glooko PDF save (requires manual click, then continues)\n\n\n\n**Still Manual (and that's fine):**\n\n  * Meal descriptions (typed into Dexcom app, 1-2 min/day)\n  * Exercise logging (marked in Dexcom app, 30 sec)\n  * Health observations (Day Health notes, 2-3 min)\n\n\n\n**Manual input: ~5 minutes daily\nAutomated processing: 90 seconds** (while making coffee)\n**Manual review: ~5 minutes** (reading the generated insights)\n\nTotal time: ~10 minutes vs 30 minutes before automation.\n\nAutomated approach (what runs now):\n\n  * Command: `pkm-health sync-full 2026-03-28`\n  * Time: 90 seconds\n  * Manual effort: Zero (runs while I make coffee)\n\n\n\n30 minutes saved daily = 15 hours per month = 180 hours per year.\n\nThat's a full work week of time recovered annually.\n\nAnd the data is more complete, more accurate, and more useful because it's structured for AI consumption, not human review.\n\nNext, let's see what the AI does with all this data...\n\n## Review Service - AI Analysis\n\nEvery morning, the Review Service takes the health data and 7 days of context, sends it to Claude AI, and generates the daily analysis.\n\n### The Context Window\n\nClaude doesn't just see yesterday. It sees:\n\n  * Day Plan (what I intended to do)\n  * Day Log (what actually happened)\n  * Day Health (manual observations)\n  * Day Diabetes (automated metrics)\n  * Previous 6 days of the same data\n\n\n\nThis 7-day sliding window is critical. The AI spots patterns I'd miss: \"Your Tuesday afternoons always spike—what's different on Tuesday?\"\n\n### The Prompt Structure\n\nThe prompt follows the Plus-Minus-Next (PMN) framework:\n\n**Plus:** What went well? The AI celebrates wins I'd forget.\n\"Fifth consecutive perfect day!\" I didn't even realize I was on a streak until the AI told me.\n\n**Minus:** What needs attention? The AI identifies patterns without judgment. \"Morning breakfast spike—timing or stress factor?\"\n\n**Next:** What specific actions? The AI provides concrete next steps. \"Try eating at 7:30 vs 8:09 to counter dawn phenomenon.\"\n\n### Example: March 28 Analysis\n\nWhen I ran the analysis after launch day, the AI:\n\n  1. Spotted the 5-day perfect streak (Mar 24-28)\n  2. Noted launch stress didn't derail diabetes (98% TIR)\n  3. Identified lawn mowing as intense exercise (113 BPM)\n  4. Suggested breakfast timing experiment\n  5. Celebrated the balance of health + work\n\n\n\nTime to generate: 30 seconds\nManual effort: Zero (runs while reviewing data)\n\nAI-generated daily analysis using Plus-Minus-Next framework\n\n### Why AI Coaching Works\n\nThree things the AI does that I can't:\n\n  1. **Pattern recognition across days:** \"Every time you exercise afternoon, glucose drops overnight—plan accordingly\"\n  2. **Objective celebration:** I minimize wins; AI celebrates them\n  3. **Comparative analysis:** \"Today's control better than last Tuesday despite similar meals\"\n\n\n\nThe AI isn't replacing my judgment—it's augmenting my awareness.\n\nNext, let's see how all this data connects in the knowledge graph...\n\n## Knowledge Graph - Neo4j Connections\n\nThe files are in Obsidian. The data is in Markdown. But the RELATIONSHIPS are in Neo4j.\n\n### Why a Graph Database?\n\nFile systems organize by location. Databases organize by tables. But health patterns don't fit neat hierarchies—they're networks of relationships.\n\nNeo4j stores:\n\n  * Days connected to weeks, months, quarters, years\n  * Health events connected to glucose readings\n  * Meals connected to insulin doses\n  * Exercise connected to subsequent lows\n  * Patterns connected to outcomes\n\n\n\n### Query Power\n\nTraditional approach (manual): \"Show me all days where I exercised AND had a low within 12 hours\".\n\n  * Open each day note\n  * Check for exercise entries\n  * Check glucose lows\n  * Cross-reference timestamps\n  * Take notes\n  * Time: 30+ minutes\n\n\n\nGraph query (Cypher):\n\n\n    MATCH (d:Day)-[:HAS_EXERCISE]->(e:Exercise)\n    MATCH (d)-[:HAS_GLUCOSE]->(g:Glucose)\n    WHERE g.value < 70\n      AND g.timestamp > e.timestamp\n      AND duration.between(e.timestamp, g.timestamp) < duration({hours: 12})\n    RETURN d, e, g\n\n\n  * Time: 2 seconds\n\nAI-generated daily analysis using Plus-Minus-Next framework\n\n### Pattern Discovery\n\nThe graph doesn't just answer questions—it reveals patterns:\n\n  * \"Your Saturday morning glucose averages 15 points higher than weekdays—different sleep pattern?\"\n  * \"Lawn mowing correlates with overnight lows 80% of the time—adjust bedtime snack?\"\n  * \"Week 13 averaged 97.1% TIR—what was different from Week 12?\"\n\n\n\nThis is where automation becomes intelligence.\n\nNext, let's see how Python orchestrates everything...\n\n## Integration Layer - Python Orchestration\n\nThe components don't run themselves—Python services orchestrate the flow.\n\n### Command-Line Interface\n\nThree main commands run everything:\n\n`pkm-day create 2026-03-28`\n\n  * Generates 13-file Day cluster\n  * Creates Neo4j nodes and relationships\n  * Opens workspace in Obsidian\n  * Time: 2 seconds\n\n\n\n`pkm-health sync-full 2026-03-28`\n\n  * Downloads Dexcom glucose data\n  * Extracts Glooko insulin data\n  * Merges and normalizes\n  * Generates Day Diabetes markdown\n  * Time: 90 seconds\n\n\n\n`pkm-review generate --stage final 2026-03-28`\n\n  * Reads Plan, Log, Health, Diabetes\n  * Gathers 7 days of context\n  * Sends to Claude AI\n  * Generates Day Analysis\n  * Time: 30 seconds\n\n\n\nTotal daily automation: ~2 minutes\n\n**What Runs Automatically vs Manual**\n\nAutomatic (runs while making coffee):\n\n  * Health data download\n  * Data normalization\n  * Chart generation\n  * Timeline creation\n  * Neo4j updates\n\n\n\nManual (what I still do):\n\n  * Morning review (5 min)\n  * Manual health notes (3 min)\n  * Journal reflections (5 min)\n\n\n\nThe automation handles DATA. I handle MEANING.\n\n### Error Handling\n\nWhen things break (they do):\n\n  * API authentication fails → retry with backoff\n  * PDF download times out → manual fallback\n  * Neo4j connection drops → queue for sync\n  * Claude rate limit hit → wait and retry\n\n\n\nThe system degrades gracefully—never crashes my workflow.\n\nNext, let's talk about costs and tools...\n\n## Technical Stack & Monthly Costs\n\n\n**The Tools**\n\n**Obsidian** (Free)\n\n  * Markdown editor and PKM platform\n  * Stores all notes locally\n  * Plugins: Dataview, Templater, Calendar\n\n\n\n**Neo4j Desktop** (Free)\n\n  * Graph database for relationships\n  * Runs locally on my Mac\n  * Unlimited nodes (local storage only)\n  * Full features, no cost, data stays private\n\n\n\nNote: Neo4j offers cloud options (Aura, $65+/month) for team collaboration or remote access. I don't need that— Desktop works perfectly for personal use.\n\n**Claude AI** ($20/month)\n\n  * Claude Pro subscription\n  * Unlimited conversations\n  * API access for automation\n\n\n\n**Python** (Free)\n\n  * Services run locally\n  * Libraries: requests, playwright, matplotlib\n  * No hosting costs (runs on my Mac)\n\n\n\n**Dexcom API** (Free)\n\n  * Production OAuth2 API\n  * No usage fees\n  * Medical device ecosystem\n\n\n\n**Glooko** (Free)\n\n  * Browser automation (no API fees)\n  * Included with Omnipod 5 pump\n\n\n\n**Total Monthly Cost: $20**\n\n  * Claude Pro: $20/month\n  * Neo4j Desktop: Free ✅\n  * Obsidian: Free ✅\n  * Python: Free ✅\n\n\n\nOptional upgrades:\n\n  * Neo4j Aura: $65/month (if you need cloud/teams)\n  * But I don't—Desktop is plenty!\n\n\n\n**Why These Choices**\n\n**Obsidian over Notion:**\n\n  * Files stored locally (I own my data)\n  * Markdown (future-proof format)\n  * Offline-first (works without internet)\n\n\n\n**Neo4j over PostgreSQL:**\n\n  * Relationships are first-class citizens\n  * Cypher queries are readable\n  * Pattern matching built-in\n\n\n\n**Claude over ChatGPT:**\n\n  * Longer context window (200K tokens)\n  * Better at structured analysis\n  * API reliability\n\n\n\n**Local vs Cloud:**\n\n  * Services run on my Mac (no hosting costs)\n  * Data stays private (HIPAA-conscious)\n  * Fast iteration (no deployment delays)\n\n\n\nThe tools matter less than the architecture. You could rebuild this with different tools—the patterns remain the same.\n\nNext, let's see how it all flows together...\n\n## Data Flow - Morning Routine in Action\n\n\n**7:00 AM - Wake Up**\n\n  * Day cluster already exists (created yesterday for planning).\n  * Glucose sensor has been collecting data all night (every 5 minutes).\n  * Omnipod pump recorded every insulin dose.\n\n\n\n**7:05 AM - Morning Routine**\n\nWhile making coffee, run:\n\n\n    pkm-health sync-full 2026-03-29\n\n\nBehind the scenes:\n\n  1. Dexcom API: Fetches 288 glucose readings\n  2. Glooko: Downloads insulin doses (23u total)\n  3. Parser: Merges glucose + insulin + meals\n  4. Generator: Creates Day Diabetes markdown\n  5. Charts: Generates 3 glucose visualizations\n  6. Neo4j: Updates graph with health nodes\n  7. Obsidian: Opens Day Diabetes note\n\n\n\nTime elapsed: 90 seconds\n\nTerminal output showing automated health data sync in action\n\n\n**7:15 AM - Review Yesterday**\n\n  * Read Day Diabetes (automated metrics).\n  * Add manual notes to Day Health (patterns observed).\n  * Update Day Log (what actually happened).\n\n\n\n**7:30 AM - Generate Analysis**\n\nRun:\n\n\n    pkm-review generate --stage final 2026-03-29\n\n\nBehind the scenes:\n\n  1. Reader: Loads Plan, Log, Health, Diabetes\n  2. Context: Gathers previous 6 days\n  3. Claude: Analyzes with PMN framework\n  4. Writer: Generates Day Analysis markdown\n  5. Obsidian: Opens Day Analysis note\n\n\n\nTime elapsed: 30 seconds\n\n**7:35 AM - Read Insights**\n\n  * AI spotted 6-day perfect streak.\n  * AI noted breakfast timing improvement.\n  * AI suggested evening walk helped dinner spike.\n  * Total time: 10 minutes (mostly reading)\n  * Manual data entry: Zero\n  * Cognitive load: Minimal\n\n\n\nThe system runs in the background. I focus on living.\n\n\n## What's Next\n\nThis is Part 2 of a 5-part _AI Diabetes Coach_ series. You've seen the architecture—now let's go deeper.\n\n**💭 Part 3:** Prompt Engineering — How to craft prompts that make Claude a genuine diabetes coach that spots patterns rather than a generic chatbot. I share:\n\n  * The exact prompt structure I use\n  * How to provide 7-day context efficiently\n  * Template for PMN (Plus-Minus-Next) analysis\n  * Examples of good vs great prompts\n  * How the AI's coaching evolves as you improve\n\n\n\n**🕸️ Part 4:** Knowledge Graph — Giving AI persistent, queryable memory across months of diabetes data. Neo4j isn't just storage—it's discovery. I'll show:\n\n  * Cypher queries for pattern detection\n  * Temporal analysis across weeks/months\n  * Correlation discovery (exercise → lows)\n  * Visual graph exploration\n  * How to ask questions your database can answer\n\n\n\n🔧**Part 5:** Build Your Own — Whatever your domain (fitness, nutrition, sleep, ADHD, energy):\n\n  * Start simple (manual + prompts)\n  * Add automation gradually\n  * Tools you can use without coding\n  * Where to invest time first\n  * How to adapt this architecture\n\n\n\n🍴 __**Part 6:** Teaching Your AI Coach to Cook — How food choices connect directly to glucose outcomes — building a recipe intelligence system that learns from your actual responses.\n\n_Missed the beginning? Start with 🚀 Part 1:_ The Transformation\n\nThe PKM structure that organizes all this data is covered in a separate series: 📅 Part 1: Day Cluster.\n\n**Your Turn**\n\n  * What domain would YOU apply this to?\n  * What patterns do you wish you could see?\n  * What data do you already collect but don't analyze?\n\n\n\nDrop a comment—I'd love to hear what you're building.\n\n* * *\n\n_Want the full series? Subscribe to get posts delivered automatically as they publish._\n\n## Sign up for WarrenWeb\n\nThinking, linking, and sharing\n\nSubscribe\n\nEmail sent! Check your inbox to complete your signup.\n\nNo spam. Unsubscribe anytime.",
  "title": "🏗️ AI Diabetes Coach — System Architecture",
  "updatedAt": "2026-04-28T11:58:34.819Z"
}