Inspiration

The IGAD region is on the frontlines of climate change; drought in the Horn of Africa, catastrophic floods in South Sudan, locust invasions in Ethiopia, and creeping desertification across the Sahel. Billions of dollars are spent on early warning systems that track river levels, rainfall deficits, and crop yields. But these systems miss the invisible crisis: the psychological toll that silently erodes a community's ability to prepare, respond, and recover.

After witnessing communities in Kenya's arid north where three consecutive drought seasons had driven smallholder farmers into gambling addiction, severe depression, and suicide with zero mental health services within a 200-kilometer radius here, we realized a devastating gap. Early warning without psychological early warning is incomplete. A community paralyzed by anxiety cannot evacuate ahead of a flood. A farmer in the throes of depression cannot plant during the critical window. A family whose breadwinner has lost everything to gambling cannot afford food.

We also saw the opportunity: WhatsApp penetration in Africa is over 95% among smartphone users, with many more accessing it on basic feature phones. The infrastructure for mental health early warning already exists in people's pockets. It just needs the right platform.

Minaki Health was born from this conviction: Climate resilience begins in the mind. Psychological early warning is not a luxury, it is the foundation of community resilience.

What it does

Minaki Health is the first AI-powered mental health early warning and anticipatory action platform purpose-built for the IGAD region. It detects early warning signs of psychological distress across multiple channels and triggers automated interventions before individuals reach crisis point.

The Early Warning Engine

The AI (GPT-4o-mini via OpenRouter) continuously analyzes user data across four dimensions:

  1. Mood Deterioration — Daily mood scores plotted over 30 days. The AI detects declining trajectories (three consecutive drops) and flags the user as "at risk"
  2. Gambling Urge Escalation — The Alchemy Lab tracks craving intensity over time. Escalating patterns trigger preventive interventions
  3. Crisis Language Detection — AI chat and therapy conversations are monitored for suicide keywords, self-harm references, and abuse indicators. Detection triggers immediate emergency resource routing to Kenya Red Cross (1199)
  4. Financial Distress Signals — Budget Safetynet detects unusual spending patterns, missed savings goals, and gambling-related transactions that indicate financial vulnerability

The Anticipatory Action System

When early warning triggers fire, the system deploys interventions across the user's preferred channel:

📱 WhatsApp Bot (+254705825637) — Users text naturally: "Log my mood 7", "I'm struggling", "Book therapy", "Donate 500". The AI understands intent and executes actions. Crisis detection triggers immediate resource sharing. No app download. No account creation. Zero barrier to entry.

🌐 Web Platform (ahaminaki.org) — Full therapeutic dashboard with:

  • Council Chat — AI mental health counselor with Kenyan context and local resources
  • Mood Tracking — Log emotions, sleep, energy, anxiety. AI generates insights and pattern analysis
  • Professional Therapy — Browse 26 licensed therapists, book sessions, pay via M-Pesa or Paystack, join secure LiveKit video calls. OTP-verified session completion ensures accountability
  • Gambling Recovery Suite — 8 specialized tools:
    • 🧪 Alchemy Lab — Transform cravings into positive emotions through drag-drop emotional alchemy
    • 🕊️ Shame Transformer — Convert self-critical thoughts into compassionate wisdom with AI-generated metaphors
    • 🔊 Echo Chamber of Selves — Guided dialogue between Past, Present, and Future selves
    • 🦅 Phoenix Rise — Create memorials, process grief through release ceremonies
    • ✈️ Aviator Simulation — Safe gambling exposure with educational warnings and fake currency
    • 🎰 Slot Simulation — Realistic slot machine for controlled trigger exposure
    • 🃏 Card Simulation — Blackjack with built-in gambling education
    • 🌱 Temporal Garden — Visualize recovery progress as a growing garden
  • Budget Safetynet — Spending alerts, savings goals, financial journal with emotional correlation
  • Minaki Circles — Peer support groups across 10 categories ( anxiety, depression, PTSD, grief, gambling recovery etc.)
  • Assessments — Clinical Approved Self-assessment tests for mental health screening and automated flagging of users classified as HIGH RISK
  • Emergency Resources — One-tap access to crisis helplines per country

🤖 Telegram Bot — Encrypted AI therapy via Telegram, with specialized crisis detection and keyword-based therapeutic responses

📱 Android App — Native Android via Capacitor 6, ready for Play Store distribution

Social Impact Model

The platform is 100% free to users. Funded through M-Pesa Till Number 4158625, M-PESA Daraja API, Paystack API, PayPal donations, and an optional ~$1/year premium tier. We do not monetize vulnerability.

How we built it

The platform follows a multi-channel, single-API architecture. One backend serves four frontends.

User ──► Web Browser ──► Next.js 15 App Router ──┐
User ──► WhatsApp ─────► OpenClaw Agent ─────────►┤
User ──► Telegram ─────► Telegram Bot ───────────►┤
User ──► Android ─────► Capacitor 6 ─────────────►┘
                                                    │
                                                    ▼
                                    ┌──────────────────────────┐
                                    │  86+ API Route Handlers   │
                                    └──────────┬───────────────┘
                                               │
                                    ┌──────────┴───────────────┐
                                    │  lib/ Service Layer       │
                                    │  • auth, subscription    │
                                    │  • therapy, payments     │
                                    │  • notifications, sms    │
                                    └──────────┬───────────────┘
                                               │
                                    ┌──────────┴───────────────┐
                                    │  Prisma ORM + PostgreSQL │
                                    │  30+ models, 18 migrations│
                                    └──────────────────────────┘
                                               │
                                    ┌──────────┴───────────────┐
                                    │  External Services        │
                                    │  • Minaki AI Core Engine   │
                                    │  • LiveKit (Self Hosted for Video Therapy Sessions)       │
                                    │  • M-Pesa STK Push       │
                                    │  • Paystack              │
                                    │  • MoveSMS API              │
                                    │  • Clerk Auth            │
                                    └──────────────────────────┘

Key Technical Decisions

1. Dual Authentication System — The middleware makes all /api/(.*) routes publicly accessible. Individual route handlers call getAuthUserId(request) which supports both Clerk session tokens (web browsers) and X-API-Key headers (WhatsApp/curl requests). This single innovation enables the entire multi-channel architecture.

2. WhatsApp Auto-Creation — When an unknown phone number sends a message to the WhatsApp bot, the system auto-creates a user record with ID format phone_2547XXXXXXXX and placeholder email. Zero sign-up friction. Critical for reaching first-time users during emergencies.

3. SSE with Smart Polling — Subscription status updates use Server-Sent Events as primary channel, with exponential backoff polling (5s → 10s → 20s → 40s → 60s max) as fallback. Ensures users see premium activation instantly without page refresh.

4. Real-Time Video Therapy — Self-hosted LiveKit server at livekit.ahaminaki.org provides WebRTC-based video calls with end-to-end encryption. No reliance on third-party video infrastructure.

5. OTP-Verified Session Completion — When therapists mark sessions complete, a 6-digit OTP is sent to the client via SMS (MoveSMS) and email (Nodemailer). The client reads the code to the therapist during the video call. Prevents fraud and ensures accountability.

6. Prisma Client Singleton — The database client is initialized once in development (hot-reload safe) and once per request in production. BigInt serialization handling ensures M-Pesa transaction IDs don't break JSON serialization.

Frontend Architecture

  • Server-Client Component Split — Next.js App Router pattern: server components fetch data, client components handle interactivity
  • Framer Motion for smooth animations with prefers-reduced-motion support for accessibility
  • Rive for the interactive panda mascot that reacts to user progress (smiles for healthy choices, sad for deteriorating patterns)
  • Recharts for mood trend visualization, analytics dashboards
  • shadcn/ui for consistent, accessible UI primitives
  • Tailwind CSS with custom brand theme (Deep Forest Teal, Lush Leaf Green, Muted Crimson)

State Management

  • React Context for cross-cutting concerns: CurrencyContext (multi-currency support), SubscriptionContext (real-time subscription status)
  • Custom Hooks: useSubscription, useSmartSubscription, useCurrencyConversion, usePrefersReducedMotion, useMediaBreakpoint

Database (30+ Models)

Key models include: User, Therapist, TherapySession, Mood, Subscription, PaymentTransaction, Coupon, Circle, CirclePost, GardenProgress, GamblingAssessment, BudgetCategory, SavingsGoal, SpendingAlert, Notification, JournalEntry, MeditationSession, and 15+ more supporting models.

Tech Stack Summary

Category Technology
Framework Next.js 15 App Router + TypeScript
Styling Tailwind CSS + shadcn/ui + CSS Modules
Database PostgreSQL + Prisma ORM (30+ models)
Auth Clerk (SOC 2, MFA-ready) + Custom API Key system
AI OpenRouter (GPT-4o-mini)
Video Self-hosted LiveKit (WebRTC)
Mobile Capacitor 6 (Android)
Payments M-Pesa STK Push, Paystack, PayPal
SMS MoveSMS Kenya API
Email Nodemailer (SMTP)
WhatsApp OpenClaw AI agent on VPS
Telegram Node.js + Google Gemini 1.5 Flash
Animation Framer Motion, Rive, AOS
PWA next-pwa with service worker
Charts Recharts
File Upload UploadThing

Challenges we ran into

1. Making WhatsApp Work with Our API Auth

The biggest architectural challenge was enabling a user to interact via WhatsApp without having a browser session. Clerk auth is session-based — it requires cookies. WhatsApp API calls are stateless curl requests.

Solution: We built a dual authentication system. The middleware passes all API requests through. Each route handler calls getAuthUserId(request) which checks for either a Clerk session (browser) or an X-API-Key header (WhatsApp). If API key auth succeeds, it looks up the user by phone number. If no user exists, it auto-creates one. This was a fundamental architectural shift that required modifying the middleware, every route handler, and creating lib/api-auth.ts.

2. Real-Time Subscription Status Without WebSockets

Deploying on Vercel's serverless architecture means no persistent connections. We needed users to see their subscription activate instantly after M-Pesa payment without refreshing the page.

Solution: We implemented Server-Sent Events (SSE) from a serverless function, combined with a smart polling fallback. The useSmartSubscription hook establishes an SSE connection, and if it fails (as serverless functions sometimes do), it falls back to exponential backoff polling. The temporary polling mode after payment initiation polls aggressively (5 attempts at 3-second intervals) to catch the callback.

3. M-Pesa Callback Reliability

M-Pesa callbacks from Safaricom's API are notoriously unreliable — they sometimes arrive late, duplicate, or not at all. Users were paying but not seeing their subscriptions activate.

Solution: We built a multi-layer callback handling system: (1) Primary callback endpoint receives M-Pesa result, (2) Manual callback test endpoint for admins, (3) Debug endpoints to check payment state, (4) SSE events push status to the client in real-time, (5) Client-side smart polling as fallback. Additionally, we implemented BigInt serialization because M-Pesa transaction IDs exceed JavaScript's safe integer range.

4. Mobile Responsiveness for Complex Interactions

The Alchemy Lab involves drag-and-drop interactions — users drag "fear" into a flask to transform it into "courage." This doesn't work on mobile touch screens.

Solution: We implemented a mobile-first interaction pattern. On touch devices, users tap a component to select it, then tap a flask to drop it. The UI provides visual feedback showing which component is selected and which flask is ready to receive it. Touch event handlers (onTouchStart, onTouchMove, onTouchEnd) complement the drag-and-drop mouse events.

5. Scaling Mental Health Content Across 6+ Countries

Each IGAD country has different emergency numbers, cultural stigmas, currency, and mental health resources. A one-size-fits-all approach would fail.

Solution: We built a country selector that triggers on first visit, sets the preferred currency (KES, UGX, TZS, ETB, NGN, GHS), and configures region-specific content. Emergency resources show the correct crisis helpline per country. The CurrencyContext and CurrencyConversion hook handle real-time exchange rates. Separate landing pages exist for each country.

6. Gambling Simulation Without Legal Risk

Building realistic gambling simulations for exposure therapy carries legal and ethical risks. We needed to educate, not encourage.

Solution: Every simulation includes educational warnings at critical moments — when users chase losses, bet large portions of their balance, or lose repeatedly. A fake currency system ($1,000 starting balance) ensures no real money is involved. The Aviator simulation shows "Gambler's fallacy" warnings. The Slot simulation explains house edge. All simulations emphasize: "This was a safe simulation — no real money was involved!"

7. Ensuring Help-Seeking for Stigmatized Issues

Mental health and gambling addiction carry deep stigma across the IGAD region. Users won't seek help if they fear judgment.

Solution: Anonymous posting in Minaki Circles allows users to share without revealing identity. The WhatsApp bot provides complete privacy — no one knows you're using a mental health app when the notification just says "WhatsApp." The AI chat maintains a warm, non-judgmental tone. Emergency resources are branded as general "support" rather than "mental health crisis."

Accomplishments that we're proud of

1. First WhatsApp-Based Mental Health Early Warning System in East Africa — We believe Minaki is the first platform in the IGAD region to deliver AI-powered mental health early warning through WhatsApp. Users don't need smartphones, data plans, or app stores. They just need WhatsApp — which 95%+ of phone users in the region already have.

2. Novel Digital Therapeutics for Gambling Addiction — The Alchemy Lab (craving → emotion transformation), Shame Transformer (self-critical → compassionate), and Echo Chamber of Selves (past/present/future dialogue) are genuinely novel therapeutic tools. We're not just wrapping ChatGPT — we've designed interactive therapeutic experiences that don't exist in any other platform.

3. Complete, Production-Ready Tech Stack — This isn't a prototype. It's a deployed, tested platform with 86+ API endpoints, 30+ database models, 4 deployment targets (Web, WhatsApp, Telegram, Android), 3 payment systems (M-Pesa, Paystack, PayPal), real-time video therapy, and real users (2,300+ clients, 26 therapists, 15 countries).

4. Sustainable Social Impact Model — The platform is 100% free to users. We fund it through M-Pesa Till 4158625 donations and an optional ~$1/year premium. We're not dependent on grants or investor funding. This means the platform can survive beyond the hackathon.

5. OTP-Verified Session Integrity — We implemented a novel OTP system where clients receive a 6-digit code via SMS and email at session completion, which they share with their therapist during the video call. This prevents the all-too-common problem of therapists marking incomplete sessions as complete, building trust in remote mental health care.

6. The Alchemy Lab Drag-Drop Experience — The Alchemy Lab is genuinely beautiful and therapeutic. Users log a craving, the AI analyzes it into emotional components (fear, escape, excitement, control), and users physically drag each component into a transformation flask. The flasks bubble and glow as transformation happens. Progress is tracked. When all four are transformed, the user sees a celebration animation. We're immensely proud of this interaction design.

7. Real Impact — 2,300+ clients served. 26 therapists onboarded. Active in 15+ countries. 99% satisfaction rate. Real people are getting real help.

📚 What We Learned

1. Mental Health Tech Requires Trauma-Informed Design — Every design decision — from color palette (calming teals and greens, no triggering reds) to language (non-judgmental, destigmatized) to interaction patterns (no high-pressure notifications) — must be made through a trauma-informed lens. We learned that standard SaaS UX patterns (aggressive CTAs, scarcity tactics, streak-shaming) are harmful for this audience.

2. WhatsApp Is the Most Underrated Health Platform in Africa — We initially built the web platform first. But when we launched the WhatsApp bot, adoption accelerated dramatically. Users who would never download a "mental health app" happily texted a WhatsApp number. The friction of app installation and account creation is a barrier that WhatsApp eliminates entirely.

3. Building for Intermittent Connectivity Changes Everything — The IGAD region has some of the world's most expensive and unreliable internet. We learned to design for offline-first: PWA service worker caching, simplified UI for 2G speeds, SMS fallback for critical communications, and asynchronous interaction patterns that don't require real-time responses.

4. You Can't Just Import Western Mental Health Models — Western therapy assumes individualistic, one-on-one, 50-minute sessions. In the IGAD region, community-based, collective healing approaches are more effective. Our Minaki Circles (peer support groups) and the community resilience focus were direct responses to this learning.

5. M-Pesa Is More Than a Payment System — M-Pesa isn't just how Kenyans pay — it's how they save, borrow, insure, and build credit. Integrating M-Pesa STK Push for donations and subscriptions was technically challenging (unreliable callbacks, BigInt serialization), but it was essential. Users trust M-Pesa in a way they don't trust credit cards.

6. AI Hallucination in Mental Health Contexts Is Dangerous — We learned that using AI for mental health requires aggressive guardrails. Our OpenRouter prompts include specific instructions: never diagnose, never prescribe medication, always recommend professional help for serious conditions, and immediately flag crisis keywords. We also learned that simpler models (GPT-4o-mini) with better prompts outperform larger models with generic prompts.

7. Stigma Is the Biggest Technical Challenge — The hardest problem wasn't building the AI or the database — it was designing a system where people would actually use it. Anonymous posting, WhatsApp privacy, destigmatized language, and the friendly panda mascot were all responses to the profound stigma around mental health in the region.

What's next for MINAKI HEALTH

Phase 1: Scale Across the IGAD Region (Next 6 Months)

  • Full IGAD Country Expansion — Deploy local instances in all 8 IGAD member states (Djibouti, Eritrea, Ethiopia, Kenya, Somalia, South Sudan, Sudan, Uganda) with local languages, emergency numbers, and therapist networks
  • Language Localization — Add Swahili, Amharic, Somali, Oromo, Tigrinya, and Arabic language support across all 4 channels
  • Therapist Network Growth — Recruit and onboard 100+ licensed therapists across the region, with special focus on female therapists and trauma specialists
  • Offline-First Mode — Build full offline functionality for the PWA, allowing users to log moods and journal entries without internet, syncing when connectivity returns

Phase 2: AI-Powered Early Warning Network (6-12 Months)

  • Population-Level Early Warning Dashboard — Aggregate anonymized mood and crisis data to provide real-time mental health early warning maps for governments and humanitarian organizations. A spike in crisis language in a specific geographic area could precede a local disaster or conflict
  • Climate-Mental Health Correlation Engine — Integrate with ICPAC climate data to predict mental health crises based on weather patterns (drought duration, flood extent, crop failure projections)
  • SMS Broadcasting for Emergency Alerts — Government and humanitarian partners can broadcast mental health support messages to at-risk populations via SMS during climate emergencies
  • Community Health Worker Network — Train community health workers to use the platform as a screening and referral tool, extending reach beyond smartphone users

Phase 3: Integration with National Health Systems (12-24 Months)

  • Ministry of Health Integration — Partner with IGAD member state Ministries of Health to integrate Minaki as the official mental health early warning and referral system
  • EMR Integration — Connect with national Electronic Medical Record systems for continuity of care between digital and in-person services
  • Telemedicine Certification — Obtain regulatory approval as a telemedicine provider in each IGAD member state
  • Insurance Integration — Work with NHIF (Kenya), SHI (Ethiopia), and other national health insurers to cover therapy sessions conducted through the platform

Phase 4: Research & Evidence Building (Ongoing)

  • Clinical Trials — Conduct randomized controlled trials to measure the platform's impact on mental health outcomes, gambling relapse rates, and community resilience
  • ICPD Partnership — Collaborate with ICPAC to publish research on the correlation between climate events and mental health deterioration in the IGAD region
  • Open Source the Platform — Release the core platform as open source so other regions facing similar challenges can adapt and deploy their own instances
  • Academic Partnerships — Partner with universities in the IGAD region to train the next generation of digital mental health practitioners

Immediate Next Steps (Post-Hackathon)

  1. Submit to Google Play Store — The signed Android AAB is ready for distribution
  2. Launch WhatsApp Bot Phase 2 — Add 30+ additional WhatsApp features (mood history, meditation stats, daily check-ins, guided breathing, crisis detection, circle joining, premium purchase via M-Pesa)
  3. Partnership with Kenya Red Cross — Formalize the emergency referral pathway
  4. Deploy in Ethiopia — Ethiopia hosts ICPAC headquarters. A localized Ethiopian instance with Amharic language support is the highest priority
  5. User Growth Campaign — Leverage the WhatsApp bot to onboard 10,000+ users across the IGAD region

"Smarter Early Warning, Stronger Communities" — IGAD Hackathon 2026

Built With

Share this project:

Updates

Submission history