diff --git a/README.md b/README.md
index 9cb57a2..68d1161 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# GRIT
-A full-stack fitness and nutrition tracking app for people serious about body composition. GRIT combines macro tracking, habit building, activity logging, social challenges, and an AI coach into a single opinionated dark-mode mobile experience.
+A full-stack fitness and nutrition tracking app for people serious about body composition. GRIT combines macro tracking, habit building, activity logging, social challenges, and an AI coach into a single opinionated mobile experience, in dark or light.
---
@@ -36,18 +36,22 @@ grit/
| `/onboarding/advanced` | Earnback calories toggle, rollover toggle |
| `/onboarding/notifications` | Notification preferences |
| `/onboarding/reveal` | Personalised TDEE + macro plan reveal |
-| `/onboarding/signup` | Account creation (email + password) |
-| `/(auth)/login` | Returning user login |
+| `/onboarding/signup` | Account creation (email + password, or Google / Apple) |
+| `/(auth)/login` | Returning user login (email, Google or Apple) |
| `/(tabs)/` | Home — daily calorie budget, macro progress, today's workout |
-| `/(tabs)/food` | Food log — any day, meal sections, edit entries, barcode scanner |
+| `/(tabs)/food` | Food log — any day, meal sections, edit entries, barcode scanner, ✨ Smart log (describe or photograph a meal) |
| `/(tabs)/habits` | Habit tracker — check-ins, undo, 30-day history and back-fill |
-| `/(tabs)/activity` | Stats — 7D/30D/3M trends for calories, protein, activity and weight, then any week's workouts |
+| `/(tabs)/activity` | Stats — adaptive calorie target, 7D/30D/3M trends for calories, protein, activity and weight, then any week's workouts |
| `/(tabs)/social` | Feed, challenges and leaderboard |
| `/(tabs)/profile` | User profile + settings |
| `/settings/goals` | Goals & Targets — goal, body stats, calories, macros, earnback/rollover |
| `/settings/notifications` | Daily reminders and alert preferences |
-| `/settings/account` | Units, password reset, log out, delete account |
+| `/settings/account` | Appearance (system, light, dark), units, password reset, log out, delete account |
| `/settings/privacy` | Private account and blocked people |
+| `/settings/health` | Apple Health / Health Connect: connect, sync now, what was imported |
+| `/settings/foods` | Foods GRIT knows: portions learned from Smart log |
+| `/settings/coach-memory` | What your coach knows: notes from chats, add or delete |
+| `/auth-callback` | Finishes Google or Apple sign-in |
| `/plan` | Weekly workout plan built by the coach |
| `/friends` | Search people, follow requests, followers and following |
| `/profile/[id]` | Someone's profile: follow state, this week's stats and recent activity (if allowed) |
@@ -107,18 +111,20 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS).
| `auth` | Guard that verifies Supabase access tokens, `POST /auth/sync` |
| `users` | `GET/PUT/DELETE /users/me` (delete removes the account and its Supabase sign-in) |
| `food` | `GET/POST /food-logs` (with the day's calorie budget and macro targets), `GET /food-logs/week?date=`, `PATCH/DELETE /food-logs/:id`, Open Food Facts search + barcode proxy, `GET /food/recent`, `GET/POST /food/favorites`, `DELETE /food/favorites/:id` |
+| `meal-parse` | `POST /food/parse` (text and/or photo → items), `POST /food/parse/log`, `GET /food/memories`, `DELETE /food/memories/:id` |
+| `health` | `POST /health/import` (workouts, daily steps and sleep, weigh-ins from Apple Health / Health Connect), `GET /health/recent` |
| `activity` | `GET/POST /activity-logs`, `GET /activity-logs/week?date=`, `PATCH/DELETE /activity-logs/:id`, `POST /activity-logs/:id/kudos` |
| `habits` | `GET/POST/PUT/DELETE /habits`, `POST/DELETE /habits/:id/log?date=`, `GET /habits/streaks`, `GET /habits/:id/streak` |
| `workout-plan` | `GET /workout-plan`, `POST /workout-plan/generate`, `PUT /workout-plan/days/:day` |
| `challenges` | `GET/POST /challenges` (steps, active minutes or workouts; progress from logged workouts), `GET/DELETE /challenges/:id`, `POST /challenges/join/:code`, `DELETE /challenges/:id/participants/me` |
| `social` | `GET /feed`, `GET /leaderboard/weekly`, `GET /search/users?q=`, `POST/DELETE /follow/:userId`, `GET /follow-requests`, `POST /follow-requests/:userId/accept`, `DELETE /follow-requests/:userId`, `DELETE /followers/:userId`, `GET /users/:id/{profile,followers,following}`, `GET/POST/DELETE /blocks` |
-| `progress` | `GET/POST /weight`, `DELETE /weight/:id`, `GET /stats/trends?days=7\|30\|90` |
-| `ai` | `POST /ai/message` (streamed), `GET /ai/messages`, `GET /ai/nudge` — AI coach |
+| `progress` | `GET/POST /weight`, `DELETE /weight/:id`, `GET /stats/trends?days=7\|30\|90`, `GET /targets/adaptive`, `POST /targets/adaptive/apply`, `POST /targets/adaptive/snooze` |
+| `ai` | `POST /ai/message` (streamed), `GET /ai/messages`, `GET /ai/nudge`, `GET/POST/DELETE /ai/memories`, `DELETE /ai/memories/:id` — AI coach and its notes |
| `notifications` | `GET /notifications`, `GET /notifications/unread-count`, `POST /notifications/read`, `POST/DELETE /notifications/register` (one row per phone), Expo push sending |
| `app` | `GET /health`, `POST /client-errors` (crash reports from the app, no sign-in, throttled) |
-| `alerts` | Hourly job: challenge results, 8pm streak-at-risk and Sunday 6pm weekly check-in, in each user's local time |
+| `alerts` | Hourly job: challenge results, 1pm coach check-ins, 8pm streak-at-risk and Sunday 6pm weekly check-in (with any target suggestion), in each user's local time |
-**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood
+**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · CoachMemory · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood · FoodMemory · HealthDay
See [`docs/ROADMAP.md`](./docs/ROADMAP.md) for what's done and what's next.
diff --git a/apps/mobile/__tests__/healthTransform.test.ts b/apps/mobile/__tests__/healthTransform.test.ts
new file mode 100644
index 0000000..2ee57cd
--- /dev/null
+++ b/apps/mobile/__tests__/healthTransform.test.ts
@@ -0,0 +1,57 @@
+import { androidExerciseType, appleWorkoutType, latestWeightPerDay, sleepByNight, toImportPayload } from '@/lib/health/transform';
+
+const at = (iso: string) => new Date(iso);
+
+describe('health transform', () => {
+ it('maps workout types from both platforms', () => {
+ expect(appleWorkoutType(37)).toBe('running');
+ expect(appleWorkoutType(50)).toBe('strength_training');
+ expect(appleWorkoutType(9999)).toBe('other');
+ expect(androidExerciseType(79)).toBe('walking');
+ expect(androidExerciseType(54)).toBe('rowing');
+ expect(androidExerciseType(-1)).toBe('other');
+ });
+
+ it('counts overlapping sleep once and removes awake time', () => {
+ const nights = sleepByNight([
+ // Phone and watch both recorded 23:00–07:00
+ { start: at('2026-11-03T23:00:00'), end: at('2026-11-04T07:00:00'), asleep: true },
+ { start: at('2026-11-04T00:00:00'), end: at('2026-11-04T06:30:00'), asleep: true },
+ // 30 minutes awake in the middle
+ { start: at('2026-11-04T03:00:00'), end: at('2026-11-04T03:30:00'), asleep: false },
+ ]);
+ expect(nights).toEqual({ '2026-11-04': 450 });
+ });
+
+ it('keeps the last weigh-in of each day and drops silly values', () => {
+ expect(
+ latestWeightPerDay([
+ { at: at('2026-11-04T07:00:00'), kg: 80.2 },
+ { at: at('2026-11-04T20:00:00'), kg: 80.9 },
+ { at: at('2026-11-03T07:00:00'), kg: 81 },
+ { at: at('2026-11-02T07:00:00'), kg: 2 },
+ ]),
+ ).toEqual([
+ { date: '2026-11-03', weightKg: 81 },
+ { date: '2026-11-04', weightKg: 80.9 },
+ ]);
+ });
+
+ it('builds the import body, merging steps and sleep per day', () => {
+ const now = at('2026-11-04T12:00:00');
+ const body = toImportPayload('healthkit', {
+ workouts: [
+ { id: 'hk:1', activityType: 'running', start: at('2026-11-04T07:00:00'), end: at('2026-11-04T07:32:30'), kcal: 310.6 },
+ { id: 'hk:future', activityType: 'yoga', start: at('2026-11-05T07:00:00'), end: at('2026-11-05T08:00:00') },
+ ],
+ steps: [{ date: '2026-11-04', steps: 6400.4 }, { date: '2026-11-05', steps: 10 }],
+ sleep: [{ start: at('2026-11-03T23:30:00'), end: at('2026-11-04T06:30:00'), asleep: true }],
+ weights: [{ at: at('2026-11-04T07:00:00'), kg: 80.21 }],
+ }, now);
+ expect(body.workouts).toEqual([
+ { externalId: 'hk:1', activityType: 'running', startedAt: at('2026-11-04T07:00:00').toISOString(), durationMin: 33, caloriesBurned: 311 },
+ ]);
+ expect(body.days).toEqual([{ date: '2026-11-04', steps: 6400, sleepMinutes: 420 }]);
+ expect(body.weights).toEqual([{ date: '2026-11-04', weightKg: 80.21 }]);
+ });
+});
diff --git a/apps/mobile/__tests__/notificationRoute.test.ts b/apps/mobile/__tests__/notificationRoute.test.ts
index 4b3b499..142edec 100644
--- a/apps/mobile/__tests__/notificationRoute.test.ts
+++ b/apps/mobile/__tests__/notificationRoute.test.ts
@@ -7,6 +7,9 @@ describe('where an alert opens', () => {
expect(notificationRoute('challenge_ended', { challengeId: 'c1' })).toEqual({ pathname: '/challenge/[id]', params: { id: 'c1' } });
expect(notificationRoute('streak_at_risk')).toBe('/(tabs)/habits');
expect(notificationRoute('weekly_progress')).toBe('/(tabs)/activity');
+ expect(notificationRoute('coach_checkin', { screen: 'food' })).toBe('/(tabs)/food');
+ expect(notificationRoute('coach_checkin', { screen: 'stats' })).toBe('/(tabs)/activity');
+ expect(notificationRoute('coach_checkin', {})).toBe('/coach');
});
it('falls back to the inbox when ids are missing or the type is unknown', () => {
expect(notificationRoute('follow')).toBe('/notifications');
diff --git a/apps/mobile/__tests__/smartLog.test.ts b/apps/mobile/__tests__/smartLog.test.ts
new file mode 100644
index 0000000..403a1f6
--- /dev/null
+++ b/apps/mobile/__tests__/smartLog.test.ts
@@ -0,0 +1,9 @@
+import { mealForHour } from '@/lib/meals';
+
+describe('mealForHour', () => {
+ it('picks the meal for the time of day', () => {
+ expect([6, 10, 11, 14, 15, 16, 17, 21, 22, 2].map(mealForHour)).toEqual([
+ 'breakfast', 'breakfast', 'lunch', 'lunch', 'snack', 'snack', 'dinner', 'dinner', 'snack', 'snack',
+ ]);
+ });
+});
diff --git a/apps/mobile/app.json b/apps/mobile/app.json
index 55b4126..e541b2f 100644
--- a/apps/mobile/app.json
+++ b/apps/mobile/app.json
@@ -6,7 +6,7 @@
"scheme": "grit",
"orientation": "portrait",
"icon": "./assets/icon.png",
- "userInterfaceStyle": "dark",
+ "userInterfaceStyle": "automatic",
"splash": {
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
@@ -57,7 +57,11 @@
"foregroundImage": "./assets/android-icon-foreground.png"
},
"permissions": [
- "android.permission.CAMERA"
+ "android.permission.CAMERA",
+ "android.permission.health.READ_EXERCISE",
+ "android.permission.health.READ_STEPS",
+ "android.permission.health.READ_WEIGHT",
+ "android.permission.health.READ_SLEEP"
],
"blockedPermissions": [
"android.permission.RECORD_AUDIO"
@@ -74,7 +78,7 @@
[
"expo-camera",
{
- "cameraPermission": "GRIT uses your camera to scan food barcodes.",
+ "cameraPermission": "GRIT uses your camera to scan food barcodes and photograph meals.",
"microphonePermission": false,
"recordAudioAndroid": false
}
@@ -90,10 +94,31 @@
[
"expo-image-picker",
{
- "photosPermission": "GRIT uses your photos so you can choose a profile picture.",
- "cameraPermission": false,
+ "photosPermission": "GRIT uses your photos so you can choose a profile picture or log a meal from a photo.",
+ "cameraPermission": "GRIT uses your camera to photograph meals so it can estimate what's in them.",
"microphonePermission": false
}
+ ],
+ "expo-apple-authentication",
+ "expo-web-browser",
+ [
+ "@kingstinct/react-native-healthkit",
+ {
+ "NSHealthShareUsageDescription": "GRIT reads your workouts, steps, sleep and weight so they count toward your goals and challenges, and so your coach can see how you're recovering.",
+ "NSHealthUpdateUsageDescription": false,
+ "background": false
+ }
+ ],
+ "react-native-health-connect",
+ [
+ "expo-build-properties",
+ {
+ "android": {
+ "compileSdkVersion": 36,
+ "targetSdkVersion": 36,
+ "minSdkVersion": 26
+ }
+ }
]
],
"extra": {
diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx
index bdd7568..1c6c9fa 100644
--- a/apps/mobile/app/(auth)/login.tsx
+++ b/apps/mobile/app/(auth)/login.tsx
@@ -1,29 +1,27 @@
import React, { useState } from 'react';
import {
View,
+ Platform,
Text,
KeyboardAvoidingView,
- Platform,
ScrollView,
Pressable,
Alert,
} from 'react-native';
import { Link, router } from 'expo-router';
import { supabase } from '@/lib/supabase';
-import { api } from '@/lib/api';
-import { useAuthStore } from '@/stores/authStore';
-import { syncOnboardingProfile } from '@/lib/onboardingProfile';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { notify } from '@/lib/confirm';
import { sendPasswordReset } from '@/lib/passwordReset';
import { Colors } from '@/constants/colors';
+import { afterSignIn } from '@/lib/postSignIn';
+import { SocialSignIn } from '@/components/auth/SocialSignIn';
export default function LoginScreen() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
- const { setOnboardingComplete } = useAuthStore();
async function handleEmailLogin() {
if (!email || !password) {
@@ -32,15 +30,11 @@ export default function LoginScreen() {
}
setLoading(true);
try {
- const { error } = await supabase.auth.signInWithPassword({ email, password });
+ const { data, error } = await supabase.auth.signInWithPassword({ email, password });
if (error) throw error;
- await setOnboardingComplete();
- // Sync user record with backend (creates if first login)
- await api.post('/auth/sync');
- // Save any plan answered before signing up (e.g. pending email confirmation)
- await syncOnboardingProfile().catch(() => {
- // Kept on the device and retried at the next login
- });
+ // Creates the backend user on first login and saves any plan answered
+ // before signing up (e.g. while the email was being confirmed)
+ await afterSignIn(data.session);
router.replace('/(tabs)/');
} catch (err: any) {
Alert.alert('Login failed', err.message ?? 'Something went wrong.');
@@ -126,36 +120,8 @@ export default function LoginScreen() {
/>
- {/* Divider */}
-
-
-
- or
-
-
-
-
- {/* OAuth */}
-
-
+ {/* Google and Apple, once switched on in Supabase */}
+
{/* Sign up link */}
diff --git a/apps/mobile/app/(tabs)/activity.tsx b/apps/mobile/app/(tabs)/activity.tsx
index db8632d..1c2fac8 100644
--- a/apps/mobile/app/(tabs)/activity.tsx
+++ b/apps/mobile/app/(tabs)/activity.tsx
@@ -13,6 +13,7 @@ import { ScreenSkeleton } from '@/components/ui/Skeleton';
import { ACTIVITY_LABELS, LogActivitySheet } from '@/components/activity/LogActivitySheet';
import { DateNavigator } from '@/components/ui/DateNavigator';
import { TrendsCard } from '@/components/stats/TrendsCard';
+import { AdaptiveCard } from '@/components/stats/AdaptiveCard';
import { LogWeightSheet } from '@/components/stats/LogWeightSheet';
import { usePullToRefresh } from '@/hooks/usePullToRefresh';
import { Colors } from '@/constants/colors';
@@ -96,7 +97,7 @@ export default function ActivityScreen() {
const { data: habitSummary } = useHabitSummary();
const [showSheet, setShowSheet] = useState(false);
const [showWeight, setShowWeight] = useState(false);
- const { refreshing, onRefresh } = usePullToRefresh([['activity-week'], ['food-week'], ['me'], ['habits'], ['habit-streaks'], ['trends'], ['weight']]);
+ const { refreshing, onRefresh } = usePullToRefresh([['activity-week'], ['food-week'], ['me'], ['habits'], ['habit-streaks'], ['trends'], ['weight'], ['adaptive']]);
useFocusEffect(
React.useCallback(() => {
@@ -154,6 +155,9 @@ export default function ActivityScreen() {
+ {/* What you actually burn, and a suggested target */}
+
+
{/* Longer-range trends and weight */}
setShowWeight(true)} />
diff --git a/apps/mobile/app/(tabs)/food.tsx b/apps/mobile/app/(tabs)/food.tsx
index db3b1d9..cebcbea 100644
--- a/apps/mobile/app/(tabs)/food.tsx
+++ b/apps/mobile/app/(tabs)/food.tsx
@@ -19,6 +19,7 @@ import { addDaysStr, dayLabel, localDateStr } from '@/lib/date';
import { confirmAction } from '@/lib/confirm';
import { DateNavigator } from '@/components/ui/DateNavigator';
import { EditFoodSheet } from '@/components/food/EditFoodSheet';
+import { SmartLogSheet } from '@/components/food/SmartLogSheet';
import { useMe } from '@/hooks/useMe';
import { ErrorNotice, useQueriesStatus } from '@/components/ui/QueryStatus';
import { ScreenSkeleton } from '@/components/ui/Skeleton';
@@ -104,6 +105,7 @@ export default function FoodScreen() {
const { data: me } = useMe();
const { refreshing, onRefresh } = usePullToRefresh([['food-logs', date], ['me'], ['food-recent'], ['food-favorites']]);
const [editingLog, setEditingLog] = useState(null);
+ const [smartOpen, setSmartOpen] = useState(false);
const [selectedFood, setSelectedFood] = useState(null);
const [selectedMeal, setSelectedMeal] = useState<(typeof MEAL_ORDER)[number] | undefined>();
@@ -177,6 +179,19 @@ export default function FoodScreen() {
Food
+ setSmartOpen(true)}
+ style={({ pressed }) => ({
+ opacity: pressed ? 0.7 : 1,
+ height: 40, borderRadius: 12, paddingHorizontal: 12,
+ backgroundColor: Colors.surface,
+ borderWidth: 1, borderColor: `${Colors.orange}80`,
+ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 4,
+ })}
+ >
+ ✨
+ Smart log
+
router.push('/barcode-scanner' as never)}
style={({ pressed }) => ({
@@ -333,6 +348,7 @@ export default function FoodScreen() {
{selectedFood && (
setSelectedFood(null)} />
)}
+ {smartOpen && setSmartOpen(false)} />}
{editingLog && setEditingLog(null)} />}
);
diff --git a/apps/mobile/app/(tabs)/profile.tsx b/apps/mobile/app/(tabs)/profile.tsx
index 2cf179a..e9a27d9 100644
--- a/apps/mobile/app/(tabs)/profile.tsx
+++ b/apps/mobile/app/(tabs)/profile.tsx
@@ -7,6 +7,7 @@ import {
ActivityIndicator,
Linking,
RefreshControl,
+ Platform,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router, useFocusEffect } from 'expo-router';
@@ -138,14 +139,17 @@ function EditSheet({ user, onClose }: { user: BackendUser; onClose: () => void }
}
const SETTINGS_ROWS = [
- { icon: '🎯', color: Colors.orange, label: 'Goals & Targets', sub: 'Calories, macros and weight goal', href: '/settings/goals' as const },
- { icon: '🏋️', color: Colors.teal, label: 'Workout Plan', sub: 'Your weekly plan from the coach', href: '/plan' as const },
- { icon: '👥', color: Colors.orange, label: 'Friends', sub: 'Find people, requests and followers', href: '/friends' as const },
- { icon: '🔒', color: Colors.blue, label: 'Privacy', sub: 'Private account and blocked people', href: '/settings/privacy' as const },
- { icon: '🔔', color: Colors.blue, label: 'Notifications', sub: 'Reminders and alerts', href: '/settings/notifications' as const },
- { icon: '👤', color: Colors.muted, label: 'Account', sub: 'Units, password, delete account', href: '/settings/account' as const },
- { icon: '📊', color: Colors.teal, label: 'My Progress', sub: 'Weekly stats', href: '/(tabs)/activity' as const },
- { icon: '💬', color: Colors.muted, label: 'Help & Feedback', sub: 'Email support', href: null },
+ { icon: '🎯', color: 'orange' as const, label: 'Goals & Targets', sub: 'Calories, macros and weight goal', href: '/settings/goals' as const },
+ { icon: '🏋️', color: 'teal' as const, label: 'Workout Plan', sub: 'Your weekly plan from the coach', href: '/plan' as const },
+ { icon: '👥', color: 'orange' as const, label: 'Friends', sub: 'Find people, requests and followers', href: '/friends' as const },
+ { icon: '🔒', color: 'blue' as const, label: 'Privacy', sub: 'Private account and blocked people', href: '/settings/privacy' as const },
+ { icon: '❤️', color: 'error' as const, label: Platform.OS === 'android' ? 'Health Connect' : Platform.OS === 'ios' ? 'Apple Health' : 'Health data', sub: 'Sync workouts, steps, sleep and weight', href: '/settings/health' as const },
+ { icon: '🧠', color: 'teal' as const, label: 'What your coach knows', sub: 'Notes from your chats', href: '/settings/coach-memory' as const },
+ { icon: '✨', color: 'orange' as const, label: 'Foods GRIT knows', sub: 'Portions learned from Smart log', href: '/settings/foods' as const },
+ { icon: '🔔', color: 'blue' as const, label: 'Notifications', sub: 'Reminders and alerts', href: '/settings/notifications' as const },
+ { icon: '👤', color: 'muted' as const, label: 'Account', sub: 'Appearance, units, password, delete account', href: '/settings/account' as const },
+ { icon: '📊', color: 'teal' as const, label: 'My Progress', sub: 'Weekly stats', href: '/(tabs)/activity' as const },
+ { icon: '💬', color: 'muted' as const, label: 'Help & Feedback', sub: 'Email support', href: null },
];
export default function ProfileScreen() {
@@ -354,7 +358,7 @@ export default function ProfileScreen() {
gap: 14,
})}
>
-
+
{row.icon}
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index b025e5b..ce93dfa 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -1,5 +1,6 @@
import '../global.css';
-import React, { useEffect } from 'react';
+import React, { useEffect, useRef } from 'react';
+import { useColorScheme } from 'react-native';
import { Stack, SplashScreen, router, useSegments, usePathname } from 'expo-router';
import { QueryClientProvider } from '@tanstack/react-query';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
@@ -18,7 +19,10 @@ import { supabase } from '@/lib/supabase';
import { queryClient } from '@/lib/queryClient';
import { useAuthStore } from '@/stores/authStore';
import { usePushNotifications } from '@/hooks/usePushNotifications';
+import { useHealthSync } from '@/hooks/useHealthSync';
import { Toast } from '@/components/ui/Toast';
+import { Colors, applyColorScheme } from '@/constants/colors';
+import { useThemeStore } from '@/stores/themeStore';
import { OfflineBanner } from '@/components/ui/OfflineBanner';
import { CrashScreen } from '@/components/ui/CrashScreen';
import { installGlobalCrashHandler, setCrashScreen } from '@/lib/crashReporter';
@@ -37,6 +41,38 @@ export default function RootLayout() {
useEffect(() => setCrashScreen(pathname), [pathname]);
// Register for push only once signed in; the backend rejects anonymous calls
usePushNotifications(!!session);
+ // Pulls new workouts, steps, sleep and weigh-ins from the health app, if connected
+ useHealthSync(!!session);
+
+ // Theme: the saved choice, or the phone's setting. Colors answers from the
+ // current palette, so set it before anything below renders.
+ const systemScheme = useColorScheme();
+ const { preference, loaded: themeLoaded, load: loadTheme } = useThemeStore();
+ useEffect(() => { loadTheme(); }, [loadTheme]);
+ const scheme = preference === 'system' ? (systemScheme === 'light' ? 'light' : 'dark') : preference;
+ applyColorScheme(scheme);
+
+ // Screens are memoised by the navigator, so a theme change redraws them by
+ // remounting the stack (keyed on the scheme), then reopens the screen the
+ // user was on
+ const schemeRef = useRef(scheme);
+ const pathRef = useRef(pathname);
+ const restoreTo = useRef(null);
+ if (schemeRef.current !== scheme) {
+ restoreTo.current = pathRef.current;
+ schemeRef.current = scheme;
+ } else if (!restoreTo.current) {
+ pathRef.current = pathname;
+ }
+ useEffect(() => {
+ const path = restoreTo.current;
+ if (!path) return;
+ const timer = setTimeout(() => {
+ restoreTo.current = null;
+ if (path !== '/') router.replace(path as never);
+ }, 0);
+ return () => clearTimeout(timer);
+ }, [scheme]);
const [fontsLoaded, fontError] = useFonts({
'DMSans-Regular': DMSans_400Regular,
@@ -93,21 +129,21 @@ export default function RootLayout() {
// screen (which signs in from its link); anything else sends them to one of
// the first two
const ready = !isLoading && !onboardingLoading && fontsReady;
- const publicRoute = segments[0] === 'onboarding' || segments[0] === '(auth)' || segments[0] === 'reset-password';
+ const publicRoute = segments[0] === 'onboarding' || segments[0] === '(auth)' || segments[0] === 'reset-password' || segments[0] === 'auth-callback';
useEffect(() => {
if (!ready || session || publicRoute) return;
router.replace(onboardingComplete ? '/(auth)/login' : '/onboarding');
}, [ready, session, publicRoute, onboardingComplete]);
- if (isLoading || onboardingLoading || !fontsReady) {
+ if (isLoading || onboardingLoading || !fontsReady || !themeLoaded) {
return null;
}
return (
-
-
+
+
@@ -120,10 +156,12 @@ export default function RootLayout() {
+
+
diff --git a/apps/mobile/app/auth-callback.tsx b/apps/mobile/app/auth-callback.tsx
new file mode 100644
index 0000000..4af6b67
--- /dev/null
+++ b/apps/mobile/app/auth-callback.tsx
@@ -0,0 +1,44 @@
+import React, { useEffect, useState } from 'react';
+import { View, Text, ActivityIndicator } from 'react-native';
+import { router } from 'expo-router';
+import * as Linking from 'expo-linking';
+import { Colors } from '@/constants/colors';
+import { completeFromUrl } from '@/lib/socialAuth';
+import { afterSignIn } from '@/lib/postSignIn';
+import { Button } from '@/components/ui/Button';
+
+/**
+ * Where Google or Apple sign-in returns on web (and on phones if the app is
+ * opened from the link). Exchanges the code for a session, then carries on.
+ */
+export default function AuthCallbackScreen() {
+ const url = Linking.useURL();
+ const [problem, setProblem] = useState(null);
+
+ useEffect(() => {
+ if (!url) return;
+ completeFromUrl(url)
+ .then(async (session) => {
+ await afterSignIn(session);
+ router.replace('/(tabs)/');
+ })
+ .catch((err: Error) => setProblem(err.message));
+ }, [url]);
+
+ return (
+
+ {problem ? (
+ <>
+ Couldn't sign you in
+ {problem}
+ router.replace('/(auth)/login')} />
+ >
+ ) : (
+ <>
+
+ Signing you in…
+ >
+ )}
+
+ );
+}
diff --git a/apps/mobile/app/barcode-scanner.tsx b/apps/mobile/app/barcode-scanner.tsx
index bb4f842..8d41b4f 100644
--- a/apps/mobile/app/barcode-scanner.tsx
+++ b/apps/mobile/app/barcode-scanner.tsx
@@ -9,6 +9,7 @@ import { LogFoodSheet } from '@/components/food/LogFoodSheet';
import { Colors } from '@/constants/colors';
export default function BarcodeScannerScreen() {
+ const styles = makeStyles();
const [permission, requestPermission] = useCameraPermissions();
const [scannedCode, setScannedCode] = useState(null);
const [showSheet, setShowSheet] = useState(false);
@@ -154,7 +155,8 @@ const CORNER_SIZE = 24;
const CORNER_THICKNESS = 3;
const CORNER_COLOR = Colors.orange;
-const styles = StyleSheet.create({
+// Built during render, so it follows the current theme
+const makeStyles = () => StyleSheet.create({
container: { flex: 1, backgroundColor: Colors.dark },
overlay: {
flex: 1,
diff --git a/apps/mobile/app/coach.tsx b/apps/mobile/app/coach.tsx
index c0e3237..cf5b9a2 100644
--- a/apps/mobile/app/coach.tsx
+++ b/apps/mobile/app/coach.tsx
@@ -13,7 +13,8 @@ import { Colors } from '@/constants/colors';
interface LocalMessage {
id: string;
- role: 'user' | 'assistant';
+ /** note: what the coach just took down to remember */
+ role: 'user' | 'assistant' | 'note';
content: string;
}
@@ -25,6 +26,7 @@ export default function CoachScreen() {
const [localMessages, setLocalMessages] = useState([]);
const [streamingContent, setStreamingContent] = useState('');
const scrollRef = useRef(null);
+ const pendingNote = useRef(null);
// Sync history into local messages once loaded
useEffect(() => {
@@ -56,13 +58,16 @@ export default function CoachScreen() {
scrollToBottom();
},
() => {
+ // Any note the coach took shows under its reply
+ const note = pendingNote.current;
+ pendingNote.current = null;
setStreamingContent((prev) => {
- if (prev) {
- setLocalMessages((msgs) => [
- ...msgs,
- { id: `local-a-${Date.now()}`, role: 'assistant', content: prev },
- ]);
- }
+ const now = Date.now();
+ setLocalMessages((msgs) => [
+ ...msgs,
+ ...(prev ? [{ id: `local-a-${now}`, role: 'assistant' as const, content: prev }] : []),
+ ...(note ? [{ id: `local-n-${now}`, role: 'note' as const, content: note }] : []),
+ ]);
return '';
});
scrollToBottom();
@@ -73,6 +78,9 @@ export default function CoachScreen() {
{ id: `local-err-${Date.now()}`, role: 'assistant', content: `Sorry, something went wrong: ${err}` },
]);
},
+ (items) => {
+ pendingNote.current = items.join(' · ');
+ },
);
}
@@ -116,6 +124,15 @@ export default function CoachScreen() {
10 messages / day
+ router.push('/settings/coach-memory')}
+ accessibilityRole="button"
+ accessibilityLabel="What your coach remembers"
+ hitSlop={8}
+ style={{ width: 36, height: 36, borderRadius: 12, backgroundColor: Colors.surface, borderWidth: 1, borderColor: Colors.border, alignItems: 'center', justifyContent: 'center' }}
+ >
+ 🧠
+
{/* Messages */}
@@ -147,7 +164,23 @@ export default function CoachScreen() {
) : (
- displayMessages.map((msg) => )
+ displayMessages.map((msg) =>
+ msg.role === 'note' ? (
+ router.push('/settings/coach-memory')}
+ accessibilityRole="button"
+ accessibilityLabel={`Coach noted: ${msg.content}. Manage what your coach remembers`}
+ style={{ alignSelf: 'center', marginBottom: 12, paddingHorizontal: 12, paddingVertical: 6, borderRadius: 999, backgroundColor: Colors.surface2, maxWidth: '90%' }}
+ >
+
+ 🧠 Noted: {msg.content}
+
+
+ ) : (
+
+ ),
+ )
)}
{/* Live streaming bubble */}
diff --git a/apps/mobile/app/notifications.tsx b/apps/mobile/app/notifications.tsx
index 8e992e9..ee36a87 100644
--- a/apps/mobile/app/notifications.tsx
+++ b/apps/mobile/app/notifications.tsx
@@ -16,6 +16,7 @@ const ICONS: Record = {
challenge_joined: '🏆',
streak_at_risk: '🔥',
weekly_progress: '📊',
+ coach_checkin: '🤖',
kudos: '👏',
};
diff --git a/apps/mobile/app/onboarding/signup.tsx b/apps/mobile/app/onboarding/signup.tsx
index 01e0683..6178d68 100644
--- a/apps/mobile/app/onboarding/signup.tsx
+++ b/apps/mobile/app/onboarding/signup.tsx
@@ -6,6 +6,7 @@ import { Colors } from '../../constants/colors';
import { useAuthStore } from '../../stores/authStore';
import { supabase } from '../../lib/supabase';
import { syncOnboardingProfile } from '../../lib/onboardingProfile';
+import { SocialSignIn } from '../../components/auth/SocialSignIn';
export default function SignupScreen() {
const [email, setEmail] = useState('');
@@ -137,6 +138,9 @@ export default function SignupScreen() {
+ {/* Google and Apple: the answers above are saved after signing in */}
+
+
Already have an account?
diff --git a/apps/mobile/app/profile/[id].tsx b/apps/mobile/app/profile/[id].tsx
index efa7dc2..17479bc 100644
--- a/apps/mobile/app/profile/[id].tsx
+++ b/apps/mobile/app/profile/[id].tsx
@@ -24,13 +24,14 @@ const GOAL_LABELS: Record = {
just_track: 'Just tracking',
};
-const card = {
+/** Read during render, so it follows the current theme */
+const card = () => ({
backgroundColor: Colors.surface,
borderRadius: 20,
padding: 16,
borderWidth: 1,
borderColor: Colors.border,
-} as const;
+} as const);
export default function ProfileScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
@@ -104,7 +105,7 @@ export default function ProfileScreen() {
{menuOpen && (
-
+
{rel?.followsYou === 'accepted' && (
Remove follower
@@ -137,7 +138,7 @@ export default function ProfileScreen() {
{rel?.blocked ? (
-
+
You blocked {name}
Unblock them to see their profile again. You'll need to follow each other again.
@@ -154,7 +155,7 @@ export default function ProfileScreen() {
) : (
<>
{/* Counts */}
-
+
{([
{ label: 'Followers', value: profile._count.followers, which: 'followers' },
{ label: 'Following', value: profile._count.following, which: 'following' },
@@ -175,7 +176,7 @@ export default function ProfileScreen() {
{/* They asked to follow you */}
{rel?.followsYou === 'pending' && (
-
+
{name} wants to follow you.
accept(profile.id)} disabled={accepting} accessibilityRole="button" style={{ flex: 1, backgroundColor: Colors.orange, borderRadius: 999, paddingVertical: 10, alignItems: 'center' }}>
@@ -199,7 +200,7 @@ export default function ProfileScreen() {
)}
{!profile.canView ? (
-
+
🔒
This account is private
@@ -211,7 +212,7 @@ export default function ProfileScreen() {
) : (
<>
{profile.week && (
-
+
{[
{ label: 'Active min', value: profile.week.activeMinutes },
{ label: 'Workouts', value: profile.week.workouts },
diff --git a/apps/mobile/app/settings/account.tsx b/apps/mobile/app/settings/account.tsx
index d66e156..1478d9e 100644
--- a/apps/mobile/app/settings/account.tsx
+++ b/apps/mobile/app/settings/account.tsx
@@ -8,6 +8,7 @@ import { api } from '@/lib/api';
import { removeAvatarFile } from '@/lib/avatar';
import { supabase } from '@/lib/supabase';
import { signOut } from '@/lib/session';
+import { useThemeStore } from '@/stores/themeStore';
import { confirmAction, notify } from '@/lib/confirm';
import { sendPasswordReset } from '@/lib/passwordReset';
import { useAuthStore } from '@/stores/authStore';
@@ -16,6 +17,8 @@ import { ChipGroup, FieldLabel, NavRow, ScreenHeader, Section } from '@/componen
export default function AccountScreen() {
const { data: me } = useMe();
+ const themePreference = useThemeStore((s) => s.preference);
+ const setThemePreference = useThemeStore((s) => s.setPreference);
const { mutate: save } = useUpdateMe();
const email = useAuthStore((s) => s.user?.email);
const [busy, setBusy] = useState(false);
@@ -66,6 +69,18 @@ export default function AccountScreen() {
{email ?? '—'}
+
+
{me && (
diff --git a/apps/mobile/app/settings/coach-memory.tsx b/apps/mobile/app/settings/coach-memory.tsx
new file mode 100644
index 0000000..0468620
--- /dev/null
+++ b/apps/mobile/app/settings/coach-memory.tsx
@@ -0,0 +1,102 @@
+import React, { useState } from 'react';
+import { ScrollView, Text, View, Pressable, ActivityIndicator, TextInput } from 'react-native';
+import { SafeAreaView } from 'react-native-safe-area-context';
+import { Colors } from '@/constants/colors';
+import { ScreenHeader, Section } from '@/components/settings/SettingsUI';
+import { ErrorNotice } from '@/components/ui/QueryStatus';
+import {
+ useAddCoachMemory, useClearCoachMemories, useCoachMemories, useDeleteCoachMemory,
+} from '@/hooks/useAICoach';
+import { confirmAction, notify } from '@/lib/confirm';
+
+/** The notes the coach keeps between chats: see them, add your own, delete any. */
+export default function CoachMemoryScreen() {
+ const { data, isLoading, isError, refetch } = useCoachMemories();
+ const { mutateAsync: add, isPending: adding } = useAddCoachMemory();
+ const { mutate: remove } = useDeleteCoachMemory();
+ const { mutate: clear } = useClearCoachMemories();
+ const [text, setText] = useState('');
+
+ async function handleAdd() {
+ const note = text.trim();
+ if (note.length < 3) return;
+ try {
+ await add(note);
+ setText('');
+ } catch (err: any) {
+ notify("Couldn't add that", err?.response?.data?.message?.toString() ?? 'Check your connection and try again.');
+ }
+ }
+
+ async function handleClear() {
+ const ok = await confirmAction({
+ title: 'Forget everything?',
+ message: 'Your coach will lose every note, including ones you wrote. Your chat history stays.',
+ confirmLabel: 'Forget all',
+ destructive: true,
+ });
+ if (ok) clear();
+ }
+
+ return (
+
+
+
+
+
+
+ = 3 ? Colors.orange : Colors.border }}
+ >
+ {adding ? : Add}
+
+
+
+
+ {isError && !data ? (
+ refetch()} />
+ ) : isLoading ? (
+
+ ) : !data?.length ? (
+
+ No notes yet. Chat with your coach, or add one above.
+
+ ) : (
+ <>
+
+ {data.map((m) => (
+
+
+ {m.text}
+
+ {m.source === 'user' ? 'Added by you' : 'From a chat'} · {new Date(m.createdAt).toLocaleDateString()}
+
+
+ remove(m.id)} accessibilityRole="button" accessibilityLabel={`Delete note: ${m.text}`} hitSlop={8}>
+ Delete
+
+
+ ))}
+
+
+ Forget everything
+
+ >
+ )}
+
+
+ );
+}
diff --git a/apps/mobile/app/settings/foods.tsx b/apps/mobile/app/settings/foods.tsx
new file mode 100644
index 0000000..1229e21
--- /dev/null
+++ b/apps/mobile/app/settings/foods.tsx
@@ -0,0 +1,57 @@
+import React from 'react';
+import { ScrollView, Text, View, Pressable, ActivityIndicator } from 'react-native';
+import { SafeAreaView } from 'react-native-safe-area-context';
+import { Colors } from '@/constants/colors';
+import { ScreenHeader, Section } from '@/components/settings/SettingsUI';
+import { ErrorNotice } from '@/components/ui/QueryStatus';
+import { useFoodMemories, useForgetFood } from '@/hooks/useSmartLog';
+import { confirmAction } from '@/lib/confirm';
+
+/** The foods smart log has learned from what you confirmed, and a way to forget them. */
+export default function FoodMemoryScreen() {
+ const { data, isLoading, isError, refetch } = useFoodMemories();
+ const { mutate: forget } = useForgetFood();
+
+ async function handleForget(id: string, name: string) {
+ const ok = await confirmAction({
+ title: `Forget ${name}?`,
+ message: 'Smart log will estimate it again next time, until you confirm a new portion.',
+ confirmLabel: 'Forget',
+ destructive: true,
+ });
+ if (ok) forget(id);
+ }
+
+ return (
+
+
+
+ {isError && !data ? (
+ refetch()} />
+ ) : isLoading ? (
+
+ ) : !data?.length ? (
+
+ ) : (
+
+ {data.map((m) => (
+
+
+ {m.name}
+
+ Usually {Math.round(m.usualGrams)} g · {Math.round(m.kcalPer100g)} kcal per 100 g · logged {m.uses}×
+
+
+ handleForget(m.id, m.name)} accessibilityRole="button" accessibilityLabel={`Forget ${m.name}`} hitSlop={8}>
+ Forget
+
+
+ ))}
+
+ )}
+
+
+ );
+}
diff --git a/apps/mobile/app/settings/health.tsx b/apps/mobile/app/settings/health.tsx
new file mode 100644
index 0000000..f702ce4
--- /dev/null
+++ b/apps/mobile/app/settings/health.tsx
@@ -0,0 +1,131 @@
+import React, { useCallback, useEffect, useState } from 'react';
+import { ScrollView, Text, View, Platform, Linking, ActivityIndicator } from 'react-native';
+import { SafeAreaView } from 'react-native-safe-area-context';
+import { Colors } from '@/constants/colors';
+import { ScreenHeader, Section, ToggleRow, NavRow, PrimaryButton } from '@/components/settings/SettingsUI';
+import { healthSource } from '@/lib/health/source';
+import { connectHealth, disconnectHealth, isHealthSyncOn, lastHealthSync, syncHealth } from '@/lib/health/sync';
+import { useHealthRecent } from '@/hooks/useHealthRecent';
+import { dayLabel } from '@/lib/date';
+import { confirmAction, notify } from '@/lib/confirm';
+import { showToast } from '@/stores/toastStore';
+
+function timeAgo(d: Date | null) {
+ if (!d) return 'Never';
+ const mins = Math.round((Date.now() - d.getTime()) / 60000);
+ if (mins < 1) return 'Just now';
+ if (mins < 60) return `${mins} min ago`;
+ const hrs = Math.round(mins / 60);
+ return hrs < 24 ? `${hrs} h ago` : d.toLocaleDateString();
+}
+
+/** Connect Apple Health or Health Connect and see what's been synced. */
+export default function HealthSettingsScreen() {
+ const [available, setAvailable] = useState(null);
+ const [on, setOn] = useState(false);
+ const [last, setLast] = useState(null);
+ const [syncing, setSyncing] = useState(false);
+ const recent = useHealthRecent();
+
+ const refresh = useCallback(async () => {
+ setAvailable(await healthSource.isAvailable());
+ setOn(await isHealthSyncOn());
+ setLast(await lastHealthSync());
+ }, []);
+ useEffect(() => { refresh(); }, [refresh]);
+
+ async function runSync() {
+ setSyncing(true);
+ try {
+ const result = await syncHealth({ force: true });
+ if (result) {
+ const w = result.workouts.created;
+ showToast(`Synced: ${w} new ${w === 1 ? 'workout' : 'workouts'}, ${result.days} days, ${result.weights} weigh-ins`, 'info');
+ }
+ await refresh();
+ } catch (err) {
+ notify("Couldn't sync", (err as Error).message ?? 'Try again in a moment.');
+ } finally {
+ setSyncing(false);
+ }
+ }
+
+ async function toggle(value: boolean) {
+ if (value) {
+ const ok = await connectHealth();
+ if (!ok) {
+ notify(`Couldn't connect ${healthSource.name}`, Platform.OS === 'android'
+ ? 'Allow GRIT in Health Connect, then try again.'
+ : 'Allow GRIT in the Health app (Sharing → Apps), then try again.');
+ return;
+ }
+ setOn(true);
+ await runSync();
+ } else {
+ const ok = await confirmAction({
+ title: `Stop syncing ${healthSource.name}?`,
+ message: 'Workouts, steps and weigh-ins already imported stay in GRIT.',
+ confirmLabel: 'Stop syncing',
+ });
+ if (!ok) return;
+ await disconnectHealth();
+ await refresh();
+ }
+ }
+
+ const name = healthSource.name;
+ return (
+
+
+
+ {Platform.OS === 'web' ? (
+
+
+ Apple Health and Health Connect sync from the GRIT iOS and Android apps. What they import shows up here too.
+
+
+ ) : available === null ? (
+
+ ) : !available ? (
+
+ {name} isn't available on this phone.
+ {Platform.OS === 'android' && (
+ Linking.openURL('market://details?id=com.google.android.apps.healthdata')} />
+ )}
+
+ ) : (
+ <>
+
+ {on && }
+ >
+ )}
+
+
+ {recent.isLoading ? (
+
+ ) : (recent.data?.days ?? []).length === 0 ? (
+ Nothing synced in the last week.
+ ) : (
+ <>
+ {[...recent.data!.days].reverse().map((d) => (
+
+ {dayLabel(d.date)}
+
+ {d.steps != null ? `${d.steps.toLocaleString()} steps` : ''}
+ {d.steps != null && d.sleepMinutes != null ? ' · ' : ''}
+ {d.sleepMinutes != null ? `${Math.floor(d.sleepMinutes / 60)}h ${d.sleepMinutes % 60}m sleep` : ''}
+
+
+ ))}
+
+ {recent.data!.importedWorkouts} imported {recent.data!.importedWorkouts === 1 ? 'workout' : 'workouts'} in total
+
+ >
+ )}
+
+
+
+ );
+}
diff --git a/apps/mobile/components/auth/SocialSignIn.tsx b/apps/mobile/components/auth/SocialSignIn.tsx
new file mode 100644
index 0000000..2a4d6ac
--- /dev/null
+++ b/apps/mobile/components/auth/SocialSignIn.tsx
@@ -0,0 +1,90 @@
+import React, { useEffect, useState } from 'react';
+import { View, Text, Pressable, Platform, ActivityIndicator } from 'react-native';
+import * as AppleAuthentication from 'expo-apple-authentication';
+import { router } from 'expo-router';
+import { Colors, colorScheme } from '@/constants/colors';
+import { enabledProviders, signInWithProvider, type Provider } from '@/lib/socialAuth';
+import { afterSignIn } from '@/lib/postSignIn';
+import { notify } from '@/lib/confirm';
+
+/**
+ * "Continue with Apple / Google". Only providers switched on in Supabase are
+ * shown, so nothing appears until they're configured. On iOS the Apple
+ * button is Apple's own, as App Review expects.
+ */
+export function SocialSignIn({ dividerLabel = 'or' }: { dividerLabel?: string }) {
+ const [providers, setProviders] = useState([]);
+ const [busy, setBusy] = useState(null);
+ const [nativeApple, setNativeApple] = useState(false);
+
+ useEffect(() => {
+ enabledProviders().then(setProviders);
+ if (Platform.OS === 'ios') AppleAuthentication.isAvailableAsync().then(setNativeApple).catch(() => {});
+ }, []);
+
+ if (providers.length === 0) return null;
+
+ async function go(provider: Provider) {
+ setBusy(provider);
+ try {
+ const session = await signInWithProvider(provider);
+ if (!session) return; // cancelled, or the web page is redirecting
+ await afterSignIn(session);
+ router.replace('/(tabs)/');
+ } catch (err) {
+ notify("Couldn't sign in", (err as Error).message ?? 'Please try again.');
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ const light = colorScheme() === 'light';
+ return (
+
+
+
+ {dividerLabel}
+
+
+
+ {providers.includes('apple') && (nativeApple ? (
+ go('apple')}
+ />
+ ) : (
+ go('apple')} dark={!light} />
+ ))}
+ {providers.includes('google') && (
+ go('google')} />
+ )}
+
+ );
+}
+
+function ProviderButton({ label, icon, busy, disabled, onPress, dark }: { label: string; icon: string; busy: boolean; disabled: boolean; onPress: () => void; dark?: boolean }) {
+ const bg = dark ? '#FFFFFF' : Colors.surface;
+ const fg = dark ? '#000000' : Colors.text;
+ return (
+ ({
+ height: 52, borderRadius: 999, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 10,
+ backgroundColor: bg, borderWidth: 1, borderColor: Colors.border, opacity: disabled && !busy ? 0.5 : pressed ? 0.85 : 1,
+ })}
+ >
+ {busy ? : (
+ <>
+ {!!icon && {icon}}
+ {label}
+ >
+ )}
+
+ );
+}
diff --git a/apps/mobile/components/food/EditFoodSheet.tsx b/apps/mobile/components/food/EditFoodSheet.tsx
index 4ae5c93..a3108f0 100644
--- a/apps/mobile/components/food/EditFoodSheet.tsx
+++ b/apps/mobile/components/food/EditFoodSheet.tsx
@@ -11,7 +11,8 @@ import { Colors } from '@/constants/colors';
const MEALS = ['breakfast', 'lunch', 'dinner', 'snack'] as const;
-const fieldStyle = {
+/** Read during render, so it follows the current theme */
+const fieldStyle = () => ({
backgroundColor: Colors.surface2,
borderRadius: 14,
padding: 12,
@@ -20,7 +21,7 @@ const fieldStyle = {
fontSize: 16,
borderWidth: 1.5,
borderColor: Colors.border,
-} as const;
+} as const);
const round1 = (n: number) => String(Math.round(n * 10) / 10);
const parse = (s: string) => (s.trim() === '' ? NaN : Number(s));
@@ -72,7 +73,7 @@ export function EditFoodSheet({ log, onClose }: { log: FoodLog; onClose: () => v
value={values[key]}
onChangeText={(t) => setValues((v) => ({ ...v, [key]: t.replace(/[^0-9.]/g, '') }))}
keyboardType="decimal-pad"
- style={fieldStyle}
+ style={fieldStyle()}
accessibilityLabel={label}
/>
@@ -96,7 +97,7 @@ export function EditFoodSheet({ log, onClose }: { log: FoodLog; onClose: () => v
onChangeText={setName}
placeholder="Food name"
placeholderTextColor={Colors.muted}
- style={{ ...fieldStyle, fontFamily: 'DMSans-Regular' }}
+ style={{ ...fieldStyle(), fontFamily: 'DMSans-Regular' }}
accessibilityLabel="Food name"
/>
diff --git a/apps/mobile/components/food/LogFoodSheet.tsx b/apps/mobile/components/food/LogFoodSheet.tsx
index f19541b..3af75e3 100644
--- a/apps/mobile/components/food/LogFoodSheet.tsx
+++ b/apps/mobile/components/food/LogFoodSheet.tsx
@@ -17,7 +17,8 @@ import { loggedAtFor } from '@/lib/date';
const MEAL_TYPES = ['breakfast', 'lunch', 'dinner', 'snack'] as const;
-const fieldStyle = {
+/** Read during render, so it follows the current theme */
+const fieldStyle = () => ({
backgroundColor: Colors.surface2,
borderRadius: 16,
padding: 12,
@@ -26,7 +27,7 @@ const fieldStyle = {
fontSize: 16,
borderWidth: 1.5,
borderColor: Colors.border,
-} as const;
+} as const);
type MealType = typeof MEAL_TYPES[number];
interface LogFoodSheetProps {
@@ -136,7 +137,7 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP
{isManual ? (
setManual((m) => ({ ...m, [key]: v }))}
keyboardType="decimal-pad"
diff --git a/apps/mobile/components/food/SmartLogSheet.tsx b/apps/mobile/components/food/SmartLogSheet.tsx
new file mode 100644
index 0000000..e42d46f
--- /dev/null
+++ b/apps/mobile/components/food/SmartLogSheet.tsx
@@ -0,0 +1,308 @@
+import React, { useRef, useState } from 'react';
+import { View, Text, Pressable, Image, Platform, ActivityIndicator } from 'react-native';
+import BottomSheet, { BottomSheetScrollView } from '@gorhom/bottom-sheet';
+import * as Haptics from 'expo-haptics';
+import * as ImagePicker from 'expo-image-picker';
+import { manipulateAsync, SaveFormat } from 'expo-image-manipulator';
+import { SheetTextInput, sheetKeyboardProps } from '@/components/ui/SheetTextInput';
+import { Button } from '@/components/ui/Button';
+import { useLogParsedMeal, useParseMeal, type ItemSource, type ParsedItem } from '@/hooks/useSmartLog';
+import { useHideTabBar } from '@/stores/uiStore';
+import { notify } from '@/lib/confirm';
+import { showToast } from '@/stores/toastStore';
+import { loggedAtFor } from '@/lib/date';
+import { MEALS, mealForHour, type Meal } from '@/lib/meals';
+import { Colors } from '@/constants/colors';
+
+
+/** Photos are shrunk before upload: plenty for the model, a few hundred kB. */
+const PHOTO_WIDTH = 1024;
+
+const SOURCE_LABELS: Record string }> = {
+ memory: { label: 'Your usual', color: () => Colors.teal },
+ database: { label: 'Food database', color: () => Colors.blue },
+ estimate: { label: 'Estimate', color: () => Colors.muted },
+};
+
+/** Read during render, so it follows the current theme */
+const fieldStyle = () => ({
+ backgroundColor: Colors.surface2,
+ borderRadius: 14,
+ padding: 12,
+ color: Colors.text,
+ fontFamily: 'DMSans-Regular',
+ fontSize: 15,
+ borderWidth: 1.5,
+ borderColor: Colors.border,
+} as const);
+
+interface Row extends ParsedItem {
+ key: string;
+ /** The grams as typed, so the field can be cleared while editing */
+ gramsText: string;
+}
+
+const kcalFor = (row: Row) => Math.round((row.per100.kcal * (parseFloat(row.gramsText) || 0)) / 100);
+const errorText = (err: any, fallback: string) => err?.response?.data?.message?.toString() ?? fallback;
+
+/**
+ * Log a meal by describing it (typed or dictated with the keyboard's mic) or
+ * from a photo. Every item is shown with where its numbers came from and can
+ * be adjusted or removed before anything is logged.
+ */
+export function SmartLogSheet({ date, initialMeal, onClose }: { date?: string; initialMeal?: Meal; onClose: () => void }) {
+ const sheetRef = useRef(null);
+ useHideTabBar();
+ const { mutateAsync: parse, isPending: reading } = useParseMeal();
+ const { mutateAsync: logMeal, isPending: logging } = useLogParsedMeal();
+
+ const [text, setText] = useState('');
+ const [photo, setPhoto] = useState<{ uri: string; base64: string } | null>(null);
+ const [rows, setRows] = useState(null);
+ const [question, setQuestion] = useState(null);
+ const [answer, setAnswer] = useState('');
+ const [meal, setMeal] = useState(initialMeal ?? mealForHour(new Date().getHours()));
+
+ async function addPhoto(fromCamera: boolean) {
+ try {
+ if (fromCamera) {
+ const perm = await ImagePicker.requestCameraPermissionsAsync();
+ if (!perm.granted) {
+ notify('Camera is off', 'Allow camera access for GRIT in Settings, or choose a photo instead.');
+ return;
+ }
+ }
+ const options: ImagePicker.ImagePickerOptions = { mediaTypes: ['images'], quality: 1 };
+ const picked = fromCamera
+ ? await ImagePicker.launchCameraAsync(options)
+ : await ImagePicker.launchImageLibraryAsync(options);
+ if (picked.canceled || !picked.assets?.[0]) return;
+ const asset = picked.assets[0];
+ const resize = !asset.width || asset.width > PHOTO_WIDTH ? [{ resize: { width: PHOTO_WIDTH } }] : [];
+ const image = await manipulateAsync(asset.uri, resize, { compress: 0.7, format: SaveFormat.JPEG, base64: true });
+ if (!image.base64) throw new Error('Could not read that photo.');
+ setPhoto({ uri: image.uri, base64: image.base64 });
+ } catch (err: any) {
+ notify("Couldn't use that photo", err?.message ?? 'Try another one.');
+ }
+ }
+
+ async function read(extra?: string) {
+ const description = [text.trim(), extra?.trim()].filter(Boolean).join('\n');
+ if (!description && !photo) return;
+ try {
+ const result = await parse({
+ text: description || undefined,
+ imageBase64: photo?.base64,
+ imageType: photo ? 'image/jpeg' : undefined,
+ });
+ if (!result.items.length) {
+ notify('No food found', 'Try describing it in a few words, like "chicken salad and a cola".');
+ return;
+ }
+ if (extra) setText(description);
+ setAnswer('');
+ setQuestion(result.question);
+ setRows(result.items.map((item, i) => ({ ...item, key: `${i}-${item.name}`, gramsText: String(item.grams) })));
+ } catch (err: any) {
+ notify("Couldn't read that meal", errorText(err, 'Check your connection and try again.'));
+ }
+ }
+
+ async function handleLog() {
+ const items = (rows ?? []).filter((r) => (parseFloat(r.gramsText) || 0) > 0);
+ if (!items.length) return;
+ try {
+ const res = await logMeal({
+ mealType: meal,
+ loggedAt: date ? loggedAtFor(date) : undefined,
+ items: items.map((r) => ({
+ name: r.name,
+ brand: r.brand ?? undefined,
+ grams: Math.min(5000, parseFloat(r.gramsText)),
+ kcalPer100g: r.per100.kcal,
+ proteinPer100g: r.per100.protein,
+ carbsPer100g: r.per100.carbs,
+ fatPer100g: r.per100.fat,
+ })),
+ });
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
+ showToast(`${res.logged} item${res.logged === 1 ? '' : 's'} added to ${meal}. GRIT will remember these portions.`, 'info');
+ onClose();
+ } catch (err: any) {
+ notify("Couldn't log the meal", errorText(err, 'Check your connection and try again.'));
+ }
+ }
+
+ const setGrams = (key: string, value: string) =>
+ setRows((rs) => rs?.map((r) => (r.key === key ? { ...r, gramsText: value.replace(/[^0-9.]/g, '') } : r)) ?? null);
+ const removeRow = (key: string) => setRows((rs) => rs?.filter((r) => r.key !== key) ?? null);
+
+ const loggable = (rows ?? []).filter((r) => (parseFloat(r.gramsText) || 0) > 0);
+ const totalKcal = loggable.reduce((t, r) => t + kcalFor(r), 0);
+
+ const chip = (label: string, onPress: () => void, a11y: string) => (
+
+ {label}
+
+ );
+
+ return (
+
+
+
+ ✨ Smart log
+
+ {rows ? 'Check the portions, then log.' : 'Describe what you ate or snap a photo. You review everything before it’s logged.'}
+
+
+
+ {!rows ? (
+ <>
+
+ {Platform.OS !== 'web' && (
+
+ Rather say it? Tap the 🎤 on your keyboard.
+
+ )}
+
+ {photo ? (
+
+
+ setPhoto(null)} accessibilityRole="button" hitSlop={8}>
+ Remove photo
+
+
+ ) : (
+
+ {Platform.OS !== 'web' && chip('📷 Take photo', () => addPhoto(true), 'Take a photo of your meal')}
+ {chip('🖼️ Choose photo', () => addPhoto(false), 'Choose a photo of your meal')}
+
+ )}
+
+ read()} loading={reading} disabled={!text.trim() && !photo} />
+ >
+ ) : (
+ <>
+ {question && (
+
+ {question}
+
+
+ read(answer)}
+ disabled={!answer.trim() || reading}
+ accessibilityRole="button"
+ style={{ paddingHorizontal: 14, paddingVertical: 11, borderRadius: 12, backgroundColor: answer.trim() ? Colors.orange : Colors.border }}
+ >
+ {reading ? : Update}
+
+
+
+ )}
+
+
+ {rows.map((row) => {
+ const src = SOURCE_LABELS[row.source];
+ return (
+
+
+
+
+ {row.brand ? `${row.brand} ` : ''}{row.name}
+
+ {row.portion}
+
+ removeRow(row.key)} accessibilityRole="button" accessibilityLabel={`Remove ${row.name}`} hitSlop={10}>
+ ✕
+
+
+
+ setGrams(row.key, t)}
+ keyboardType="decimal-pad"
+ style={{ ...fieldStyle(), width: 84, paddingVertical: 8, fontFamily: 'JetBrainsMono-Regular' }}
+ accessibilityLabel={`Grams of ${row.name}`}
+ />
+ g
+
+ {kcalFor(row)} kcal
+
+
+
+
+
+ {src.label}{row.source === 'estimate' && row.confidence === 'low' ? ' · check the portion' : ''}
+
+
+
+ );
+ })}
+
+
+
+ Total
+
+ {totalKcal} kcal
+
+
+
+
+ {MEALS.map((m) => (
+ setMeal(m)}
+ accessibilityRole="radio"
+ aria-selected={meal === m}
+ style={{ paddingHorizontal: 14, paddingVertical: 8, borderRadius: 999, backgroundColor: meal === m ? Colors.orange : Colors.surface2, borderWidth: 1, borderColor: meal === m ? Colors.orange : Colors.border }}
+ >
+ {m}
+
+ ))}
+
+
+
+ { setRows(null); setQuestion(null); }} accessibilityRole="button" style={{ alignItems: 'center', paddingVertical: 4 }}>
+ Start over
+
+ >
+ )}
+
+
+ );
+}
diff --git a/apps/mobile/components/plan/EditPlanDaySheet.tsx b/apps/mobile/components/plan/EditPlanDaySheet.tsx
index 05beabf..e84d18d 100644
--- a/apps/mobile/components/plan/EditPlanDaySheet.tsx
+++ b/apps/mobile/components/plan/EditPlanDaySheet.tsx
@@ -11,7 +11,8 @@ import { Colors } from '@/constants/colors';
const MAX_EXERCISES = 12;
-const inputStyle = {
+/** Read during render, so it follows the current theme */
+const inputStyle = () => ({
backgroundColor: Colors.surface2,
borderRadius: 12,
borderWidth: 1,
@@ -21,7 +22,7 @@ const inputStyle = {
color: Colors.text,
fontFamily: 'DMSans-Regular',
fontSize: 14,
-} as const;
+} as const);
/** Edit one day of the plan by hand: rest or train, title, type, length and exercises. */
export function EditPlanDaySheet({ day, onClose }: { day: PlanDay; onClose: () => void }) {
@@ -81,7 +82,7 @@ export function EditPlanDaySheet({ day, onClose }: { day: PlanDay; onClose: () =
-
+
{!rest && (
<>
@@ -101,15 +102,15 @@ export function EditPlanDaySheet({ day, onClose }: { day: PlanDay; onClose: () =
Minutes
- setDuration(t.replace(/[^0-9]/g, ''))} keyboardType="number-pad" maxLength={3} style={{ ...inputStyle, width: 80, fontFamily: 'JetBrainsMono-Regular' }} accessibilityLabel="Minutes" />
+ setDuration(t.replace(/[^0-9]/g, ''))} keyboardType="number-pad" maxLength={3} style={{ ...inputStyle(), width: 80, fontFamily: 'JetBrainsMono-Regular' }} accessibilityLabel="Minutes" />
Exercises
{exercises.map((e, i) => (
- setExercise(i, { name: t })} placeholder="Exercise" placeholderTextColor={Colors.muted} maxLength={80} style={{ ...inputStyle, flex: 2 }} accessibilityLabel={`Exercise ${i + 1}`} />
- setExercise(i, { detail: t })} placeholder="3 × 12" placeholderTextColor={Colors.muted} maxLength={60} style={{ ...inputStyle, flex: 1 }} accessibilityLabel={`Sets for exercise ${i + 1}`} />
+ setExercise(i, { name: t })} placeholder="Exercise" placeholderTextColor={Colors.muted} maxLength={80} style={{ ...inputStyle(), flex: 2 }} accessibilityLabel={`Exercise ${i + 1}`} />
+ setExercise(i, { detail: t })} placeholder="3 × 12" placeholderTextColor={Colors.muted} maxLength={60} style={{ ...inputStyle(), flex: 1 }} accessibilityLabel={`Sets for exercise ${i + 1}`} />
setExercises((list) => list.filter((_, j) => j !== i))} hitSlop={8} accessibilityRole="button" accessibilityLabel={`Remove exercise ${i + 1}`}>
✕
diff --git a/apps/mobile/components/stats/AdaptiveCard.tsx b/apps/mobile/components/stats/AdaptiveCard.tsx
new file mode 100644
index 0000000..cb804f6
--- /dev/null
+++ b/apps/mobile/components/stats/AdaptiveCard.tsx
@@ -0,0 +1,108 @@
+import React from 'react';
+import { View, Text, Pressable } from 'react-native';
+import * as Haptics from 'expo-haptics';
+import { Colors } from '@/constants/colors';
+import { useAdaptive, useApplyTarget, useSnoozeTarget } from '@/hooks/useAdaptive';
+import { kgToUnit, type WeightUnit } from '@/lib/units';
+
+function Meter({ label, value, need }: { label: string; value: number; need: number }) {
+ const pct = Math.min(1, value / need);
+ return (
+
+
+ {label}
+ {Math.min(value, need)}/{need}
+
+
+ = 1 ? Colors.teal : Colors.orange, borderRadius: 3 }} />
+
+
+ );
+}
+
+const CONFIDENCE = { low: 'early estimate', medium: 'getting sharper', high: 'high confidence' } as const;
+
+/**
+ * Your real daily burn, worked out from what you logged and how your weight
+ * moved, and the coach's suggested target. Learns as you log.
+ */
+export function AdaptiveCard({ unit }: { unit: WeightUnit }) {
+ const { data } = useAdaptive();
+ const { mutate: apply, isPending: applying } = useApplyTarget();
+ const { mutate: snooze } = useSnoozeTarget();
+ if (!data) return null;
+
+ const { estimate: est, suggestion: s, progress: p } = data;
+ const card = { backgroundColor: Colors.surface, borderRadius: 20, borderWidth: 1, borderColor: Colors.border, padding: 18, marginBottom: 12, gap: 12 } as const;
+
+ if (!est) {
+ return (
+
+ Learning your metabolism
+
+ Log your food and weigh in a few times a week. GRIT will work out what you really burn and tune your target to it.
+
+
+
+
+
+ );
+ }
+
+ const trend = kgToUnit(Math.abs(est.trendKgPerWeek), unit);
+ const trendText = est.trendKgPerWeek < -0.05 ? `−${trend} ${unit}/wk` : est.trendKgPerWeek > 0.05 ? `+${trend} ${unit}/wk` : 'steady';
+ return (
+
+
+ Your metabolism
+
+ {CONFIDENCE[est.confidence]}
+
+
+
+ {[
+ { label: 'you burn / day', value: est.tdee.toLocaleString(), color: Colors.orange },
+ { label: 'you eat / day', value: est.avgIntake.toLocaleString(), color: Colors.text },
+ { label: 'weight trend', value: trendText, color: Colors.text },
+ ].map((x) => (
+
+ {x.value}
+ {x.label}
+
+ ))}
+
+
+ From {est.loggedDays} logged days and {est.weighIns} weigh-ins over {est.spanDays} days.
+
+
+ {s && (
+
+
+ Suggested target: {s.suggested.toLocaleString()} kcal (now {s.current.toLocaleString()})
+
+ {s.reason}
+
+ {
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
+ apply(s.suggested);
+ }}
+ disabled={applying}
+ accessibilityRole="button"
+ style={({ pressed }) => ({ flex: 1, backgroundColor: Colors.orange, borderRadius: 999, paddingVertical: 11, alignItems: 'center', opacity: applying ? 0.5 : pressed ? 0.85 : 1 })}
+ >
+ Use {s.suggested.toLocaleString()}
+
+ snooze()}
+ accessibilityRole="button"
+ style={({ pressed }) => ({ paddingHorizontal: 18, borderRadius: 999, paddingVertical: 11, alignItems: 'center', backgroundColor: Colors.surface2, opacity: pressed ? 0.7 : 1 })}
+ >
+ Not now
+
+
+
+ )}
+
+ );
+}
diff --git a/apps/mobile/components/stats/TrendsCard.tsx b/apps/mobile/components/stats/TrendsCard.tsx
index adc00a9..bf250c1 100644
--- a/apps/mobile/components/stats/TrendsCard.tsx
+++ b/apps/mobile/components/stats/TrendsCard.tsx
@@ -14,11 +14,11 @@ const RANGES: { value: TrendRange; label: string }[] = [
{ value: 30, label: '30D' },
{ value: 90, label: '3M' },
];
-const METRICS: { value: Metric; label: string; color: string }[] = [
- { value: 'calories', label: 'Calories', color: Colors.orange },
- { value: 'protein', label: 'Protein', color: Colors.blue },
- { value: 'activity', label: 'Activity', color: Colors.teal },
- { value: 'weight', label: 'Weight', color: Colors.orange },
+const METRICS: { value: Metric; label: string; color: 'orange' | 'blue' | 'teal' }[] = [
+ { value: 'calories', label: 'Calories', color: 'orange' },
+ { value: 'protein', label: 'Protein', color: 'blue' },
+ { value: 'activity', label: 'Activity', color: 'teal' },
+ { value: 'weight', label: 'Weight', color: 'orange' },
];
const CHART_H = 120;
@@ -142,7 +142,7 @@ export function TrendsCard({ unit, onLogWeight }: { unit: WeightUnit; onLogWeigh
const { data, isLoading, isError, refetch } = useTrends(range);
const weight = useWeightHistory(range === 90 ? 90 : 30);
const { mutate: deleteWeight } = useDeleteWeight();
- const color = METRICS.find((m) => m.value === metric)!.color;
+ const color = Colors[METRICS.find((m) => m.value === metric)!.color];
const weekly = range === 90;
const view = useMemo(() => {
diff --git a/apps/mobile/components/ui/Button.tsx b/apps/mobile/components/ui/Button.tsx
index cc8611f..a5454c0 100644
--- a/apps/mobile/components/ui/Button.tsx
+++ b/apps/mobile/components/ui/Button.tsx
@@ -72,15 +72,14 @@ const baseText = {
letterSpacing: 0.2,
};
+// Getters, so each read uses the current theme's colours
const styles = {
- primaryBg: { backgroundColor: Colors.orange },
- secondaryBg: {
- backgroundColor: 'transparent',
- borderWidth: 1.5,
- borderColor: Colors.orange,
+ get primaryBg() { return { backgroundColor: Colors.orange }; },
+ get secondaryBg() {
+ return { backgroundColor: 'transparent', borderWidth: 1.5, borderColor: Colors.orange };
},
ghostBg: { backgroundColor: 'transparent' },
primaryText: { color: '#fff' },
- secondaryText: { color: Colors.orange },
- ghostText: { color: Colors.muted },
+ get secondaryText() { return { color: Colors.orange }; },
+ get ghostText() { return { color: Colors.muted }; },
};
diff --git a/apps/mobile/constants/colors.ts b/apps/mobile/constants/colors.ts
index 2307422..01e4dc4 100644
--- a/apps/mobile/constants/colors.ts
+++ b/apps/mobile/constants/colors.ts
@@ -1,5 +1,15 @@
-export const Colors = {
+/**
+ * The app's colours, for a dark and a light theme.
+ *
+ * Screens read `Colors.x` while rendering, so `Colors` always answers from
+ * the current palette. When the theme changes, the root layout redraws the
+ * screens (see components/ThemeRoot.tsx). Don't copy a colour into a value
+ * computed once at module load; read it during render instead.
+ */
+
+const DARK = {
orange: '#FF5C2B',
+ /** Page background */
dark: '#0F0F0F',
surface: '#1A1A1C',
surface2: '#242428',
@@ -11,4 +21,48 @@ export const Colors = {
blue: '#4B9FFF',
border: '#2B2B30',
error: '#FF453A',
-} as const;
+};
+
+export type Palette = typeof DARK;
+export type ColorScheme = 'light' | 'dark';
+
+// Same roles, tuned for a light background: deeper accents keep text and
+// icons readable (muted text is 5:1 on white)
+const LIGHT: Palette = {
+ orange: '#EC5020',
+ dark: '#F6F4F1',
+ surface: '#FFFFFF',
+ surface2: '#F1EEEA',
+ surface3: '#E5E1DC',
+ text: '#1A1714',
+ muted: '#68625D',
+ teal: '#00957A',
+ success: '#00957A',
+ blue: '#2C75D6',
+ border: '#E2DDD7',
+ error: '#D93025',
+};
+
+let current: Palette = DARK;
+let currentScheme: ColorScheme = 'dark';
+
+export const Colors: Palette = new Proxy({} as Palette, {
+ get: (_target, key: string) => current[key as keyof Palette],
+ ownKeys: () => Reflect.ownKeys(current),
+ getOwnPropertyDescriptor: (_target, key) => ({
+ enumerable: true,
+ configurable: true,
+ value: current[key as keyof Palette],
+ }),
+});
+
+export function applyColorScheme(scheme: ColorScheme) {
+ current = scheme === 'light' ? LIGHT : DARK;
+ currentScheme = scheme;
+}
+
+export function colorScheme(): ColorScheme {
+ return currentScheme;
+}
+
+export const PALETTES = { dark: DARK, light: LIGHT } as const;
diff --git a/apps/mobile/hooks/useAICoach.ts b/apps/mobile/hooks/useAICoach.ts
index eee6e75..502aa2b 100644
--- a/apps/mobile/hooks/useAICoach.ts
+++ b/apps/mobile/hooks/useAICoach.ts
@@ -1,5 +1,5 @@
import { useState, useCallback } from 'react';
-import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
// React Native's global fetch can't stream response bodies; Expo's can
import { fetch } from 'expo/fetch';
import { api, authHeaders } from '@/lib/api';
@@ -53,6 +53,8 @@ export function useStreamMessage() {
onChunk: (text: string) => void,
onDone: () => void,
onError: (err: string) => void,
+ /** Notes the coach took from this message, to remember next time */
+ onRemembered?: (items: string[]) => void,
) => {
setIsStreaming(true);
@@ -101,9 +103,12 @@ export function useStreamMessage() {
if (!raw) continue;
try {
- const chunk = JSON.parse(raw) as { type: string; text?: string; error?: string };
+ const chunk = JSON.parse(raw) as { type: string; text?: string; error?: string; items?: string[] };
if (chunk.type === 'delta' && chunk.text) {
onChunk(chunk.text);
+ } else if (chunk.type === 'remembered' && chunk.items?.length) {
+ qc.invalidateQueries({ queryKey: ['coach-memories'] });
+ onRemembered?.(chunk.items);
} else if (chunk.type === 'done') {
onDone();
} else if (chunk.type === 'error') {
@@ -128,3 +133,41 @@ export function useStreamMessage() {
return { sendMessage, isStreaming };
}
+
+export interface CoachMemory {
+ id: string;
+ text: string;
+ source: 'chat' | 'user';
+ createdAt: string;
+}
+
+export function useCoachMemories() {
+ return useQuery({
+ queryKey: ['coach-memories'],
+ queryFn: () => api.get('/ai/memories').then((r) => r.data),
+ });
+}
+
+export function useAddCoachMemory() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (text: string) => api.post('/ai/memories', { text }).then((r) => r.data),
+ onSuccess: () => qc.invalidateQueries({ queryKey: ['coach-memories'] }),
+ });
+}
+
+export function useDeleteCoachMemory() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => api.delete(`/ai/memories/${id}`).then((r) => r.data),
+ onSuccess: () => qc.invalidateQueries({ queryKey: ['coach-memories'] }),
+ });
+}
+
+export function useClearCoachMemories() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: () => api.delete('/ai/memories').then((r) => r.data),
+ onSuccess: () => qc.invalidateQueries({ queryKey: ['coach-memories'] }),
+ });
+}
diff --git a/apps/mobile/hooks/useAdaptive.ts b/apps/mobile/hooks/useAdaptive.ts
new file mode 100644
index 0000000..e7a80cb
--- /dev/null
+++ b/apps/mobile/hooks/useAdaptive.ts
@@ -0,0 +1,53 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { api } from '@/lib/api';
+
+export interface AdaptiveCheckIn {
+ estimate: {
+ tdee: number;
+ confidence: 'low' | 'medium' | 'high';
+ loggedDays: number;
+ weighIns: number;
+ spanDays: number;
+ trendKgPerWeek: number;
+ avgIntake: number;
+ } | null;
+ suggestion: { current: number; suggested: number; change: number; ideal: number; reason: string } | null;
+ formulaTdee: number | null;
+ progress: {
+ loggedDays: number;
+ weighIns: number;
+ spanDays: number;
+ needs: { loggedDays: number; weighIns: number; spanDays: number };
+ };
+ snoozedUntil: string | null;
+}
+
+/** Estimated burn from what you ate and how your weight moved, and a suggested target. */
+export function useAdaptive() {
+ return useQuery({
+ queryKey: ['adaptive'],
+ queryFn: () => api.get('/targets/adaptive').then((r) => r.data),
+ staleTime: 10 * 60_000,
+ });
+}
+
+function refresh(qc: ReturnType) {
+ for (const key of ['adaptive', 'me', 'food-logs', 'trends', 'ai-nudge']) qc.invalidateQueries({ queryKey: [key] });
+}
+
+export function useApplyTarget() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (calorieGoal: number) => api.post('/targets/adaptive/apply', { calorieGoal }).then((r) => r.data),
+ meta: { errorMessage: "Couldn't update your target. Check your connection." },
+ onSuccess: () => refresh(qc),
+ });
+}
+
+export function useSnoozeTarget() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: () => api.post('/targets/adaptive/snooze').then((r) => r.data),
+ onSuccess: () => qc.invalidateQueries({ queryKey: ['adaptive'] }),
+ });
+}
diff --git a/apps/mobile/hooks/useFoodLog.ts b/apps/mobile/hooks/useFoodLog.ts
index b148bfd..cffa940 100644
--- a/apps/mobile/hooks/useFoodLog.ts
+++ b/apps/mobile/hooks/useFoodLog.ts
@@ -114,6 +114,7 @@ export function useLogFood() {
qc.invalidateQueries({ queryKey: ['food-logs'] });
qc.invalidateQueries({ queryKey: ['food-week'] });
qc.invalidateQueries({ queryKey: ['trends'] });
+ qc.invalidateQueries({ queryKey: ['adaptive'] });
},
});
}
@@ -153,6 +154,7 @@ export function useDeleteFoodLog() {
qc.invalidateQueries({ queryKey: ['food-recent'] });
qc.invalidateQueries({ queryKey: ['food-week'] });
qc.invalidateQueries({ queryKey: ['trends'] });
+ qc.invalidateQueries({ queryKey: ['adaptive'] });
},
});
}
@@ -169,6 +171,7 @@ export function useUpdateFoodLog() {
qc.invalidateQueries({ queryKey: ['food-recent'] });
qc.invalidateQueries({ queryKey: ['food-week'] });
qc.invalidateQueries({ queryKey: ['trends'] });
+ qc.invalidateQueries({ queryKey: ['adaptive'] });
},
});
}
diff --git a/apps/mobile/hooks/useHealthKit.ts b/apps/mobile/hooks/useHealthKit.ts
deleted file mode 100644
index cda641b..0000000
--- a/apps/mobile/hooks/useHealthKit.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * Health data integration — Apple HealthKit (iOS) + Google Health Connect (Android)
- *
- * Not built yet, so react-native-health and react-native-health-connect are
- * not installed: linking HealthKit into a build that never uses it gets App
- * Store builds rejected. To build it:
- * 1. npx expo install react-native-health react-native-health-connect
- * 2. Add the HealthKit entitlement and NSHealthShareUsageDescription /
- * NSHealthUpdateUsageDescription in app.json, and the Health Connect
- * permissions and config plugin for Android
- * 3. Uncomment the imports and real implementation below, and test on
- * real devices with a development build
- *
- * Until then, the hook returns empty/safe defaults so the rest of the app compiles.
- */
-
-import { useCallback } from 'react';
-// The real implementation also needs Platform (react-native) and api (@/lib/api)
-
-// ─── Bare-workflow implementation (uncomment after prebuild) ─────────────────
-// import AppleHealthKit, { HealthKitPermissions, HealthUnit } from 'react-native-health';
-// import { initialize, requestPermission, readRecords } from 'react-native-health-connect';
-
-export interface HealthSyncResult {
- steps: number;
- activeMinutes: number;
-}
-
-export function useHealthKit() {
- const requestPermissions = useCallback(async (): Promise => {
- // TODO: uncomment after `npx expo prebuild`
- // if (Platform.OS === 'ios') {
- // return new Promise((resolve) => {
- // AppleHealthKit.initHealthKit(IOS_PERMISSIONS, (err) => resolve(!err));
- // });
- // }
- // if (Platform.OS === 'android') {
- // await initialize();
- // const granted = await requestPermission([
- // { accessType: 'read', recordType: 'Steps' },
- // { accessType: 'read', recordType: 'ActiveCaloriesBurned' },
- // ]);
- // return granted;
- // }
- console.warn('[HealthKit] Native modules not available — run expo prebuild first.');
- return false;
- }, []);
-
- const syncToday = useCallback(async (): Promise => {
- // TODO: uncomment after prebuild
- // if (Platform.OS === 'ios') {
- // const steps = await getIosSteps();
- // const activeMin = await getIosActiveMinutes();
- // if (steps > 0 || activeMin > 0) {
- // await api.post('/activity-logs', {
- // activityType: 'walking',
- // durationMin: activeMin,
- // steps,
- // source: 'healthkit',
- // });
- // }
- // return { steps, activeMinutes: activeMin };
- // }
- // if (Platform.OS === 'android') {
- // const stepsResult = await readRecords('Steps', { timeRangeFilter: todayRange() });
- // const steps = stepsResult.reduce((s, r) => s + r.count, 0);
- // await api.post('/activity-logs', { activityType: 'walking', durationMin: 0, steps, source: 'health_connect' });
- // return { steps, activeMinutes: 0 };
- // }
- return { steps: 0, activeMinutes: 0 };
- }, []);
-
- return { requestPermissions, syncToday };
-}
-
-// ─── iOS helper stubs (uncomment after prebuild) ─────────────────────────────
-// const IOS_PERMISSIONS: HealthKitPermissions = {
-// permissions: {
-// read: [AppleHealthKit.Constants.Permissions.Steps, AppleHealthKit.Constants.Permissions.ActiveEnergyBurned],
-// write: [],
-// },
-// };
-//
-// function getIosSteps(): Promise {
-// return new Promise((resolve) => {
-// const options = { date: new Date().toISOString(), includeManuallyAdded: false };
-// AppleHealthKit.getStepCount(options, (err, result) => resolve(err ? 0 : result.value));
-// });
-// }
-//
-// function getIosActiveMinutes(): Promise {
-// return new Promise((resolve) => {
-// const now = new Date();
-// const startOfDay = new Date(now); startOfDay.setHours(0, 0, 0, 0);
-// AppleHealthKit.getActiveEnergyBurned(
-// { startDate: startOfDay.toISOString(), endDate: now.toISOString() },
-// (err, results) => resolve(err ? 0 : Math.round(results.reduce((s, r) => s + r.value, 0) / 5)),
-// );
-// });
-// }
-//
-// function todayRange() {
-// const now = new Date();
-// const start = new Date(now); start.setHours(0, 0, 0, 0);
-// return { operator: 'between' as const, startTime: start.toISOString(), endTime: now.toISOString() };
-// }
diff --git a/apps/mobile/hooks/useHealthRecent.ts b/apps/mobile/hooks/useHealthRecent.ts
new file mode 100644
index 0000000..bba6553
--- /dev/null
+++ b/apps/mobile/hooks/useHealthRecent.ts
@@ -0,0 +1,16 @@
+import { useQuery } from '@tanstack/react-query';
+import { api } from '@/lib/api';
+
+export interface HealthRecent {
+ days: { date: string; steps: number | null; sleepMinutes: number | null; source: string }[];
+ importedWorkouts: number;
+ lastSyncedAt: string | null;
+}
+
+/** The last week of synced steps and sleep. */
+export function useHealthRecent() {
+ return useQuery({
+ queryKey: ['health-recent'],
+ queryFn: () => api.get('/health/recent').then((r) => r.data),
+ });
+}
diff --git a/apps/mobile/hooks/useHealthSync.ts b/apps/mobile/hooks/useHealthSync.ts
new file mode 100644
index 0000000..7601f54
--- /dev/null
+++ b/apps/mobile/hooks/useHealthSync.ts
@@ -0,0 +1,15 @@
+import { useEffect } from 'react';
+import { AppState, Platform } from 'react-native';
+import { syncHealth } from '@/lib/health/sync';
+
+/** Syncs the health app when the app opens and whenever it comes back to the foreground. */
+export function useHealthSync(signedIn: boolean) {
+ useEffect(() => {
+ if (!signedIn || Platform.OS === 'web') return;
+ syncHealth().catch(() => {});
+ const sub = AppState.addEventListener('change', (state) => {
+ if (state === 'active') syncHealth().catch(() => {});
+ });
+ return () => sub.remove();
+ }, [signedIn]);
+}
diff --git a/apps/mobile/hooks/useNotifications.ts b/apps/mobile/hooks/useNotifications.ts
index 36fe73a..743a89c 100644
--- a/apps/mobile/hooks/useNotifications.ts
+++ b/apps/mobile/hooks/useNotifications.ts
@@ -10,7 +10,8 @@ export type NotificationType =
| 'challenge_joined'
| 'challenge_ended'
| 'streak_at_risk'
- | 'weekly_progress';
+ | 'weekly_progress'
+ | 'coach_checkin';
export interface AppNotification {
id: string;
diff --git a/apps/mobile/hooks/useProgress.ts b/apps/mobile/hooks/useProgress.ts
index dd69237..33434e6 100644
--- a/apps/mobile/hooks/useProgress.ts
+++ b/apps/mobile/hooks/useProgress.ts
@@ -55,6 +55,7 @@ function invalidateWeight(qc: ReturnType) {
qc.invalidateQueries({ queryKey: ['weight'] });
qc.invalidateQueries({ queryKey: ['trends'] });
qc.invalidateQueries({ queryKey: ['me'] });
+ qc.invalidateQueries({ queryKey: ['adaptive'] });
}
export function useLogWeight() {
diff --git a/apps/mobile/hooks/useSmartLog.ts b/apps/mobile/hooks/useSmartLog.ts
new file mode 100644
index 0000000..4a4ffa2
--- /dev/null
+++ b/apps/mobile/hooks/useSmartLog.ts
@@ -0,0 +1,90 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { api } from '@/lib/api';
+
+export type ItemSource = 'memory' | 'database' | 'estimate';
+
+export interface Per100 {
+ kcal: number;
+ protein: number;
+ carbs: number;
+ fat: number;
+}
+
+export interface ParsedItem {
+ name: string;
+ brand: string | null;
+ portion: string;
+ grams: number;
+ per100: Per100;
+ source: ItemSource;
+ confidence: 'high' | 'medium' | 'low';
+ calories: number;
+ proteinG: number;
+ carbsG: number;
+ fatG: number;
+}
+
+export interface ParsedMeal {
+ items: ParsedItem[];
+ total: { calories: number; proteinG: number; carbsG: number; fatG: number };
+ question: string | null;
+}
+
+export interface FoodMemory {
+ id: string;
+ name: string;
+ kcalPer100g: number;
+ proteinPer100g: number;
+ carbsPer100g: number;
+ fatPer100g: number;
+ usualGrams: number;
+ uses: number;
+}
+
+/** Reads a described or photographed meal into items. Nothing is logged yet. */
+export function useParseMeal() {
+ return useMutation({
+ mutationFn: (body: { text?: string; imageBase64?: string; imageType?: string }) =>
+ api.post('/food/parse', body, { timeout: 90_000 }).then((r) => r.data),
+ });
+}
+
+export function useLogParsedMeal() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (body: {
+ mealType: string;
+ loggedAt?: string;
+ items: {
+ name: string;
+ brand?: string;
+ grams: number;
+ kcalPer100g: number;
+ proteinPer100g: number;
+ carbsPer100g: number;
+ fatPer100g: number;
+ remember?: boolean;
+ }[];
+ }) => api.post<{ logged: number }>('/food/parse/log', body).then((r) => r.data),
+ onSuccess: () => {
+ for (const key of ['food-logs', 'food-recent', 'food-week', 'trends', 'adaptive', 'food-memories']) {
+ qc.invalidateQueries({ queryKey: [key] });
+ }
+ },
+ });
+}
+
+export function useFoodMemories() {
+ return useQuery({
+ queryKey: ['food-memories'],
+ queryFn: () => api.get('/food/memories').then((r) => r.data),
+ });
+}
+
+export function useForgetFood() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => api.delete(`/food/memories/${id}`).then((r) => r.data),
+ onSuccess: () => qc.invalidateQueries({ queryKey: ['food-memories'] }),
+ });
+}
diff --git a/apps/mobile/lib/health/source.android.ts b/apps/mobile/lib/health/source.android.ts
new file mode 100644
index 0000000..86a3181
--- /dev/null
+++ b/apps/mobile/lib/health/source.android.ts
@@ -0,0 +1,85 @@
+import {
+ aggregateGroupByPeriod,
+ getSdkStatus,
+ initialize,
+ readRecords,
+ requestPermission,
+ SdkAvailabilityStatus,
+} from 'react-native-health-connect';
+import { localDateStr } from '@/lib/date';
+import { androidExerciseType } from './transform';
+import type { HealthSource, SleepInterval } from './types';
+
+// Sleep stage types that are awake time inside a session
+const AWAKE_STAGES = new Set([1, 3]);
+
+const PERMISSIONS = [
+ { accessType: 'read', recordType: 'ExerciseSession' },
+ { accessType: 'read', recordType: 'Steps' },
+ { accessType: 'read', recordType: 'Weight' },
+ { accessType: 'read', recordType: 'SleepSession' },
+] as const;
+
+let initialized = false;
+async function ready() {
+ if (!initialized) initialized = await initialize();
+ return initialized;
+}
+
+/** Health Connect, through react-native-health-connect. */
+export const healthSource: HealthSource = {
+ id: 'health_connect',
+ name: 'Health Connect',
+ isAvailable: async () => {
+ try {
+ return (await getSdkStatus()) === SdkAvailabilityStatus.SDK_AVAILABLE && (await ready());
+ } catch {
+ return false;
+ }
+ },
+ requestAccess: async () => {
+ if (!(await ready())) return false;
+ const granted = await requestPermission([...PERMISSIONS] as never);
+ return granted.length > 0;
+ },
+ read: async (since, until) => {
+ await ready();
+ const timeRangeFilter = { operator: 'between' as const, startTime: since.toISOString(), endTime: until.toISOString() };
+
+ const sessions = await readRecords('ExerciseSession', { timeRangeFilter });
+ const workouts = sessions.records.map((r) => ({
+ id: `hc:${r.metadata?.id ?? `${r.startTime}-${r.exerciseType}`}`,
+ activityType: androidExerciseType(r.exerciseType),
+ start: new Date(r.startTime),
+ end: new Date(r.endTime),
+ }));
+
+ const midnight = new Date(since);
+ midnight.setHours(0, 0, 0, 0);
+ const stepGroups = await aggregateGroupByPeriod({
+ recordType: 'Steps',
+ timeRangeFilter: { operator: 'between', startTime: midnight.toISOString(), endTime: until.toISOString() },
+ timeRangeSlicer: { period: 'DAYS', length: 1 },
+ } as never);
+ const steps = (stepGroups as unknown as { startTime: string; result: { COUNT_TOTAL?: number } }[]).map((g) => ({
+ date: localDateStr(new Date(g.startTime)),
+ steps: g.result.COUNT_TOTAL ?? 0,
+ }));
+
+ const weightRecords = await readRecords('Weight', { timeRangeFilter });
+ const weights = weightRecords.records.map((w) => ({ at: new Date(w.time), kg: w.weight.inKilograms }));
+
+ const sleepRecords = await readRecords('SleepSession', { timeRangeFilter });
+ const sleep: SleepInterval[] = [];
+ for (const s of sleepRecords.records) {
+ sleep.push({ start: new Date(s.startTime), end: new Date(s.endTime), asleep: true });
+ for (const stage of s.stages ?? []) {
+ if (AWAKE_STAGES.has(stage.stage)) {
+ sleep.push({ start: new Date(stage.startTime), end: new Date(stage.endTime), asleep: false });
+ }
+ }
+ }
+
+ return { workouts, steps, sleep, weights };
+ },
+};
diff --git a/apps/mobile/lib/health/source.ios.ts b/apps/mobile/lib/health/source.ios.ts
new file mode 100644
index 0000000..5e6b9dd
--- /dev/null
+++ b/apps/mobile/lib/health/source.ios.ts
@@ -0,0 +1,90 @@
+import {
+ isHealthDataAvailable,
+ queryCategorySamples,
+ queryQuantitySamples,
+ queryStatisticsCollectionForQuantity,
+ queryWorkoutSamples,
+ requestAuthorization,
+} from '@kingstinct/react-native-healthkit';
+import { localDateStr } from '@/lib/date';
+import { appleWorkoutType } from './transform';
+import type { HealthSource, HealthWorkout, SleepInterval } from './types';
+
+// Sleep analysis values that mean asleep (unspecified, core, deep, REM); 0 is
+// in bed and 2 is awake
+const ASLEEP = new Set([1, 3, 4, 5]);
+
+const READ = [
+ 'HKWorkoutTypeIdentifier',
+ 'HKQuantityTypeIdentifierStepCount',
+ 'HKQuantityTypeIdentifierBodyMass',
+ 'HKCategoryTypeIdentifierSleepAnalysis',
+ 'HKQuantityTypeIdentifierActiveEnergyBurned',
+] as const;
+
+/** Apple Health, through @kingstinct/react-native-healthkit. */
+export const healthSource: HealthSource = {
+ id: 'healthkit',
+ name: 'Apple Health',
+ isAvailable: async () => {
+ try {
+ return isHealthDataAvailable();
+ } catch {
+ return false;
+ }
+ },
+ requestAccess: async () => {
+ // iOS never says what was granted, only that it asked
+ await requestAuthorization({ toRead: READ as never });
+ return true;
+ },
+ read: async (since, until) => {
+ const filter = { date: { startDate: since, endDate: until } };
+
+ const rawWorkouts = (await queryWorkoutSamples({ limit: 0, filter } as never)) as unknown as {
+ uuid: string;
+ workoutActivityType: number;
+ startDate: Date;
+ endDate: Date;
+ totalEnergyBurned?: { quantity: number; unit: string };
+ }[];
+ const workouts: HealthWorkout[] = rawWorkouts.map((w) => ({
+ id: `hk:${w.uuid}`,
+ activityType: appleWorkoutType(w.workoutActivityType),
+ start: new Date(w.startDate),
+ end: new Date(w.endDate),
+ kcal: w.totalEnergyBurned?.unit === 'kcal' ? w.totalEnergyBurned.quantity : undefined,
+ }));
+
+ // Daily step totals, de-duplicated across iPhone and Watch by HealthKit
+ const midnight = new Date(since);
+ midnight.setHours(0, 0, 0, 0);
+ const stepDays = await queryStatisticsCollectionForQuantity(
+ 'HKQuantityTypeIdentifierStepCount',
+ ['cumulativeSum'],
+ midnight,
+ { day: 1 },
+ { filter, unit: 'count' } as never,
+ );
+ const steps = stepDays
+ .filter((d) => d.startDate && d.sumQuantity)
+ .map((d) => ({ date: localDateStr(new Date(d.startDate!)), steps: d.sumQuantity!.quantity }));
+
+ const weightSamples = (await queryQuantitySamples('HKQuantityTypeIdentifierBodyMass', {
+ limit: 0,
+ unit: 'kg',
+ filter,
+ } as never)) as unknown as { quantity: number; startDate: Date }[];
+ const weights = weightSamples.map((w) => ({ at: new Date(w.startDate), kg: w.quantity }));
+
+ const sleepSamples = (await queryCategorySamples('HKCategoryTypeIdentifierSleepAnalysis', {
+ limit: 0,
+ filter,
+ } as never)) as unknown as { value: number; startDate: Date; endDate: Date }[];
+ const sleep: SleepInterval[] = sleepSamples
+ .filter((s) => s.value !== 0) // "in bed" isn't sleep
+ .map((s) => ({ start: new Date(s.startDate), end: new Date(s.endDate), asleep: ASLEEP.has(s.value) }));
+
+ return { workouts, steps, sleep, weights };
+ },
+};
diff --git a/apps/mobile/lib/health/source.ts b/apps/mobile/lib/health/source.ts
new file mode 100644
index 0000000..12b476e
--- /dev/null
+++ b/apps/mobile/lib/health/source.ts
@@ -0,0 +1,10 @@
+import type { HealthSource } from './types';
+
+/** Web (and anywhere without a health store): nothing to read. */
+export const healthSource: HealthSource = {
+ id: null,
+ name: 'Health data',
+ isAvailable: async () => false,
+ requestAccess: async () => false,
+ read: async () => ({ workouts: [], steps: [], sleep: [], weights: [] }),
+};
diff --git a/apps/mobile/lib/health/sync.ts b/apps/mobile/lib/health/sync.ts
new file mode 100644
index 0000000..17743c4
--- /dev/null
+++ b/apps/mobile/lib/health/sync.ts
@@ -0,0 +1,75 @@
+import { api } from '@/lib/api';
+import { storage } from '@/lib/storage';
+import { queryClient } from '@/lib/queryClient';
+import { healthSource } from './source';
+import { toImportPayload } from './transform';
+
+const ENABLED_KEY = 'grit_health_enabled';
+const LAST_KEY = 'grit_health_last_sync';
+const MIN_GAP_MS = 15 * 60_000;
+const FIRST_SYNC_DAYS = 14;
+// Re-read a little before the last sync: the watch may upload late
+const OVERLAP_MS = 2 * 86_400_000;
+
+export async function isHealthSyncOn() {
+ return (await storage.getItem(ENABLED_KEY).catch(() => null)) === '1';
+}
+
+export async function lastHealthSync(): Promise {
+ const raw = await storage.getItem(LAST_KEY).catch(() => null);
+ return raw ? new Date(raw) : null;
+}
+
+/** Asks the health app for access and turns syncing on. False if refused or unavailable. */
+export async function connectHealth(): Promise {
+ if (!(await healthSource.isAvailable())) return false;
+ if (!(await healthSource.requestAccess())) return false;
+ await storage.setItem(ENABLED_KEY, '1');
+ return true;
+}
+
+/** Stops syncing. What was already imported stays. */
+export async function disconnectHealth() {
+ await storage.removeItem(ENABLED_KEY);
+ await storage.removeItem(LAST_KEY);
+}
+
+export interface SyncResult {
+ workouts: { created: number; updated: number };
+ days: number;
+ weights: number;
+}
+
+let running: Promise | null = null;
+
+/**
+ * Reads new data from the health app and sends it to GRIT. Runs at most
+ * every 15 minutes unless forced, and never twice at once. Returns what the
+ * backend stored, or null if it didn't run.
+ */
+export async function syncHealth({ force = false } = {}): Promise {
+ if (running) return running;
+ if (!healthSource.id || !(await isHealthSyncOn())) return null;
+ const last = await lastHealthSync();
+ const now = new Date();
+ if (!force && last && now.getTime() - last.getTime() < MIN_GAP_MS) return null;
+
+ running = (async () => {
+ const since = last
+ ? new Date(last.getTime() - OVERLAP_MS)
+ : new Date(now.getTime() - FIRST_SYNC_DAYS * 86_400_000);
+ const data = await healthSource.read(since, now);
+ const payload = toImportPayload(healthSource.id!, data, now);
+ const { data: result } = await api.post('/health/import', payload);
+ await storage.setItem(LAST_KEY, now.toISOString());
+ for (const key of ['activity-week', 'activity-logs', 'trends', 'weight', 'me', 'challenges', 'health-recent', 'leaderboard-weekly']) {
+ queryClient.invalidateQueries({ queryKey: [key] });
+ }
+ return result as SyncResult;
+ })();
+ try {
+ return await running;
+ } finally {
+ running = null;
+ }
+}
diff --git a/apps/mobile/lib/health/transform.ts b/apps/mobile/lib/health/transform.ts
new file mode 100644
index 0000000..9a924cf
--- /dev/null
+++ b/apps/mobile/lib/health/transform.ts
@@ -0,0 +1,101 @@
+import { localDateStr } from '@/lib/date';
+import type { HealthData, SleepInterval, WeightSample } from './types';
+
+// Apple Health workout activity types (HKWorkoutActivityType) → GRIT's
+const APPLE_TYPES: Record = {
+ 37: 'running', 52: 'walking', 13: 'cycling', 46: 'swimming', 57: 'yoga', 24: 'hiking',
+ 50: 'strength_training', 20: 'strength_training', 11: 'strength_training',
+ 63: 'hiit', 35: 'rowing', 16: 'elliptical', 44: 'stair_climbing', 68: 'stair_climbing',
+ 6: 'basketball', 48: 'tennis', 41: 'soccer', 77: 'dancing', 78: 'dancing',
+ 66: 'pilates', 8: 'boxing', 9: 'rock_climbing', 64: 'jump_rope',
+};
+
+// Health Connect exercise types → GRIT's
+const ANDROID_TYPES: Record = {
+ 56: 'running', 79: 'walking', 8: 'cycling', 9: 'cycling', 74: 'swimming', 73: 'swimming',
+ 83: 'yoga', 37: 'hiking', 70: 'strength_training', 81: 'strength_training', 13: 'strength_training',
+ 36: 'hiit', 53: 'rowing', 54: 'rowing', 25: 'elliptical', 68: 'stair_climbing',
+ 5: 'basketball', 76: 'tennis', 64: 'soccer', 16: 'dancing', 48: 'pilates', 11: 'boxing', 51: 'rock_climbing',
+};
+
+export const appleWorkoutType = (code: number) => APPLE_TYPES[code] ?? 'other';
+export const androidExerciseType = (code: number) => ANDROID_TYPES[code] ?? 'other';
+
+/**
+ * Minutes asleep per night, keyed by the local date the night ends on.
+ * Overlapping intervals (a watch and a phone both recording) count once,
+ * and awake stretches inside a session are taken out.
+ */
+export function sleepByNight(intervals: SleepInterval[]): Record {
+ const merge = (list: SleepInterval[]) => {
+ const sorted = [...list].sort((a, b) => a.start.getTime() - b.start.getTime());
+ const out: { start: number; end: number }[] = [];
+ for (const i of sorted) {
+ const s = i.start.getTime(), e = i.end.getTime();
+ if (e <= s) continue;
+ const last = out[out.length - 1];
+ if (last && s <= last.end) last.end = Math.max(last.end, e);
+ else out.push({ start: s, end: e });
+ }
+ return out;
+ };
+ const asleep = merge(intervals.filter((i) => i.asleep));
+ const awake = merge(intervals.filter((i) => !i.asleep));
+
+ const nights: Record = {};
+ for (const a of asleep) {
+ let ms = a.end - a.start;
+ for (const w of awake) {
+ const overlap = Math.min(a.end, w.end) - Math.max(a.start, w.start);
+ if (overlap > 0) ms -= overlap;
+ }
+ // A nap after midday counts toward that day; overnight sleep toward the morning it ends
+ const date = localDateStr(new Date(a.end));
+ nights[date] = (nights[date] ?? 0) + Math.max(0, ms) / 60_000;
+ }
+ for (const d of Object.keys(nights)) nights[d] = Math.round(nights[d]);
+ return nights;
+}
+
+/** The last weigh-in of each local day. */
+export function latestWeightPerDay(samples: WeightSample[]): { date: string; weightKg: number }[] {
+ const byDay = new Map();
+ for (const s of samples) {
+ const date = localDateStr(s.at);
+ const prev = byDay.get(date);
+ if (!prev || s.at > prev.at) byDay.set(date, s);
+ }
+ return [...byDay.entries()]
+ .map(([date, s]) => ({ date, weightKg: Math.round(s.kg * 100) / 100 }))
+ .filter((w) => w.weightKg >= 20 && w.weightKg <= 400)
+ .sort((a, b) => a.date.localeCompare(b.date));
+}
+
+/** The backend's import body for what was read. */
+export function toImportPayload(source: 'healthkit' | 'health_connect', data: HealthData, now = new Date()) {
+ const workouts = data.workouts
+ .filter((w) => w.start <= now)
+ .map((w) => ({
+ externalId: w.id.slice(0, 120),
+ activityType: w.activityType,
+ startedAt: w.start.toISOString(),
+ durationMin: Math.min(1440, Math.max(1, Math.round((w.end.getTime() - w.start.getTime()) / 60_000))),
+ ...(w.kcal && w.kcal > 0 ? { caloriesBurned: Math.min(20000, Math.round(w.kcal)) } : {}),
+ }))
+ .slice(-300);
+
+ const days = new Map();
+ for (const s of data.steps) {
+ days.set(s.date, { ...days.get(s.date), date: s.date, steps: Math.min(200000, Math.round(s.steps)) });
+ }
+ for (const [date, minutes] of Object.entries(sleepByNight(data.sleep))) {
+ days.set(date, { ...days.get(date), date, sleepMinutes: Math.min(1440, minutes) });
+ }
+ const today = localDateStr(now);
+ return {
+ source,
+ workouts,
+ days: [...days.values()].filter((d) => d.date <= today).sort((a, b) => a.date.localeCompare(b.date)).slice(-62),
+ weights: latestWeightPerDay(data.weights).filter((w) => w.date <= today).slice(-62),
+ };
+}
diff --git a/apps/mobile/lib/health/types.ts b/apps/mobile/lib/health/types.ts
new file mode 100644
index 0000000..20877e9
--- /dev/null
+++ b/apps/mobile/lib/health/types.ts
@@ -0,0 +1,48 @@
+/** What GRIT reads from Apple Health or Health Connect, before sending it to the backend. */
+
+export interface HealthWorkout {
+ /** The health app's own ID, so syncing again updates instead of duplicating */
+ id: string;
+ /** One of GRIT's activity types */
+ activityType: string;
+ start: Date;
+ end: Date;
+ kcal?: number;
+}
+
+/** A stretch of sleep (or awake time inside a sleep session). */
+export interface SleepInterval {
+ start: Date;
+ end: Date;
+ asleep: boolean;
+}
+
+export interface DailySteps {
+ /** Local YYYY-MM-DD */
+ date: string;
+ steps: number;
+}
+
+export interface WeightSample {
+ at: Date;
+ kg: number;
+}
+
+export interface HealthData {
+ workouts: HealthWorkout[];
+ steps: DailySteps[];
+ sleep: SleepInterval[];
+ weights: WeightSample[];
+}
+
+/** One phone's health store. */
+export interface HealthSource {
+ /** 'healthkit' or 'health_connect'; null where there's none (web) */
+ id: 'healthkit' | 'health_connect' | null;
+ /** "Apple Health" or "Health Connect" */
+ name: string;
+ isAvailable(): Promise;
+ /** Asks for read access; true if granted (iOS never says, so true once asked) */
+ requestAccess(): Promise;
+ read(since: Date, until: Date): Promise;
+}
diff --git a/apps/mobile/lib/meals.ts b/apps/mobile/lib/meals.ts
new file mode 100644
index 0000000..cbe109d
--- /dev/null
+++ b/apps/mobile/lib/meals.ts
@@ -0,0 +1,10 @@
+export const MEALS = ['breakfast', 'lunch', 'dinner', 'snack'] as const;
+export type Meal = (typeof MEALS)[number];
+
+/** The meal someone is most likely logging at this hour. */
+export function mealForHour(hour: number): Meal {
+ if (hour >= 4 && hour < 11) return 'breakfast';
+ if (hour >= 11 && hour < 15) return 'lunch';
+ if (hour >= 17 && hour < 22) return 'dinner';
+ return 'snack';
+}
diff --git a/apps/mobile/lib/notificationRoute.ts b/apps/mobile/lib/notificationRoute.ts
index 8b26454..86e83de 100644
--- a/apps/mobile/lib/notificationRoute.ts
+++ b/apps/mobile/lib/notificationRoute.ts
@@ -18,6 +18,9 @@ export function notificationRoute(type: string | undefined, data: Record;
+ const name = [meta.full_name, meta.name].find((v): v is string => typeof v === 'string' && v.trim() !== '');
+ await api.post('/auth/sync', name ? { displayName: name.trim().slice(0, 50) } : {});
+ // Kept on the device and retried at the next sign-in if this fails
+ await syncOnboardingProfile().catch(() => {});
+}
diff --git a/apps/mobile/lib/socialAuth.ts b/apps/mobile/lib/socialAuth.ts
new file mode 100644
index 0000000..faff9d6
--- /dev/null
+++ b/apps/mobile/lib/socialAuth.ts
@@ -0,0 +1,105 @@
+import { Platform } from 'react-native';
+import * as AppleAuthentication from 'expo-apple-authentication';
+import * as Crypto from 'expo-crypto';
+import * as Linking from 'expo-linking';
+import * as WebBrowser from 'expo-web-browser';
+import type { Session } from '@supabase/supabase-js';
+import { supabase } from './supabase';
+
+export type Provider = 'google' | 'apple';
+
+const SUPABASE_URL = process.env.EXPO_PUBLIC_SUPABASE_URL!;
+const ANON_KEY = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!;
+
+/** Which sign-in providers are switched on in the Supabase project. */
+export async function enabledProviders(): Promise {
+ try {
+ const res = await fetch(`${SUPABASE_URL}/auth/v1/settings`, { headers: { apikey: ANON_KEY } });
+ const settings = (await res.json()) as { external?: Record };
+ return (['apple', 'google'] as const).filter((p) => settings.external?.[p]);
+ } catch {
+ return [];
+ }
+}
+
+/** The route the browser returns to after signing in with a provider. */
+export function authCallbackUrl() {
+ return Platform.OS === 'web'
+ ? `${globalThis.location?.origin ?? ''}/auth-callback`
+ : Linking.createURL('auth-callback');
+}
+
+/** Finishes a provider sign-in from the URL it returned to: a code (PKCE) or an error. */
+export async function completeFromUrl(url: string): Promise {
+ const params = new URLSearchParams();
+ const [, query = ''] = url.split('?');
+ const [, hash = ''] = url.split('#');
+ for (const part of [query.split('#')[0], hash]) new URLSearchParams(part).forEach((v, k) => params.set(k, v));
+
+ const error = params.get('error_description') ?? params.get('error');
+ if (error) throw new Error(error.replace(/\+/g, ' '));
+ const code = params.get('code');
+ if (!code) throw new Error('The sign-in link is missing its code.');
+ const { data, error: exchangeError } = await supabase.auth.exchangeCodeForSession(code);
+ if (exchangeError) throw exchangeError;
+ return data.session;
+}
+
+async function nativeApple(): Promise {
+ // Apple compares a hash of this with the one inside the identity token
+ const rawNonce = Crypto.randomUUID();
+ const hashedNonce = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, rawNonce);
+ let credential: AppleAuthentication.AppleAuthenticationCredential;
+ try {
+ credential = await AppleAuthentication.signInAsync({
+ requestedScopes: [
+ AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
+ AppleAuthentication.AppleAuthenticationScope.EMAIL,
+ ],
+ nonce: hashedNonce,
+ });
+ } catch (err) {
+ if ((err as { code?: string }).code === 'ERR_REQUEST_CANCELED') return null;
+ throw err;
+ }
+ if (!credential.identityToken) throw new Error('Apple did not return a sign-in token.');
+ const { data, error } = await supabase.auth.signInWithIdToken({
+ provider: 'apple',
+ token: credential.identityToken,
+ nonce: rawNonce,
+ });
+ if (error) throw error;
+
+ // Apple shares the name only the first time someone signs in
+ const name = [credential.fullName?.givenName, credential.fullName?.familyName].filter(Boolean).join(' ');
+ if (name) await supabase.auth.updateUser({ data: { full_name: name } }).catch(() => {});
+ return data.session;
+}
+
+/**
+ * Signs in with Google or Apple. iOS uses the native Apple sheet; everything
+ * else goes through Supabase's sign-in page in a browser session. Resolves
+ * to the session, or null if the user cancelled. On web the page navigates
+ * away and the sign-in finishes on /auth-callback instead.
+ */
+export async function signInWithProvider(provider: Provider): Promise {
+ if (provider === 'apple' && Platform.OS === 'ios' && (await AppleAuthentication.isAvailableAsync())) {
+ return nativeApple();
+ }
+
+ const redirectTo = authCallbackUrl();
+ if (Platform.OS === 'web') {
+ const { error } = await supabase.auth.signInWithOAuth({ provider, options: { redirectTo } });
+ if (error) throw error;
+ return null; // the browser is leaving for the provider
+ }
+
+ const { data, error } = await supabase.auth.signInWithOAuth({
+ provider,
+ options: { redirectTo, skipBrowserRedirect: true },
+ });
+ if (error) throw error;
+ const result = await WebBrowser.openAuthSessionAsync(data.url, redirectTo);
+ if (result.type !== 'success') return null;
+ return completeFromUrl(result.url);
+}
diff --git a/apps/mobile/lib/supabase.ts b/apps/mobile/lib/supabase.ts
index 034b382..d872598 100644
--- a/apps/mobile/lib/supabase.ts
+++ b/apps/mobile/lib/supabase.ts
@@ -57,5 +57,8 @@ export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
+ // Sign-in links carry a one-time code, exchanged on the device that
+ // started the sign-in, rather than the tokens themselves
+ flowType: 'pkce',
},
});
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index c3a51ba..2bd4c75 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -16,15 +16,19 @@
"@expo-google-fonts/jetbrains-mono": "^0.4.1",
"@expo/vector-icons": "^15.0.3",
"@gorhom/bottom-sheet": "^5.2.8",
+ "@kingstinct/react-native-healthkit": "^16.2.0",
"@react-native-community/netinfo": "11.4.1",
"@supabase/supabase-js": "^2.100.0",
"@tanstack/react-query": "^5.95.2",
"axios": "^1.13.6",
"cross-env": "^10.1.0",
"expo": "~54.0.0",
+ "expo-apple-authentication": "~8.0.8",
+ "expo-build-properties": "~1.0.10",
"expo-camera": "~17.0.10",
"expo-clipboard": "~8.0.8",
"expo-constants": "~18.0.13",
+ "expo-crypto": "~15.0.9",
"expo-dev-client": "~6.0.20",
"expo-font": "~14.0.11",
"expo-haptics": "~15.0.8",
@@ -36,11 +40,14 @@
"expo-secure-store": "~15.0.8",
"expo-sharing": "~14.0.8",
"expo-status-bar": "~3.0.9",
+ "expo-web-browser": "~15.0.11",
"nativewind": "^4.1.23",
"react": "19.1.0",
"react-dom": "19.1.0",
"react-native": "0.81.5",
"react-native-gesture-handler": "~2.28.0",
+ "react-native-health-connect": "^4.1.3",
+ "react-native-nitro-modules": "^0.37.2",
"react-native-reanimated": "~4.1.1",
"react-native-safe-area-context": "~5.6.0",
"react-native-screens": "~4.16.0",
diff --git a/apps/mobile/stores/themeStore.ts b/apps/mobile/stores/themeStore.ts
new file mode 100644
index 0000000..acc9668
--- /dev/null
+++ b/apps/mobile/stores/themeStore.ts
@@ -0,0 +1,30 @@
+import { create } from 'zustand';
+import { storage } from '@/lib/storage';
+
+export type ThemePreference = 'system' | 'light' | 'dark';
+
+const KEY = 'grit_theme';
+
+interface ThemeState {
+ preference: ThemePreference;
+ loaded: boolean;
+ load: () => Promise;
+ setPreference: (p: ThemePreference) => void;
+}
+
+/** Light, dark, or follow the phone. Saved on the device. */
+export const useThemeStore = create((set) => ({
+ preference: 'system',
+ loaded: false,
+ load: async () => {
+ const saved = await storage.getItem(KEY).catch(() => null);
+ set({
+ preference: saved === 'light' || saved === 'dark' || saved === 'system' ? saved : 'system',
+ loaded: true,
+ });
+ },
+ setPreference: (preference) => {
+ set({ preference });
+ storage.setItem(KEY, preference).catch(() => {});
+ },
+}));
diff --git a/docs/MARKET_RESEARCH.md b/docs/MARKET_RESEARCH.md
new file mode 100644
index 0000000..cc1fde5
--- /dev/null
+++ b/docs/MARKET_RESEARCH.md
@@ -0,0 +1,126 @@
+
+
+# GRIT Competitive Research: Phase 4 Moat Features (Nov 2026)
+
+**Method note.** Most web-page fetches were blocked in this session (macrofactor.com, aol.com and others would not resolve), so this report rests on search-result extracts. Many 2026 "reviews" come from competitor SEO blogs (Nutrola, NutriScan, SensAI, GAYA). I used them only for user-sentiment themes, and prices marked "~" are unverified. Press releases and trade press (TechCrunch, BusinessWire, GlobeNewswire, 9to5Mac, Healio) carry the firm claims.
+
+## 1. Landscape
+
+| App | Positioning | Standout features (2025–26 news in bold) | Top complaints | Price (2026) |
+|---|---|---|---|---|
+| **MyFitnessPal** | Mass-market tracker, biggest database | **Acquired Cal AI (announced Mar 2026)**; **ChatGPT Health app (Jan 2026)**; **AI Coach, Premium only (Jun 2026)**; **free GLP-1 support (Apr 2026)**; Meal Planner (Intent acquisition) in Premium+ | Barcode scan paywalled since 2022; ads; crowdsourced data errors; **Apr 2026 "Today" redesign backlash, no way back to old Diary, reported data-loss bugs** | Free; Premium $79.99/yr ($19.99/mo); Premium+ $99.99/yr |
+| **Lose It!** | Simple weight-loss counter | Snap It (photo) + Say It (voice) logging, trial for free users; GLP-1 tracking listed 2026 (unverified) | Barcode scan reportedly moving to Premium for new users; ads; duplicate entries | ~$39.99/yr |
+| **Cronometer** | Micronutrient accuracy, lab-verified database | **Photo Logging, Gold-only (beta Feb 2026)**, matches to its verified database | Dated UI; photo logging immature | Gold ~$50–60/yr (sources conflict) |
+| **MacroFactor** | Evidence-based adaptive macro coach | Adaptive expenditure algorithm (V3 + **Expenditure Modifiers, Oct 2025**); AI Describe (text/voice) + photo; **separate Workouts app (Jan 2026)**, **Plate-Stack AI (Jul 2026)** | No free tier; algorithm slow to converge and noisy with menstrual-cycle water swings; minimal social; two apps, two subscriptions | $71.99/yr; Workouts $71.99/yr; bundle ~$89.99 |
+| **Cal AI** (+ photo-first clones) | Snap-a-photo, Gen-Z virality | Photo calorie estimate; 15M+ downloads, $30–40M/yr revenue | Accuracy (see gap #1); **pulled from App Store Apr 2026 over deceptive paywall, later restored**; billing-trial complaints | ~$20–30/yr, dynamic |
+| **Yazio** | EU-centric tracker + fasting | Fasting, recipes, photo logging in PRO (claims conflict) | Paywall creep | ~$45–48/yr |
+| **Lifesum** | Lifestyle/diet plans | Multimodal tracker (photo/voice/text, Feb 2025) | Misidentified foods (cashews logged as shrimp), barcode calories doubled | Unclear (~$99.99/yr cited) |
+| **Noom** | Psychology program, now GLP-1 telehealth | Noom Med GLP-1Rx + **Microdose GLP-1 (2026)** | Cost; upsell-heavy | GLP-1Rx from $129, then $279/mo; Microdose $79 intro, then $199/mo |
+| **Carbon Diet Coach** | Layne Norton's adaptive macros | Weekly check-in with algorithmic macro adjustment | No free tier; nutrition only; thin logging (barcode reportedly missing) | ~$80–120/yr (conflicting) |
+| **Strava** | Endurance social network | Social graph, clubs, segments; Athlete Intelligence AI summaries; **bought Runna (Apr 2026), joint bundle** | Paywalled analytics; AI summaries seen as shallow; no nutrition | $79.99/yr; +Runna $149.99/yr |
+| **Fitbod** | Algorithmic strength programming | Auto progressive overload | **2026 price hike**; rotates exercises too often to progress on specific lifts | $95.99/yr new subs (legacy $79.99) |
+| **Hevy** | Free social lift logger | Generous free tier, feed, PRs, strength-level comparisons | No programming or coaching | Pro ~$23.99/yr |
+| **Ladder / Future** | Human-coached training | Ladder: coach-led group programs. Future: 1:1 human coach. **Future reportedly scrapped its AI coach (Jun 2026)** to focus on humans | Price; Ladder is iOS-only and not individualised | Ladder ~$150–180/yr; Future $149–199/mo |
+| **WHOOP / Oura** | Wearable recovery + AI advisor | **WHOOP "My Memory" (7 editable memory categories) + Proactive Check-Ins (May 2026)**; Oura Advisor with user-controlled memory (2025) | Nutrition logging weak or absent; hardware-locked | Subscription bundled with hardware (not verified) |
+| **Streaks / Habitica** | Habit trackers | Streaks: polished iOS app, Health auto-complete. Habitica: gamified, social | Streaks has a 24-habit cap and no social; Habitica feels overbuilt | Streaks $5.99 one-time; Habitica free + extras |
+
+## 2. Category gaps (ranked)
+
+1. **AI logging is fast but inaccurate, and every app hides it behind a paywall.** In a NUTRITION 2026 study of 102 controlled meals (preliminary), photo features underestimated energy by about 33%: Cal AI by 345 kcal, Lose It! by 333 and MyFitnessPal by 327, with fat undercounted by about 30 g per meal. Accuracy was worse for keto meals. The researchers suggest combining photo AI with traditional database logging. MFP's Meal Scan and Cronometer's photo logging both need a paid tier.
+2. **Basic features keep moving behind paywalls, plus ads.** MFP's barcode scan has been Premium-only since 2022, Lose It! is reportedly paywalling barcode scanning for new users, and one market analysis links Lose It!'s falling sentiment to "aggressive paywalling of legacy features". Cal AI was removed from the App Store over its paywall design.
+3. **Bad database data.** In an analysis of 50,000 reviews (by a competitor), inaccurate data made up 15.7% of complaints overall and 24.1% among long-term users. MFP's crowdsourced entries draw the most criticism, and Lifesum's barcode scans reportedly double or triple calories.
+4. **Targets don't adapt.** On MFP, users set and fix their own targets. MacroFactor's expenditure algorithm is "the whole USP" according to its subreddit, but it costs $72/yr with no free tier, and Carbon has none either.
+5. **Logging falls off after a few weeks, and nothing holds people to it.** In two 6-month trials, fewer than half of participants were still self-monitoring by week 10. Supportive-accountability scores correlate with adherence (JMIR 2020). Nutrition apps have weak social features, and Strava and Hevy have strong social features but no nutrition.
+6. **AI coaches are siloed and forgetful.** MFP's AI Coach (Jun 2026) covers nutrition only and is Premium-only. Strava's AI summaries cover training only. WHOOP and Oura only recently added memory, and they lack serious food data. Even coaches are wary: 54% worry about the accuracy of AI advice (FitBudd, a vendor survey).
+7. **Nutrition and training live in separate apps.** MacroFactor needed a second app and a second subscription for workouts, Fitbod raised prices, and Hevy is free but has no coaching.
+8. **Redesigns break habits.** MFP's April 2026 "Today" redesign reportedly drove version ratings from ~3.2 to ~1.5, with no way to revert.
+
+## 3. Recommended Phase 4 moat features (ranked)
+
+### 1. Multimodal "Say / Snap / Type" logging, grounded in a database and your history (BUILD FIRST)
+- **What it is.** You type or say "2 eggs, toast with butter, flat white" or snap a photo. The LLM breaks the meal into items, grams and cooking method. Each item is then matched to Open Food Facts, USDA FoodData Central, or your own recent and favourite foods. Before saving, you see a confirm sheet with portion sliders. When something is ambiguous, the app asks one clarifying question, such as "cooked in oil?". Recipe-URL import uses the same pipeline.
+- **Why it's a moat for GRIT.** On its own this is now table stakes, but personalised it compounds. Every correction ("my usual oats = 60 g") goes into a per-user food memory, so logging gets faster and more accurate the longer someone uses GRIT, which a new app can't match on day one. Offering it free would hit competitors where they paywall.
+- **Evidence of demand.** Lose It! reports 3.5x faster logging and 2x more foods logged with AI (vendor data). MacroFactor, MFP, Cronometer, Lifesum and Yazio all shipped versions in 2025–26, and Cal AI built $30M+/yr of revenue on it.
+- **Who does it, and how well.** Accuracy is poor across the board (about −33%). MacroFactor grounds AI Describe in its database, which is the right pattern. Cronometer's version is Gold-only and limited.
+- **Build note.** Mobile: expo-camera / expo-image-picker, plus audio sent to Azure OpenAI transcription (or on-device speech). Backend: a NestJS `POST /food/parse` endpoint calls the vision-capable GPT with a strict JSON schema (structured outputs). The LLM estimates portions only; nutrients per gram always come from the database. Prisma models: `ParsedMeal`, `FoodAlias` (user-specific corrections). Reuse the coach's daily cap for cost control, add a "low confidence" flag, and log the photo-vs-confirmed difference to tune prompts.
+
+### 2. Adaptive TDEE with a weekly check-in (BUILD FIRST)
+- **What it is.** Estimated expenditure = intake − (change in weight-trend × ~7,700 kcal/kg) / days. Start from the Mifflin estimate and blend toward the observed value as data comes in. Days with incomplete logs are excluded. A weekly check-in proposes a new calorie and macro target, and the coach explains why in one paragraph.
+- **Why it's a moat for GRIT.** GRIT already has weigh-ins, intake, MET-based burn, earnback, rollover and a weekly check-in push, so most of the inputs exist. GRIT can do something MacroFactor can't: reconcile logged training with weight trend to auto-calibrate earnback, for example "your workouts burn ~70% of the MET estimate". The estimate improves with personal history, which gives the switching cost MacroFactor users cite.
+- **Evidence of demand.** r/MacroFactor users call the expenditure algorithm "the whole USP" and value being told "how much to eat each week". Carbon charges ~$80–120/yr for little more than this.
+- **Who does it, and how well.** MacroFactor does it well but behind $72/yr; Carbon is paid only; MFP and Lose It! use static targets.
+- **Build note.** A nightly @nestjs/schedule job computes an EWMA weight trend and runs a simple Kalman/Bayesian update. Prisma: `ExpenditureEstimate(date, value, confidence)` and `TargetProposal(status)`. Require at least 14 days of data and about 80% logging completeness. Let the user accept, adjust or ignore each proposal. Add guardrails: a minimum calorie floor and a maximum weekly change. Optionally add cycle-aware smoothing (a known MacroFactor complaint).
+
+### 3. Coach with long-term memory that acts proactively, across nutrition, training, habits and social (BUILD FIRST)
+- **What it is.** The coach keeps an editable memory ("What Coach knows about me": goals, injuries, schedule, food dislikes, events), as WHOOP's My Memory does. Event triggers fire proactive messages: two days without logging, protein short three days running, a weight plateau, a PR, a challenge about to be lost, a friend who has been quiet. Through tool calls (with user confirmation), the coach can change the workout plan, habits or targets.
+- **Why it's a moat for GRIT.** No competitor holds all four data streams plus a social graph. MFP's coach sees food only, Strava's sees training only, WHOOP's sees recovery without real food data. Memory accumulates per user, so switching means starting over.
+- **Evidence of demand.** WHOOP (May 2026) and Oura (2025) shipped memory and proactive check-ins, MFP shipped its AI Coach (Jun 2026), and MFP built a ChatGPT integration. On the other side, Future dropped its AI coach in favour of human coaches, a sign that generic AI coaches disappoint.
+- **Build note.** Prisma model: `CoachMemory(category, text, source, confidence, expiresAt)`. Retrieve memories with pgvector on Supabase, or with a simple category filter at first. After each chat, the GPT extracts memory candidates through a tool call. A rules engine (cron) detects triggers, the GPT drafts the message, and it is delivered through the existing inbox and push. Register tools such as `updateWorkoutPlan`, `proposeTarget` and `addHabit`, and require user approval for each change. Add a privacy screen to view and delete memories.
+
+### 4. Squads: small accountability groups and partners
+- **What it is.** Groups of 2–6 people with shared weekly commitments (log five days, hit protein, three workouts). Challenges can be built on habits and nutrition, not just steps and minutes. Partners can do a "check on a friend" one-tap nudge, and the coach writes a weekly squad recap.
+- **Why it's a moat for GRIT.** This is a social-graph network effect: the more friends someone has on GRIT, the harder it is to leave. It reuses GRIT's existing friends, kudos, challenges and streak-at-risk push. MacroFactor and Cronometer have essentially no social features, and Strava and Hevy have no nutrition.
+- **Evidence of demand.** Self-monitoring collapses by week 10, and supportive accountability correlates with adherence (JMIR 2020). NCT05180448 is testing data-sharing with groups and friends, but its results are unpublished, so this is unverified.
+- **Build note.** Prisma: `Squad`, `SquadMember`, `SquadGoal`, `Nudge`. Generalise the challenge engine's metric source to habits and nutrition. Rate-limit nudges. This is mostly CRUD plus push, a low-risk build.
+
+### 5. GLP-1 mode
+- **What it is.** Medication and dose-day log, side-effect journal, protein-first and lower-volume targets, hydration and fibre habits, and a strength-training emphasis to preserve muscle (GRIT's training data is an edge here). Also a "coming off the drug" maintenance plan.
+- **Why it's a moat for GRIT.** It combines nutrition, training, habits and coach where competitors offer nutrition-only logging. The muscle-preservation and maintenance angles are underserved.
+- **Evidence of demand.** 12% of US adults are currently taking a GLP-1 (KFF, Nov 2025). MFP made its GLP-1 support free (Apr 2026), MyNetDiary launched a companion (May 2026), and Noom built a telehealth business around the drugs.
+- **Caveat.** This is quickly becoming table stakes and is not deeply defensible. Avoid dosing advice; it is a medical and regulatory risk.
+- **Build note.** Add a med-log model, reuse habits for reminders, add a target preset, and give the coach prompt context and guardrails.
+
+### 6. Progressive-overload strength tracking linked to nutrition
+- **What it is.** Set, rep and load logging, PRs and e1RM, auto-progression suggestions inside the coach's weekly plan. Training-day versus rest-day macros feed into feature #2.
+- **Why it's a moat for GRIT.** It joins what MacroFactor sells as two apps and two subscriptions. Fitbod's price hike and exercise-rotation complaints leave an opening.
+- **Caveat.** This is the largest build and Hevy is cheap and good, so treat it as later Phase 4. Sleep- and recovery-aware coaching should ride on the Health Connect / Apple Health work already in progress, as an input to #3 rather than a separate feature.
+- **Build note.** Prisma models: `Exercise`, `WorkoutSet`. Use an exercise library seed (e.g. the open-source free-exercise-db). Drive progression with rules such as double progression or RPE, and let the coach explain them.
+
+**Deprioritised.** Meal planning: MFP Premium+ owns it and LLM meal plans are generic, so it's better offered as a coach action. Restaurant logging: data licensing is hard, so fold it into #1 ("Chipotle bowl, chicken, rice…").
+
+**Build first: #1, #2, #3.** Free AI logging removes the category's biggest pain and paywall. Adaptive targets create personal-data lock-in. A cross-domain memory coach is the one thing no competitor can copy without owning all four data types. #4 is cheap and can ship alongside.
+
+**Could not verify:** Lose It!, Cronometer, Lifesum, Carbon and Ladder prices; whether Yazio has photo logging; WHOOP/Oura subscription prices; the MacroFactor bundle price; Future cancelling its AI coach (one source); Lose It!'s GLP-1 feature. Treat Reddit sentiment as indicative: no 2026 r/MacroFactor threads were readable.
+
+## Sources
+- https://techcrunch.com/2026/03/02/myfitnesspal-has-acquired-cal-ai-the-viral-calorie-app-built-by-teens
+- https://thenextweb.com/news/myfitnesspal-acquires-cal-ai-the-viral-calorie-tracking-app-built-by-teens
+- https://www.globenewswire.com/news-release/2026/04/28/3282728/0/en/MyFitnessPal-Launches-Comprehensive-GLP-1-Support-Helping-Users-Stay-Consistent-and-Build-Habits-Alongside-Medication-to-Maximize-Their-Experience.html
+- https://markets.financialcontent.com/woonsocketcall/article/gnwcq-2026-2-24-myfitnesspal-debuts-its-2026-winter-release
+- https://9to5mac.com/2026/06/16/myfitnesspal-adds-ai-powered-coach-for-personalized-nutrition-guidance/
+- https://business.mammothtimes.com/mammothtimes/article/gnwcq-2026-1-7-myfitnesspal-launches-app-in-new-chatgpt-health-experience
+- https://piunikaweb.com/2026/04/24/myfitnesspal-new-update-complaints/
+- https://mwm.ai/articles/myfitnesspal-v26-16-0-replaces-diary-with-new-ui-sparking-rating-drop-in-april-2026
+- https://www.healio.com/news/primary-care/20260804/ai-photobased-calorietracking-tools-underestimate-them-by-33
+- https://www.newswise.com/articles/photo-based-calorie-tracking-apps-may-underestimate-energy-in-meals
+- https://www.eesel.ai/en/blog/cal-ai-pricing
+- https://www.newswire.com/news/lose-it-finds-ai-powered-logging-boosts-weight-loss-success-and-22557702
+- https://www.fitbudd.com/post/lose-it-premium-review
+- https://www.finanzen.net/nachricht/aktien/cronometer-launches-premium-photo-logging-fast-verified-nutrition-tracking-for-real-life-14808068
+- https://macrofactor.com/mm-july-2026/
+- https://macrofactor.com/mm-jan-2026/
+- https://macrofactor.com/mm-oct-2025/
+- https://macrofactor.com/ai-food-logging/
+- https://apps.apple.com/us/app/macrofactor-macro-tracker/id1553503471
+- https://www.similarweb.com/es/app/apple/6737156524
+- https://nutrola.app/en/blog/we-analyzed-50000-calorie-tracker-reviews-what-users-actually-complain-about-2026 (competitor, sentiment only)
+- https://www.mycallie.app/en/blog/best-calorie-tracker-app-reddit
+- https://www.noom.com/plans
+- https://athletechnews.com/noom-microdose-glp1-rx-program-pricing-eligibility/
+- https://www.kff.org/public-opinion/poll-1-in-8-adults-say-they-are-currently-taking-a-glp-1-drug-for-weight-loss-diabetes-or-another-condition-even-as-half-say-the-drugs-are-difficult-to-afford/
+- https://digital-release.kxan.com/business/press-releases/cision/20260505FL48085/mynetdiary-launches-glp-1-companion-for-ozempic-wegovy-and-mounjaro-users
+- https://strava.com/pricing
+- https://www.t3.com/active/strava-and-runna-now-offer-a-joint-subscription-and-its-cheaper-than-buying-one-pair-of-running-shoes
+- https://the5krunner.com/2026/10/14/is-runna-free/
+- https://www.sensai.fit/blog/fitbod-review-2026
+- https://www.sensai.fit/blog/future-app-review-2026
+- https://www.sensai.fit/blog/ladder-app-review-2026
+- https://www.sensai.fit/blog/hevy-review-2026
+- https://businesswire.com/news/home/20260508464188/en/WHOOP-Expands-Health-Platform-with-On-Demand-Clinician-Access-and-New-AI-Features
+- https://www.wareable.com/wearable-tech/whoop-healthex-partnership-my-memory-ai-features-navigator-bands
+- https://www.tomsguide.com/wellness/fitness/ouras-ai-powered-advisor-is-rolling-out-heres-what-it-means-for-you
+- https://nutrola.app/en/blog/is-carbon-diet-coach-worth-it-2026 (competitor)
+- https://toolradar.com/compare/streaks-vs-habitica
+- https://pubmed.ncbi.nlm.nih.gov/31155473/
+- https://pmc.ncbi.nlm.nih.gov/articles/PMC7420735
+- https://www.fitbudd.com/fitness-industry-trends/ai-fitness-coaching-report
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index ded2797..8a18793 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -84,8 +84,52 @@ display rounding.
the old `users.pushToken` column, which Phase 2 servers still read, so
only apply it once Railway runs this version.
+## Phase 4 — Moat features and platform ✅
+
+Chosen from [`MARKET_RESEARCH.md`](./MARKET_RESEARCH.md): the three
+"build first" features, plus the platform work that was asked for.
+
+- **Light theme.** Follows the phone's setting, or pick Light or Dark
+ under Account → Appearance.
+- **Google and Apple sign-in** on the login and sign-up screens (native
+ Apple sign-in on iPhone, a browser sign-in everywhere else). The buttons
+ only appear for providers that are switched on in Supabase.
+- **Apple Health / Health Connect sync.** Workouts, steps, sleep and
+ weigh-ins come in automatically (Settings → Apple Health / Health
+ Connect). Imports never duplicate, steps count toward step challenges,
+ and the coach sees steps and sleep.
+- **Adaptive calorie targets.** From logged intake and the weigh-in
+ trend, GRIT estimates what you actually burn and suggests a new target
+ on Stats and in the Sunday check-in. You can use it, change it or snooze
+ it. Changes are capped at ±200 kcal a week, with a 1,200 kcal floor and
+ a settling period after each change.
+- **✨ Smart log.** Type, dictate or photograph a meal. GRIT splits it
+ into items with portions, including hidden oil, butter and sauces.
+ Nutrition comes first from your own past confirmations, then the food
+ database for branded items, then a checked estimate, and each item shows
+ its source. You review every item before logging. Confirmed foods and
+ portions are remembered ("Foods GRIT knows" in Profile), so logging gets
+ faster with use. Capped at 30 readings a day.
+- **Coach memory.** The coach notes lasting facts from chats (injuries,
+ foods avoided, when you can train), replaces notes that go out of date,
+ and uses them in every reply. It also sees your week's averages and the
+ adaptive estimate. Notes appear in the chat as they're taken and can be
+ viewed, added and deleted under "What your coach knows".
+- **Proactive check-ins.** At 1pm local time the coach checks for a
+ logging gap, a run of missed workouts, low protein, or a weight plateau
+ while cutting, and sends the first that applies. Each kind goes at most
+ once a week, never on Sundays, and only with progress alerts on.
+
+Database: migrations `20261106120000` to `20261106150000` are applied to
+Supabase. All are additive, so earlier servers keep working.
+
## Later
+- From the research: Squads (small accountability groups), a GLP-1
+ mode, and strength tracking with progressive overload linked to
+ nutrition.
+- Let the coach propose changes to the workout plan and habits for the
+ user to approve, as it already does for calorie targets.
- A real-device check of push alerts, photo picking and the keyboard in
sheets.
- Fuzzy user search (a `pg_trgm` index) once there are many users.
@@ -94,9 +138,15 @@ display rounding.
## Needs the account owner
-- Google and Apple sign-in: enable the providers in Supabase and use the
- Apple Developer account.
-- HealthKit / Health Connect: a development build tested on real devices.
+- Google and Apple sign-in: enable the Google and Apple providers in
+ Supabase Auth. Add `grit://auth-callback` and the web app's
+ `/auth-callback` URL to the redirect URLs. Apple needs a Services ID and
+ key from the Apple Developer account; Google needs an OAuth client.
+ Until then the buttons stay hidden.
+- HealthKit / Health Connect and Smart log's camera: these need a
+ development build (`eas build --profile development`) on real devices,
+ since Expo Go has no HealthKit or Health Connect. Check the permission
+ prompts, a first sync, and a photo reading.
- Push notifications: the app already has an EAS project ID; set
`EXPO_ACCESS_TOKEN` on the server if push security is turned on for
the Expo project. Crash reports go to the backend logs; add Sentry
diff --git a/packages/backend/prisma/migrations/20261106120000_add_health_sync/migration.sql b/packages/backend/prisma/migrations/20261106120000_add_health_sync/migration.sql
new file mode 100644
index 0000000..d9e457b
--- /dev/null
+++ b/packages/backend/prisma/migrations/20261106120000_add_health_sync/migration.sql
@@ -0,0 +1,28 @@
+-- AlterTable
+ALTER TABLE "activity_logs" ADD COLUMN "externalId" TEXT;
+
+-- CreateTable
+CREATE TABLE "health_days" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "day" TIMESTAMP(3) NOT NULL,
+ "steps" INTEGER,
+ "sleepMinutes" INTEGER,
+ "source" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "health_days_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "health_days_userId_day_key" ON "health_days"("userId", "day");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "activity_logs_userId_externalId_key" ON "activity_logs"("userId", "externalId");
+
+-- AddForeignKey
+ALTER TABLE "health_days" ADD CONSTRAINT "health_days_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+
+-- Same as every other table: only the API (as table owner) may read or write it
+ALTER TABLE "health_days" ENABLE ROW LEVEL SECURITY;
diff --git a/packages/backend/prisma/migrations/20261106130000_add_adaptive_targets/migration.sql b/packages/backend/prisma/migrations/20261106130000_add_adaptive_targets/migration.sql
new file mode 100644
index 0000000..28a6d19
--- /dev/null
+++ b/packages/backend/prisma/migrations/20261106130000_add_adaptive_targets/migration.sql
@@ -0,0 +1,4 @@
+-- AlterTable
+ALTER TABLE "users" ADD COLUMN "adaptiveAppliedAt" TIMESTAMP(3),
+ADD COLUMN "adaptiveSnoozedUntil" TIMESTAMP(3);
+
diff --git a/packages/backend/prisma/migrations/20261106140000_add_meal_parsing/migration.sql b/packages/backend/prisma/migrations/20261106140000_add_meal_parsing/migration.sql
new file mode 100644
index 0000000..7f19869
--- /dev/null
+++ b/packages/backend/prisma/migrations/20261106140000_add_meal_parsing/migration.sql
@@ -0,0 +1,30 @@
+-- AlterTable
+ALTER TABLE "users" ADD COLUMN "aiParseCount" INTEGER NOT NULL DEFAULT 0,
+ADD COLUMN "aiParseDay" TEXT;
+
+-- CreateTable
+CREATE TABLE "food_memories" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "key" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "kcalPer100g" DOUBLE PRECISION NOT NULL,
+ "proteinPer100g" DOUBLE PRECISION NOT NULL,
+ "carbsPer100g" DOUBLE PRECISION NOT NULL,
+ "fatPer100g" DOUBLE PRECISION NOT NULL,
+ "usualGrams" DOUBLE PRECISION NOT NULL,
+ "uses" INTEGER NOT NULL DEFAULT 1,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "food_memories_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "food_memories_userId_key_key" ON "food_memories"("userId", "key");
+
+-- AddForeignKey
+ALTER TABLE "food_memories" ADD CONSTRAINT "food_memories_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+
+-- Same as every other table: only the API (as table owner) may read or write it
+ALTER TABLE "food_memories" ENABLE ROW LEVEL SECURITY;
diff --git a/packages/backend/prisma/migrations/20261106150000_add_coach_memory/migration.sql b/packages/backend/prisma/migrations/20261106150000_add_coach_memory/migration.sql
new file mode 100644
index 0000000..070d5a9
--- /dev/null
+++ b/packages/backend/prisma/migrations/20261106150000_add_coach_memory/migration.sql
@@ -0,0 +1,20 @@
+-- CreateTable
+CREATE TABLE "coach_memories" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "text" TEXT NOT NULL,
+ "source" TEXT NOT NULL DEFAULT 'chat',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "coach_memories_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "coach_memories_userId_createdAt_idx" ON "coach_memories"("userId", "createdAt");
+
+-- AddForeignKey
+ALTER TABLE "coach_memories" ADD CONSTRAINT "coach_memories_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+
+-- Same as every other table: only the API (as table owner) may read or write it
+ALTER TABLE "coach_memories" ENABLE ROW LEVEL SECURITY;
diff --git a/packages/backend/prisma/schema.prisma b/packages/backend/prisma/schema.prisma
index 6be059e..c5d6882 100644
--- a/packages/backend/prisma/schema.prisma
+++ b/packages/backend/prisma/schema.prisma
@@ -44,35 +44,46 @@ model User {
notifOffTrackOnly Boolean @default(false)
// Push and inbox alerts for follows, requests, kudos and challenges
- notifSocial Boolean @default(true)
+ notifSocial Boolean @default(true)
// Private accounts approve each follower; only approved followers see activity
isPrivate Boolean @default(true)
+ // Meal descriptions/photos read by the AI today (a daily cap)
+ aiParseDay String?
+ aiParseCount Int @default(0)
+
+ // Adaptive targets: when a suggestion was last taken or put off
+ adaptiveAppliedAt DateTime?
+ adaptiveSnoozedUntil DateTime?
+
// The device's latest UTC offset in minutes, so scheduled alerts arrive at
// the right local time
utcOffset Int @default(0)
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
-
- foodLogs FoodLog[]
- activityLogs ActivityLog[]
- habitLogs HabitLog[]
- habits Habit[]
- following Follow[] @relation("following")
- followers Follow[] @relation("followers")
- challenges ChallengeParticipant[]
- aiMessages AIMessage[]
- kudosGiven Kudos[]
- workoutPlan WorkoutPlan?
- blocking Block[] @relation("blocker")
- blockedBy Block[] @relation("blocked")
- pushDevices PushDevice[]
- weightLogs WeightLog[]
- favoriteFoods FavoriteFood[]
- notifications Notification[] @relation("recipient")
- notificationsSent Notification[] @relation("actor")
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ foodLogs FoodLog[]
+ activityLogs ActivityLog[]
+ habitLogs HabitLog[]
+ habits Habit[]
+ following Follow[] @relation("following")
+ followers Follow[] @relation("followers")
+ challenges ChallengeParticipant[]
+ aiMessages AIMessage[]
+ coachMemories CoachMemory[]
+ kudosGiven Kudos[]
+ workoutPlan WorkoutPlan?
+ blocking Block[] @relation("blocker")
+ blockedBy Block[] @relation("blocked")
+ pushDevices PushDevice[]
+ weightLogs WeightLog[]
+ favoriteFoods FavoriteFood[]
+ healthDays HealthDay[]
+ foodMemories FoodMemory[]
+ notifications Notification[] @relation("recipient")
+ notificationsSent Notification[] @relation("actor")
@@map("users")
}
@@ -139,10 +150,13 @@ model ActivityLog {
source String @default("manual")
loggedAt DateTime @default(now())
kudosCount Int @default(0)
+ // The health app's ID for an imported workout, so importing again updates it
+ externalId String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
kudos Kudos[]
+ @@unique([userId, externalId])
@@index([userId, loggedAt])
@@map("activity_logs")
}
@@ -199,22 +213,22 @@ model HabitLog {
}
model Challenge {
- id String @id @default(cuid())
+ id String @id @default(cuid())
title String
// What counts, from workouts logged during the challenge:
// steps | active_minutes | workouts
- type String @default("active_minutes")
+ type String @default("active_minutes")
goalValue Int
durationDays Int
startDate DateTime
endDate DateTime
creatorId String
- inviteCode String @unique @default(cuid())
+ inviteCode String @unique @default(cuid())
// The group reached the goal (it can still be running)
- isComplete Boolean @default(false)
+ isComplete Boolean @default(false)
// Set once the end date has passed and the results were sent
endedAt DateTime?
- createdAt DateTime @default(now())
+ createdAt DateTime @default(now())
participants ChallengeParticipant[]
@@ -252,10 +266,27 @@ model AIMessage {
@@map("ai_messages")
}
+// Lasting facts the coach has learned about the user (an injury, foods they
+// avoid, when they train), from chats or added by hand. Shown and editable
+// in settings.
+model CoachMemory {
+ id String @id @default(cuid())
+ userId String
+ text String
+ // chat | user
+ source String @default("chat")
+ createdAt DateTime @default(now())
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ @@index([userId, createdAt])
+ @@map("coach_memories")
+}
+
// The coach-generated weekly plan; one per user, replaced when regenerated
model WorkoutPlan {
- id String @id @default(cuid())
- userId String @unique
+ id String @id @default(cuid())
+ userId String @unique
summary String
daysPerWeek Int
location String // home | gym
@@ -293,7 +324,7 @@ model Notification {
id String @id @default(cuid())
userId String // who it's for
// follow | follow_request | follow_accepted | kudos | challenge_joined |
- // challenge_ended | streak_at_risk | weekly_progress
+ // challenge_ended | streak_at_risk | weekly_progress | coach_checkin
type String
actorId String? // who caused it, for social alerts
title String
@@ -350,3 +381,45 @@ model FavoriteFood {
@@unique([userId, key])
@@map("favorite_foods")
}
+
+// Daily totals read from Apple Health / Health Connect. Steps count toward
+// step challenges; sleep is context for the coach.
+model HealthDay {
+ id String @id @default(cuid())
+ userId String
+ // The local day, stored as midnight UTC of that date
+ day DateTime
+ steps Int?
+ // Asleep time for the night ending on this day
+ sleepMinutes Int?
+ source String // healthkit | health_connect
+ updatedAt DateTime @updatedAt
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ @@unique([userId, day])
+ @@map("health_days")
+}
+
+// What someone actually ate when they confirmed an AI-read meal: their
+// nutrition per 100 g and usual portion for a food, used before any
+// estimate the next time they mention it
+model FoodMemory {
+ id String @id @default(cuid())
+ userId String
+ // lowercased, single-spaced name
+ key String
+ name String
+ kcalPer100g Float
+ proteinPer100g Float
+ carbsPer100g Float
+ fatPer100g Float
+ usualGrams Float
+ uses Int @default(1)
+ updatedAt DateTime @updatedAt
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ @@unique([userId, key])
+ @@map("food_memories")
+}
diff --git a/packages/backend/src/ai/ai.controller.ts b/packages/backend/src/ai/ai.controller.ts
index 95a44a8..52d1d72 100644
--- a/packages/backend/src/ai/ai.controller.ts
+++ b/packages/backend/src/ai/ai.controller.ts
@@ -1,9 +1,18 @@
-import { Controller, Post, Get, Body, Res, UseGuards } from '@nestjs/common';
+import {
+ Controller,
+ Post,
+ Get,
+ Delete,
+ Body,
+ Param,
+ Res,
+ UseGuards,
+} from '@nestjs/common';
import type { Response } from 'express';
import { AuthGuard } from '../auth/auth.guard';
import { CurrentUser } from '../common/current-user.decorator';
import { AIService } from './ai.service';
-import { SendMessageDto } from './ai.dto';
+import { AddMemoryDto, SendMessageDto } from './ai.dto';
import { UtcOffset } from '../common/utc-offset.decorator';
@Controller('ai')
@@ -54,4 +63,32 @@ export class AIController {
const nudge = await this.ai.getNudge(user.supabaseId, offset);
return { nudge };
}
+
+ // ── What the coach remembers ──────────────────────────────────────────────
+
+ @Get('memories')
+ memories(@CurrentUser() user: { supabaseId: string }) {
+ return this.ai.listMemories(user.supabaseId);
+ }
+
+ @Post('memories')
+ addMemory(
+ @CurrentUser() user: { supabaseId: string },
+ @Body() body: AddMemoryDto,
+ ) {
+ return this.ai.addMemory(user.supabaseId, body.text);
+ }
+
+ @Delete('memories/:id')
+ deleteMemory(
+ @CurrentUser() user: { supabaseId: string },
+ @Param('id') id: string,
+ ) {
+ return this.ai.deleteMemory(user.supabaseId, id);
+ }
+
+ @Delete('memories')
+ clearMemories(@CurrentUser() user: { supabaseId: string }) {
+ return this.ai.clearMemories(user.supabaseId);
+ }
}
diff --git a/packages/backend/src/ai/ai.dto.ts b/packages/backend/src/ai/ai.dto.ts
index a4c2b34..6eb43a4 100644
--- a/packages/backend/src/ai/ai.dto.ts
+++ b/packages/backend/src/ai/ai.dto.ts
@@ -5,3 +5,9 @@ export class SendMessageDto {
@Length(1, 2000)
message: string;
}
+
+export class AddMemoryDto {
+ @IsString()
+ @Length(3, 160)
+ text: string;
+}
diff --git a/packages/backend/src/ai/ai.module.ts b/packages/backend/src/ai/ai.module.ts
index f55fd1a..a0be9f8 100644
--- a/packages/backend/src/ai/ai.module.ts
+++ b/packages/backend/src/ai/ai.module.ts
@@ -2,8 +2,10 @@ import { Module } from '@nestjs/common';
import { AIController } from './ai.controller';
import { AIService } from './ai.service';
import { azureOpenAIProviders } from './azure-openai';
+import { ProgressModule } from '../progress/progress.module';
@Module({
+ imports: [ProgressModule],
controllers: [AIController],
providers: [...azureOpenAIProviders, AIService],
})
diff --git a/packages/backend/src/ai/ai.service.ts b/packages/backend/src/ai/ai.service.ts
index 69d3f6c..8c96f08 100644
--- a/packages/backend/src/ai/ai.service.ts
+++ b/packages/backend/src/ai/ai.service.ts
@@ -1,6 +1,7 @@
import {
Inject,
Injectable,
+ Logger,
NotFoundException,
HttpException,
HttpStatus,
@@ -22,17 +23,31 @@ import {
FRICTION_LABELS,
} from './profile-labels';
import { macroTargets } from '../common/nutrition';
+import { AdaptiveService } from '../progress/adaptive.service';
+import {
+ MAX_MEMORIES,
+ MEMORY_SCHEMA,
+ cleanMemory,
+ mayHoldFacts,
+ memoryInstructions,
+ planMemoryUpdate,
+ type MemoryUpdate,
+} from './coach-memory';
const DAILY_LIMIT = 10;
+// How long a finished reply waits for the note-taking call before moving on
+const MEMORY_WAIT_MS = 5000;
@Injectable()
export class AIService {
+ private readonly logger = new Logger(AIService.name);
private nudgesInFlight = new Map>();
constructor(
private prisma: PrismaService,
private openai: OpenAI,
@Inject(AI_MODEL) private model: string,
+ private adaptive: AdaptiveService,
) {}
private async resolveUser(supabaseId: string) {
@@ -46,22 +61,50 @@ export class AIService {
const today = dayRange(todayDate, offset).start;
const weekAgo = dayRange(addDays(todayDate, -7), offset).start;
- const [user, todayFood, weekActivity, habits, habitLogs] =
- await Promise.all([
- this.prisma.user.findUnique({ where: { id: userId } }),
- this.prisma.foodLog.findMany({
- where: { userId, loggedAt: { gte: today } },
- }),
- this.prisma.activityLog.findMany({
- where: { userId, loggedAt: { gte: weekAgo } },
- orderBy: { loggedAt: 'desc' },
- take: 10,
- }),
- this.prisma.habit.findMany({ where: { userId, isActive: true } }),
- this.prisma.habitLog.findMany({
- where: { userId, loggedAt: dateMarker(todayDate) },
- }),
- ]);
+ const [
+ user,
+ todayFood,
+ weekActivity,
+ habits,
+ habitLogs,
+ healthDays,
+ weekFood,
+ memories,
+ ] = await Promise.all([
+ this.prisma.user.findUnique({ where: { id: userId } }),
+ this.prisma.foodLog.findMany({
+ where: { userId, loggedAt: { gte: today } },
+ }),
+ this.prisma.activityLog.findMany({
+ where: { userId, loggedAt: { gte: weekAgo } },
+ orderBy: { loggedAt: 'desc' },
+ take: 10,
+ }),
+ this.prisma.habit.findMany({ where: { userId, isActive: true } }),
+ this.prisma.habitLog.findMany({
+ where: { userId, loggedAt: dateMarker(todayDate) },
+ }),
+ // From Apple Health / Health Connect, if connected
+ this.prisma.healthDay.findMany({
+ where: {
+ userId,
+ day: {
+ gte: dateMarker(addDays(todayDate, -1)),
+ lte: dateMarker(todayDate),
+ },
+ },
+ }),
+ // The last 7 full days, for averages
+ this.prisma.foodLog.findMany({
+ where: { userId, loggedAt: { gte: weekAgo, lt: today } },
+ select: { loggedAt: true, calories: true, proteinG: true },
+ }),
+ this.prisma.coachMemory.findMany({
+ where: { userId },
+ orderBy: { createdAt: 'asc' },
+ select: { text: true },
+ }),
+ ]);
const todayCalories = todayFood.reduce((s, f) => s + f.calories, 0);
const todayProtein = todayFood.reduce((s, f) => s + f.proteinG, 0);
@@ -109,8 +152,58 @@ export class AIService {
`- Active-minutes goal: ${user?.activeMinutesGoal ?? 60} min/day`,
].filter(Boolean);
+ const todayHealth = healthDays.find(
+ (d) => d.day.toISOString().slice(0, 10) === todayDate,
+ );
+ const healthLines = [
+ todayHealth?.steps != null ? `- Steps today: ${todayHealth.steps}` : null,
+ todayHealth?.sleepMinutes != null
+ ? `- Sleep last night: ${Math.floor(todayHealth.sleepMinutes / 60)}h ${todayHealth.sleepMinutes % 60}m`
+ : null,
+ ].filter(Boolean);
+
+ // Averages over the days they logged, so unlogged days don't drag them down
+ const byDay = new Map();
+ for (const f of weekFood) {
+ const d = localDateOf(f.loggedAt, offset);
+ const day = byDay.get(d) ?? { calories: 0, protein: 0 };
+ day.calories += f.calories;
+ day.protein += f.proteinG;
+ byDay.set(d, day);
+ }
+ const logged = [...byDay.values()];
+ const avg = (pick: (d: { calories: number; protein: number }) => number) =>
+ Math.round(logged.reduce((t, d) => t + pick(d), 0) / logged.length);
+ const weekLines = logged.length
+ ? [
+ `- Food logged on ${logged.length} of the last 7 days`,
+ `- On those days: ${avg((d) => d.calories)} kcal and ${avg((d) => d.protein)}g protein on average`,
+ ]
+ : ['- No food logged in the last 7 days'];
+
+ const checkIn = user
+ ? await this.adaptive.checkIn(user.supabaseId, offset).catch(() => null)
+ : null;
+ if (checkIn?.estimate) {
+ weekLines.push(
+ `- Estimated daily burn from their logs and weigh-ins: ${checkIn.estimate.tdee} kcal`,
+ );
+ }
+ if (checkIn?.suggestion) {
+ weekLines.push(
+ `- The app is suggesting they change their calorie target to ${checkIn.suggestion.suggested} kcal (they can accept it on the Stats tab)`,
+ );
+ }
+
+ const memoryBlock = memories.length
+ ? `\nWhat you know about them from earlier chats (use it naturally; don't list it back to them):\n${memories.map((m) => `- ${m.text}`).join('\n')}\n`
+ : '';
+
return `User profile:
${profileLines.join('\n')}
+${memoryBlock}${healthLines.length ? `\nFrom their health app:\n${healthLines.join('\n')}\n` : ''}
+Last 7 days:
+${weekLines.join('\n')}
Today's nutrition:
- Calories: ${Math.round(todayCalories)} / ${user?.calorieGoal} kcal
@@ -172,9 +265,16 @@ Keep responses to 2–4 sentences unless detail is needed. Reference specific nu
supabaseId: string,
userMessage: string,
offset: number,
- ): AsyncGenerator<{ type: string; text?: string }> {
+ ): AsyncGenerator<{ type: string; text?: string; items?: string[] }> {
const user = await this.resolveUser(supabaseId);
await this.saveUserMessage(user.id, userMessage, offset);
+ // Note-taking runs alongside the reply; it never holds the reply up
+ const noting = mayHoldFacts(userMessage)
+ ? this.updateMemories(user.id, userMessage).catch((err: Error) => {
+ this.logger.warn(`Coach memory update failed: ${err.message}`);
+ return [] as string[];
+ })
+ : Promise.resolve([] as string[]);
const history = await this.prisma.aIMessage.findMany({
where: { userId: user.id, content: { not: { startsWith: '[NUDGE]' } } },
@@ -204,6 +304,7 @@ Keep responses to 2–4 sentences unless detail is needed. Reference specific nu
stream: true,
});
+ let finished = false;
for await (const event of stream) {
if (event.type === 'response.output_text.delta') {
fullResponse += event.delta;
@@ -212,7 +313,7 @@ Keep responses to 2–4 sentences unless detail is needed. Reference specific nu
event.type === 'response.completed' ||
event.type === 'response.incomplete'
) {
- yield { type: 'done' };
+ finished = true;
} else if (event.type === 'response.failed') {
throw new Error(event.response.error?.message ?? 'AI response failed');
} else if (event.type === 'error') {
@@ -225,6 +326,109 @@ Keep responses to 2–4 sentences unless detail is needed. Reference specific nu
data: { userId: user.id, role: 'assistant', content: fullResponse },
});
}
+
+ // Tell the app what was noted, if the notes are ready by now
+ const noted = await Promise.race([
+ noting,
+ new Promise((r) => setTimeout(() => r([]), MEMORY_WAIT_MS)),
+ ]);
+ if (noted.length) yield { type: 'remembered', items: noted };
+ if (finished) yield { type: 'done' };
+ }
+
+ /**
+ * Asks the model whether the message holds anything worth remembering,
+ * and applies its answer. Returns the notes added.
+ */
+ async updateMemories(userId: string, message: string): Promise {
+ const existing = await this.prisma.coachMemory.findMany({
+ where: { userId },
+ orderBy: { createdAt: 'asc' },
+ });
+ const response = await this.openai.responses.create({
+ model: this.model,
+ instructions: memoryInstructions(existing),
+ input: message,
+ max_output_tokens: 2000,
+ reasoning: { effort: 'low' },
+ store: false,
+ text: {
+ format: {
+ type: 'json_schema',
+ name: 'coach_notes',
+ strict: true,
+ schema: MEMORY_SCHEMA as unknown as Record,
+ },
+ },
+ });
+ const update = JSON.parse(response.output_text) as MemoryUpdate;
+ const plan = planMemoryUpdate(existing, {
+ add: Array.isArray(update.add) ? update.add.map(String) : [],
+ remove: Array.isArray(update.remove) ? update.remove.map(String) : [],
+ });
+ if (!plan.add.length && !plan.remove.length) return [];
+ await this.prisma.$transaction([
+ this.prisma.coachMemory.deleteMany({
+ where: { userId, id: { in: plan.remove } },
+ }),
+ this.prisma.coachMemory.createMany({
+ data: plan.add.map((text) => ({ userId, text, source: 'chat' })),
+ }),
+ ]);
+ return plan.add;
+ }
+
+ async listMemories(supabaseId: string) {
+ const user = await this.resolveUser(supabaseId);
+ return this.prisma.coachMemory.findMany({
+ where: { userId: user.id },
+ orderBy: { createdAt: 'desc' },
+ select: { id: true, text: true, source: true, createdAt: true },
+ });
+ }
+
+ /** A note the user writes themselves; these are never dropped automatically. */
+ async addMemory(supabaseId: string, text: string) {
+ const user = await this.resolveUser(supabaseId);
+ const existing = await this.prisma.coachMemory.findMany({
+ where: { userId: user.id },
+ });
+ const plan = planMemoryUpdate(existing, { add: [text], remove: [] });
+ if (!plan.add.length) {
+ throw new HttpException(
+ existing.length >= MAX_MEMORIES
+ ? 'Your coach is full: delete a note first'
+ : 'Your coach already knows that',
+ HttpStatus.CONFLICT,
+ );
+ }
+ const [, created] = await this.prisma.$transaction([
+ this.prisma.coachMemory.deleteMany({
+ where: { userId: user.id, id: { in: plan.remove } },
+ }),
+ this.prisma.coachMemory.create({
+ data: { userId: user.id, text: cleanMemory(text), source: 'user' },
+ select: { id: true, text: true, source: true, createdAt: true },
+ }),
+ ]);
+ return created;
+ }
+
+ async deleteMemory(supabaseId: string, id: string) {
+ const user = await this.resolveUser(supabaseId);
+ const { count } = await this.prisma.coachMemory.deleteMany({
+ where: { id, userId: user.id },
+ });
+ if (!count) throw new NotFoundException('Note not found');
+ return { ok: true };
+ }
+
+ async clearMemories(supabaseId: string) {
+ const user = await this.resolveUser(supabaseId);
+ const { count } = await this.prisma.coachMemory.deleteMany({
+ where: { userId: user.id },
+ });
+ return { deleted: count };
}
async getMessages(supabaseId: string) {
diff --git a/packages/backend/src/ai/coach-memory.db-spec.ts b/packages/backend/src/ai/coach-memory.db-spec.ts
new file mode 100644
index 0000000..0de4872
--- /dev/null
+++ b/packages/backend/src/ai/coach-memory.db-spec.ts
@@ -0,0 +1,171 @@
+import type OpenAI from 'openai';
+import { TestDb } from '../test-utils/db';
+import { AdaptiveService } from '../progress/adaptive.service';
+import { TrendsService } from '../progress/trends.service';
+import { AIService } from './ai.service';
+
+/**
+ * A model that streams a fixed reply for chat requests and returns `notes`
+ * for note-taking requests, recording what it was asked.
+ */
+function fakeModel(notes: unknown) {
+ const calls: { instructions: string; stream?: boolean }[] = [];
+ const client = {
+ responses: {
+ create: (req: { instructions: string; stream?: boolean }) => {
+ calls.push(req);
+ if (req.stream) {
+ return Promise.resolve(
+ (async function* () {
+ await Promise.resolve();
+ yield { type: 'response.output_text.delta', delta: 'Got it. ' };
+ yield {
+ type: 'response.output_text.delta',
+ delta: 'Low impact today.',
+ };
+ yield { type: 'response.completed' };
+ })(),
+ );
+ }
+ return Promise.resolve({ output_text: JSON.stringify(notes) });
+ },
+ },
+ } as unknown as OpenAI;
+ return { client, calls };
+}
+
+async function collect(gen: AsyncGenerator) {
+ const out: T[] = [];
+ for await (const x of gen) out.push(x);
+ return out;
+}
+
+describe('Coach memory (database)', () => {
+ const db = new TestDb();
+ const adaptive = new AdaptiveService(db.prisma, new TrendsService(db.prisma));
+ afterAll(() => db.cleanup());
+
+ it('notes facts from a chat, tells the app, and uses them next time', async () => {
+ const u = await db.user();
+ const { client, calls } = fakeModel({
+ add: ['Has a sore left knee; avoid jumping'],
+ remove: [],
+ });
+ const ai = new AIService(db.prisma, client, 'test', adaptive);
+
+ const events = await collect(
+ ai.streamMessage(u.supabaseId, 'My left knee hurts when I jump', 0),
+ );
+ expect(events.map((e) => e.type)).toEqual([
+ 'delta',
+ 'delta',
+ 'remembered',
+ 'done',
+ ]);
+ expect(events[2].items).toEqual(['Has a sore left knee; avoid jumping']);
+
+ const notes = await ai.listMemories(u.supabaseId);
+ expect(notes.map((n) => [n.text, n.source])).toEqual([
+ ['Has a sore left knee; avoid jumping', 'chat'],
+ ]);
+
+ // The next reply's instructions carry the note
+ await collect(ai.streamMessage(u.supabaseId, 'What should I do today?', 0));
+ const chat = calls.filter((c) => c.stream).pop()!;
+ expect(chat.instructions).toContain('Has a sore left knee; avoid jumping');
+ // and the note-taker sees it with its id, so it can remove it later
+ const noteTaker = calls.filter((c) => !c.stream).pop()!;
+ expect(noteTaker.instructions).toContain(`[${notes[0].id}]`);
+ });
+
+ it('replaces a note the user contradicts', async () => {
+ const u = await db.user();
+ const old = await db.prisma.coachMemory.create({
+ data: { userId: u.id, text: 'Has a sore left knee' },
+ });
+ const { client } = fakeModel({
+ add: ['Knee has healed; back to running'],
+ remove: [old.id],
+ });
+ const ai = new AIService(db.prisma, client, 'test', adaptive);
+ await ai.updateMemories(u.id, 'My knee is all better now, running again');
+ expect((await ai.listMemories(u.supabaseId)).map((n) => n.text)).toEqual([
+ 'Knee has healed; back to running',
+ ]);
+ });
+
+ it("doesn't ask about short messages, and skips the event when nothing is new", async () => {
+ const u = await db.user();
+ const { client, calls } = fakeModel({ add: [], remove: [] });
+ const ai = new AIService(db.prisma, client, 'test', adaptive);
+ const short = await collect(ai.streamMessage(u.supabaseId, 'thanks!', 0));
+ expect(short.map((e) => e.type)).toEqual(['delta', 'delta', 'done']);
+ expect(calls.filter((c) => !c.stream)).toHaveLength(0);
+
+ const long = await collect(
+ ai.streamMessage(u.supabaseId, 'How much protein should I eat?', 0),
+ );
+ expect(long.map((e) => e.type)).not.toContain('remembered');
+ expect(calls.filter((c) => !c.stream)).toHaveLength(1);
+ });
+
+ it('lets the user add, delete and clear notes', async () => {
+ const u = await db.user();
+ const ai = new AIService(db.prisma, fakeModel({}).client, 'test', adaptive);
+ const note = await ai.addMemory(u.supabaseId, ' Allergic to peanuts ');
+ expect([note.text, note.source]).toEqual(['Allergic to peanuts', 'user']);
+ await expect(
+ ai.addMemory(u.supabaseId, 'allergic to peanuts'),
+ ).rejects.toThrow('already knows');
+
+ const other = await db.user();
+ await expect(ai.deleteMemory(other.supabaseId, note.id)).rejects.toThrow(
+ 'Note not found',
+ );
+ await ai.deleteMemory(u.supabaseId, note.id);
+ await ai.addMemory(u.supabaseId, 'Trains at lunch');
+ await ai.addMemory(u.supabaseId, 'Has dumbbells at home');
+ expect(await ai.clearMemories(u.supabaseId)).toEqual({ deleted: 2 });
+ });
+
+ it("gives the coach the week's averages over logged days", async () => {
+ const u = await db.user();
+ const day = (n: number) => new Date(Date.now() - n * 86_400_000);
+ await db.prisma.foodLog.createMany({
+ data: [
+ {
+ userId: u.id,
+ name: 'a',
+ mealType: 'lunch',
+ calories: 1500,
+ proteinG: 80,
+ loggedAt: day(1),
+ },
+ {
+ userId: u.id,
+ name: 'b',
+ mealType: 'dinner',
+ calories: 500,
+ proteinG: 40,
+ loggedAt: day(1),
+ },
+ {
+ userId: u.id,
+ name: 'c',
+ mealType: 'lunch',
+ calories: 1800,
+ proteinG: 100,
+ loggedAt: day(3),
+ },
+ ],
+ });
+ const { client, calls } = fakeModel({ add: [], remove: [] });
+ const ai = new AIService(db.prisma, client, 'test', adaptive);
+ await collect(ai.streamMessage(u.supabaseId, 'hi', 0));
+ const chat = calls.find((c) => c.stream)!;
+ expect(chat.instructions).toContain('Food logged on 2 of the last 7 days');
+ expect(chat.instructions).toContain(
+ '1900 kcal and 110g protein on average',
+ );
+ });
+});
diff --git a/packages/backend/src/ai/coach-memory.spec.ts b/packages/backend/src/ai/coach-memory.spec.ts
new file mode 100644
index 0000000..c9191e3
--- /dev/null
+++ b/packages/backend/src/ai/coach-memory.spec.ts
@@ -0,0 +1,84 @@
+import {
+ MAX_MEMORIES,
+ cleanMemory,
+ mayHoldFacts,
+ planMemoryUpdate,
+ type StoredMemory,
+} from './coach-memory';
+
+const mem = (
+ id: string,
+ text: string,
+ daysAgo = 0,
+ source = 'chat',
+): StoredMemory => ({
+ id,
+ text,
+ source,
+ createdAt: new Date(Date.now() - daysAgo * 86_400_000),
+});
+
+describe('planMemoryUpdate', () => {
+ it('adds new notes and removes the ones it replaces', () => {
+ const existing = [mem('a', 'Has a sore left knee'), mem('b', 'Vegetarian')];
+ expect(
+ planMemoryUpdate(existing, {
+ add: ['Knee has healed; can run again'],
+ remove: ['a', 'not-an-id'],
+ }),
+ ).toEqual({ remove: ['a'], add: ['Knee has healed; can run again'] });
+ });
+
+ it('skips duplicates and blanks', () => {
+ const existing = [mem('a', 'Trains before work, around 6am')];
+ expect(
+ planMemoryUpdate(existing, {
+ add: [
+ 'trains before work around 6am!',
+ ' ',
+ 'Hates running',
+ 'hates running',
+ ],
+ remove: [],
+ }),
+ ).toEqual({ remove: [], add: ['Hates running'] });
+ });
+
+ it("past the limit, drops the coach's oldest notes but keeps the user's", () => {
+ const existing = [
+ mem('user-old', 'Allergic to peanuts', 100, 'user'),
+ ...Array.from({ length: MAX_MEMORIES - 1 }, (_, i) =>
+ mem(`c${i}`, `Note ${i}`, 50 - i),
+ ),
+ ];
+ const plan = planMemoryUpdate(existing, {
+ add: ['New one', 'Another'],
+ remove: [],
+ });
+ expect(plan.add).toEqual(['New one', 'Another']);
+ expect(plan.remove).toEqual(['c0', 'c1']);
+ });
+
+ it('when every note is hand-written, only adds what fits', () => {
+ const existing = Array.from({ length: MAX_MEMORIES }, (_, i) =>
+ mem(`u${i}`, `Mine ${i}`, 0, 'user'),
+ );
+ expect(planMemoryUpdate(existing, { add: ['x y z'], remove: [] })).toEqual({
+ remove: [],
+ add: [],
+ });
+ });
+});
+
+describe('helpers', () => {
+ it('cleans notes to one short line', () => {
+ expect(cleanMemory(' Has\n a bad back ')).toBe('Has a bad back');
+ expect(cleanMemory('x'.repeat(300))).toHaveLength(160);
+ });
+
+ it('only asks about messages with some substance', () => {
+ expect(mayHoldFacts('thanks!')).toBe(false);
+ expect(mayHoldFacts('ok cool')).toBe(false);
+ expect(mayHoldFacts('I hurt my knee running yesterday')).toBe(true);
+ });
+});
diff --git a/packages/backend/src/ai/coach-memory.ts b/packages/backend/src/ai/coach-memory.ts
new file mode 100644
index 0000000..8407046
--- /dev/null
+++ b/packages/backend/src/ai/coach-memory.ts
@@ -0,0 +1,103 @@
+/**
+ * What the coach remembers between chats: short facts that change how it
+ * should coach (an injury, foods avoided, when they can train). The model
+ * proposes changes after each message; these helpers decide what's kept.
+ */
+
+export const MAX_MEMORIES = 40;
+export const MAX_MEMORY_LENGTH = 160;
+
+export interface StoredMemory {
+ id: string;
+ text: string;
+ source: string;
+ createdAt: Date;
+}
+
+export interface MemoryUpdate {
+ add: string[];
+ remove: string[];
+}
+
+export const MEMORY_SCHEMA = {
+ type: 'object',
+ additionalProperties: false,
+ required: ['add', 'remove'],
+ properties: {
+ add: { type: 'array', items: { type: 'string' } },
+ remove: { type: 'array', items: { type: 'string' } },
+ },
+} as const;
+
+export function memoryInstructions(existing: { id: string; text: string }[]) {
+ const list = existing.length
+ ? existing.map((m) => `- [${m.id}] ${m.text}`).join('\n')
+ : '(none yet)';
+ return `You keep the long-term notes of a fitness and nutrition coach about one person.
+
+Current notes:
+${list}
+
+Read the person's latest message. Return:
+- add: new lasting facts worth remembering for future coaching: injuries or health conditions, foods they avoid, dislike or are allergic to, foods they love, their schedule or when they can train, equipment they have, how they like to be coached, life context (shift work, new baby, training for an event). Write each as a short third-person note under 15 words, e.g. "Has a sore left knee; avoid jumping" or "Trains before work, around 6am".
+- remove: ids of notes the message makes wrong or out of date (e.g. the knee has healed). If a fact changed, remove the old note and add the new one.
+
+Don't note today's numbers, meals or workouts (the app tracks those), passing moods, questions, or anything already in the notes. Most messages contain nothing new: then return empty lists.`;
+}
+
+const key = (text: string) =>
+ text
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N} ]/gu, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+
+/** Cleans a note: one line, trimmed, within the length limit. */
+export function cleanMemory(text: string): string {
+ return text.replace(/\s+/g, ' ').trim().slice(0, MAX_MEMORY_LENGTH);
+}
+
+/**
+ * Turns the model's proposal into what to delete and create. Unknown ids
+ * are ignored, duplicates skipped, and past the limit the oldest notes the
+ * coach took go first (notes the user wrote are kept).
+ */
+export function planMemoryUpdate(
+ existing: StoredMemory[],
+ update: MemoryUpdate,
+): { remove: string[]; add: string[] } {
+ const ids = new Set(existing.map((m) => m.id));
+ const remove = new Set(update.remove.filter((id) => ids.has(id)));
+ const kept = existing.filter((m) => !remove.has(m.id));
+ const seen = new Set(kept.map((m) => key(m.text)));
+
+ const add: string[] = [];
+ for (const raw of update.add) {
+ const text = cleanMemory(raw);
+ const k = key(text);
+ if (k.length < 3 || seen.has(k)) continue;
+ seen.add(k);
+ add.push(text);
+ }
+
+ // Over the limit: drop the oldest of the coach's own notes
+ let over = kept.length + add.length - MAX_MEMORIES;
+ if (over > 0) {
+ const oldestFirst = kept
+ .filter((m) => m.source !== 'user')
+ .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
+ for (const m of oldestFirst) {
+ if (over <= 0) break;
+ remove.add(m.id);
+ over--;
+ }
+ // Still over (all hand-written): add only what fits
+ if (over > 0) add.splice(add.length - over, over);
+ }
+ return { remove: [...remove], add };
+}
+
+/** Worth asking the model about: more than a couple of words. */
+export function mayHoldFacts(message: string): boolean {
+ return message.trim().split(/\s+/).length >= 4;
+}
diff --git a/packages/backend/src/alerts/alerts.db-spec.ts b/packages/backend/src/alerts/alerts.db-spec.ts
index 6bb778c..2acd3a1 100644
--- a/packages/backend/src/alerts/alerts.db-spec.ts
+++ b/packages/backend/src/alerts/alerts.db-spec.ts
@@ -2,6 +2,8 @@ import { TestDb } from '../test-utils/db';
import { dateMarker } from '../common/day';
import { AlertsService } from './alerts.service';
import { ChallengesService } from '../challenges/challenges.service';
+import { AdaptiveService } from '../progress/adaptive.service';
+import { TrendsService } from '../progress/trends.service';
describe('AlertsService (database)', () => {
const db = new TestDb();
@@ -9,6 +11,7 @@ describe('AlertsService (database)', () => {
db.prisma,
db.notifications,
new ChallengesService(db.prisma, db.notifications),
+ new AdaptiveService(db.prisma, new TrendsService(db.prisma)),
);
const inbox = (userId: string) =>
db.prisma.notification.findMany({ where: { userId } });
@@ -161,4 +164,112 @@ describe('AlertsService (database)', () => {
await alerts.sendWeeklyProgress(new Date('2026-11-07T18:05:00Z'));
expect(await inbox(saturday.id)).toHaveLength(0);
});
+
+ describe('coach check-ins', () => {
+ // 13:05 UTC on Wednesday 4 November
+ const lunchtime = new Date('2026-11-04T13:05:00Z');
+ const at = (date: string) => new Date(`${date}T12:00:00Z`);
+
+ it('sends the first one that applies, once a week', async () => {
+ const u = await db.user();
+ // Logged food regularly until 4 days ago, and trained until 6 days ago
+ for (const d of [
+ '2026-10-25',
+ '2026-10-27',
+ '2026-10-29',
+ '2026-10-31',
+ ]) {
+ await db.prisma.foodLog.create({
+ data: {
+ userId: u.id,
+ name: 'x',
+ mealType: 'lunch',
+ calories: 500,
+ loggedAt: at(d),
+ },
+ });
+ }
+ for (const d of ['2026-10-24', '2026-10-26', '2026-10-29']) {
+ await db.prisma.activityLog.create({
+ data: {
+ userId: u.id,
+ activityType: 'running',
+ durationMin: 30,
+ loggedAt: at(d),
+ },
+ });
+ }
+
+ await alerts.sendCoachCheckIns(lunchtime);
+ let items = await inbox(u.id);
+ expect(items.map((n) => [n.type, n.title])).toEqual([
+ ['coach_checkin', 'Quick catch-up?'],
+ ]);
+ expect(items[0].data).toEqual({ screen: 'food', rule: 'logging_gap' });
+
+ // The next day: logging gap already sent this week, so the next rule
+ await alerts.sendCoachCheckIns(new Date('2026-11-05T13:05:00Z'));
+ items = await inbox(u.id);
+ expect(
+ items.map((n) => (n.data as { rule: string }).rule).sort(),
+ ).toEqual(['activity_gap', 'logging_gap']);
+ // And again: nothing left to say this week
+ await alerts.sendCoachCheckIns(new Date('2026-11-06T13:05:00Z'));
+ expect(await inbox(u.id)).toHaveLength(2);
+ });
+
+ it('stays quiet on track, when progress alerts are off, and on Sundays', async () => {
+ const fine = await db.user();
+ const off = await db.user();
+ await db.prisma.user.update({
+ where: { id: off.id },
+ data: { notifProgress: false },
+ });
+ for (const u of [fine, off]) {
+ for (const d of [
+ '2026-10-25',
+ '2026-10-27',
+ '2026-10-29',
+ '2026-10-30',
+ ]) {
+ await db.prisma.foodLog.create({
+ data: {
+ userId: u.id,
+ name: 'x',
+ mealType: 'lunch',
+ calories: 500,
+ loggedAt: at(d),
+ },
+ });
+ }
+ }
+ await db.prisma.foodLog.create({
+ data: {
+ userId: fine.id,
+ name: 'x',
+ mealType: 'lunch',
+ calories: 500,
+ loggedAt: at('2026-11-03'),
+ },
+ });
+ await alerts.sendCoachCheckIns(lunchtime);
+ expect(await inbox(fine.id)).toHaveLength(0);
+ expect(await inbox(off.id)).toHaveLength(0);
+
+ const sunday = await db.user();
+ for (const d of ['2026-10-25', '2026-10-27', '2026-10-29']) {
+ await db.prisma.foodLog.create({
+ data: {
+ userId: sunday.id,
+ name: 'x',
+ mealType: 'lunch',
+ calories: 500,
+ loggedAt: at(d),
+ },
+ });
+ }
+ await alerts.sendCoachCheckIns(new Date('2026-11-08T13:05:00Z'));
+ expect(await inbox(sunday.id)).toHaveLength(0);
+ });
+ });
});
diff --git a/packages/backend/src/alerts/alerts.module.ts b/packages/backend/src/alerts/alerts.module.ts
index b6632ab..a6c80e0 100644
--- a/packages/backend/src/alerts/alerts.module.ts
+++ b/packages/backend/src/alerts/alerts.module.ts
@@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
import { NotificationsModule } from '../notifications/notifications.module';
import { AlertsService } from './alerts.service';
import { ChallengesModule } from '../challenges/challenges.module';
+import { ProgressModule } from '../progress/progress.module';
@Module({
- imports: [NotificationsModule, ChallengesModule],
+ imports: [NotificationsModule, ChallengesModule, ProgressModule],
providers: [AlertsService],
})
export class AlertsModule {}
diff --git a/packages/backend/src/alerts/alerts.service.ts b/packages/backend/src/alerts/alerts.service.ts
index adcaff2..339f893 100644
--- a/packages/backend/src/alerts/alerts.service.ts
+++ b/packages/backend/src/alerts/alerts.service.ts
@@ -3,6 +3,7 @@ import { Cron } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
import { NotificationsService } from '../notifications/notifications.service';
import { ChallengesService } from '../challenges/challenges.service';
+import { AdaptiveService } from '../progress/adaptive.service';
import {
addDays,
dateMarker,
@@ -11,6 +12,8 @@ import {
weekStart,
} from '../common/day';
import { calculateStreak } from '../habits/habits.streak';
+import { macroTargets } from '../common/nutrition';
+import { checkInsFor } from './coach-checkins';
import {
isOffTrack,
offsetRangesAtLocalHour,
@@ -21,6 +24,7 @@ import {
export const STREAK_ALERT_HOUR = 20; // 8pm local
export const WEEKLY_ALERT_HOUR = 18; // 6pm local, on Sundays
+export const COACH_CHECKIN_HOUR = 13; // 1pm local, not on Sundays
const MIN_STREAK = 2;
const USER_PAGE = 500;
@@ -38,6 +42,7 @@ export class AlertsService {
private prisma: PrismaService,
private notifications: NotificationsService,
private challenges: ChallengesService,
+ private adaptive: AdaptiveService,
) {}
@Cron('5 * * * *')
@@ -49,9 +54,10 @@ export class AlertsService {
const ended = await this.challenges.finishEnded(now);
const streaks = await this.sendStreakAlerts(now);
const weekly = await this.sendWeeklyProgress(now);
+ const coach = await this.sendCoachCheckIns(now);
const pruned = await this.notifications.prune();
this.logger.log(
- `Alerts: ${ended} challenges ended, ${streaks} streak, ${weekly} weekly, ${pruned} old removed`,
+ `Alerts: ${ended} challenges ended, ${streaks} streak, ${weekly} weekly, ${coach} coach, ${pruned} old removed`,
);
} catch (err) {
this.logger.error(`Hourly alerts failed: ${(err as Error).message}`);
@@ -83,6 +89,7 @@ export class AlertsService {
utcOffset: true,
activeMinutesGoal: true,
notifOffTrackOnly: true,
+ supabaseId: true,
},
orderBy: { id: 'asc' },
take: USER_PAGE,
@@ -179,9 +186,19 @@ export class AlertsService {
};
if (user.notifOffTrackOnly && !isOffTrack(stats)) continue;
+ // The weekly check-in also carries a target adjustment, if there is one
+ const checkIn = await this.adaptive
+ .checkIn(user.supabaseId, user.utcOffset)
+ .catch(() => null);
+ const alert = weeklyAlert(stats);
+ const s = checkIn?.suggestion;
+ if (s) {
+ alert.body += ` Your coach suggests ${s.change > 0 ? 'raising' : 'lowering'} your target to ${s.suggested.toLocaleString('en-US')} kcal: tap to review.`;
+ }
+
const delivered = await this.notifications.notify(user.id, {
type: 'weekly_progress',
- ...weeklyAlert(stats),
+ ...alert,
data: { screen: 'stats' },
dedupeKey: `weekly:${monday}`,
});
@@ -189,4 +206,95 @@ export class AlertsService {
}
return sent;
}
+
+ /**
+ * 1pm: one check-in from the coach, if a pattern calls for one. Each kind
+ * is sent at most once a week; Sundays are left to the weekly summary.
+ */
+ async sendCoachCheckIns(now: Date): Promise {
+ const users = this.usersAtLocalHour(
+ now,
+ COACH_CHECKIN_HOUR,
+ 'notifProgress',
+ );
+ let sent = 0;
+ for await (const user of users) {
+ const offset = user.utcOffset;
+ const today = localDateOf(now, offset);
+ if (new Date(`${today}T00:00:00Z`).getUTCDay() === 0) continue;
+
+ const since14 = dayRange(addDays(today, -14), offset).start;
+ const todayStart = dayRange(today, offset).start;
+ const weekAgo = dayRange(addDays(today, -7), offset).start;
+ const [profile, food, activity, weights] = await Promise.all([
+ this.prisma.user.findUnique({
+ where: { id: user.id },
+ select: {
+ calorieGoal: true,
+ goalFocus: true,
+ dietType: true,
+ primaryGoal: true,
+ },
+ }),
+ this.prisma.foodLog.findMany({
+ where: { userId: user.id, loggedAt: { gte: since14, lte: now } },
+ select: { loggedAt: true, proteinG: true },
+ }),
+ this.prisma.activityLog.findMany({
+ where: { userId: user.id, loggedAt: { gte: since14, lte: now } },
+ select: { loggedAt: true },
+ }),
+ this.prisma.weightLog.findMany({
+ where: {
+ userId: user.id,
+ day: { gte: dateMarker(addDays(today, -21)) },
+ },
+ select: { day: true, weightKg: true },
+ }),
+ ]);
+ if (!profile) continue;
+
+ // Protein per logged day over the last 7 full days
+ const protein = new Map();
+ for (const f of food) {
+ if (f.loggedAt < weekAgo || f.loggedAt >= todayStart) continue;
+ const d = localDateOf(f.loggedAt, offset);
+ protein.set(d, (protein.get(d) ?? 0) + f.proteinG);
+ }
+
+ const checkIns = checkInsFor({
+ today,
+ foodDays: food.map((f) => localDateOf(f.loggedAt, offset)),
+ proteinByDay: [...protein].map(([date, proteinG]) => ({
+ date,
+ proteinG,
+ })),
+ proteinTarget: macroTargets(profile.calorieGoal, profile.goalFocus)
+ .proteinG,
+ dietType: profile.dietType,
+ workoutDays: activity.map((a) => localDateOf(a.loggedAt, offset)),
+ weights: weights.map((w) => ({
+ date: w.day.toISOString().slice(0, 10),
+ weightKg: w.weightKg,
+ })),
+ primaryGoal: profile.primaryGoal,
+ });
+
+ // The first one not already sent this week
+ for (const c of checkIns) {
+ const delivered = await this.notifications.notify(user.id, {
+ type: 'coach_checkin',
+ title: c.title,
+ body: c.body,
+ data: { screen: c.screen, rule: c.rule },
+ dedupeKey: `coach:${c.rule}:${weekStart(today)}`,
+ });
+ if (delivered) {
+ sent++;
+ break;
+ }
+ }
+ }
+ return sent;
+ }
}
diff --git a/packages/backend/src/alerts/coach-checkins.spec.ts b/packages/backend/src/alerts/coach-checkins.spec.ts
new file mode 100644
index 0000000..5f19bd2
--- /dev/null
+++ b/packages/backend/src/alerts/coach-checkins.spec.ts
@@ -0,0 +1,76 @@
+import { addDays } from '../common/day';
+import { checkInsFor, type CheckInInput } from './coach-checkins';
+
+const today = '2026-11-04';
+const ago = (n: number) => addDays(today, -n);
+const base: CheckInInput = {
+ today,
+ foodDays: [0, 1, 2, 3, 4, 5, 6].map(ago),
+ proteinByDay: [1, 2, 3, 4, 5].map((n) => ({ date: ago(n), proteinG: 140 })),
+ proteinTarget: 150,
+ dietType: null,
+ workoutDays: [1, 3, 5, 8].map(ago),
+ weights: [],
+ primaryGoal: 'lose_weight',
+};
+const rules = (over: Partial) =>
+ checkInsFor({ ...base, ...over }).map((c) => c.rule);
+
+describe('checkInsFor', () => {
+ it('says nothing when things are on track', () => {
+ expect(checkInsFor(base)).toEqual([]);
+ });
+
+ it('notices when logging stops after a regular run', () => {
+ const [c] = checkInsFor({ ...base, foodDays: [3, 4, 6, 9].map(ago) });
+ expect(c.rule).toBe('logging_gap');
+ expect(c.body).toContain('No meals logged for 3 days');
+ // Never a regular logger: nothing to say
+ expect(rules({ foodDays: [10].map(ago) })).not.toContain('logging_gap');
+ // Logged today: fine
+ expect(rules({ foodDays: [0, 5, 6, 7].map(ago) })).not.toContain(
+ 'logging_gap',
+ );
+ });
+
+ it('notices a run of missed workouts', () => {
+ const [c] = checkInsFor({ ...base, workoutDays: [5, 7, 9].map(ago) });
+ expect(c).toMatchObject({ rule: 'activity_gap', screen: 'activity' });
+ expect(c.body).toContain("It's been 5 days");
+ expect(rules({ workoutDays: [4, 7, 9].map(ago) })).not.toContain(
+ 'activity_gap',
+ );
+ expect(rules({ workoutDays: [] })).not.toContain('activity_gap');
+ });
+
+ it('flags low protein, with ideas that fit the diet', () => {
+ const low = [1, 2, 3, 4].map((n) => ({ date: ago(n), proteinG: 90 }));
+ const [c] = checkInsFor({ ...base, proteinByDay: low, dietType: 'vegan' });
+ expect(c.rule).toBe('protein_low');
+ expect(c.body).toContain('averaged 90 g');
+ expect(c.body).toContain('tofu');
+ // Three days isn't enough to judge
+ expect(rules({ proteinByDay: low.slice(0, 3) })).toEqual([]);
+ });
+
+ it('spots a plateau only when losing weight and weighing in regularly', () => {
+ const flat = [20, 17, 14, 10, 7, 3, 0].map((n, i) => ({
+ date: ago(n),
+ weightKg: 80 + (i % 2 ? 0.2 : -0.2),
+ }));
+ expect(rules({ weights: flat })).toEqual(['plateau']);
+ expect(rules({ weights: flat, primaryGoal: 'build_muscle' })).toEqual([]);
+ const falling = flat.map((w, i) => ({ ...w, weightKg: 82 - i * 0.3 }));
+ expect(rules({ weights: falling })).toEqual([]);
+ expect(rules({ weights: flat.slice(0, 5) })).toEqual([]);
+ });
+
+ it('lists the most useful first', () => {
+ expect(
+ rules({
+ foodDays: [4, 5, 6].map(ago),
+ workoutDays: [6, 8, 10].map(ago),
+ }),
+ ).toEqual(['logging_gap', 'activity_gap']);
+ });
+});
diff --git a/packages/backend/src/alerts/coach-checkins.ts b/packages/backend/src/alerts/coach-checkins.ts
new file mode 100644
index 0000000..551d70f
--- /dev/null
+++ b/packages/backend/src/alerts/coach-checkins.ts
@@ -0,0 +1,137 @@
+/**
+ * The coach's daily check-in: the most useful thing to say, if anything,
+ * from a few clear patterns in what the user logged. Rules, not a model:
+ * cheap to run for everyone, and each message says exactly why it was sent.
+ */
+import { addDays } from '../common/day';
+
+export type CheckInRule =
+ 'logging_gap' | 'activity_gap' | 'protein_low' | 'plateau';
+
+export interface CheckInInput {
+ /** The user's local date */
+ today: string;
+ /** Local dates with food logged, any order, over the last 14+ days */
+ foodDays: string[];
+ /** Protein eaten on each of the last 7 full days that had food logged */
+ proteinByDay: { date: string; proteinG: number }[];
+ proteinTarget: number;
+ dietType: string | null;
+ /** Local dates with a workout, over the last 14+ days */
+ workoutDays: string[];
+ /** Weigh-ins over the last 21 days */
+ weights: { date: string; weightKg: number }[];
+ primaryGoal: string;
+}
+
+export interface CheckIn {
+ rule: CheckInRule;
+ title: string;
+ body: string;
+ /** The app screen it opens */
+ screen: 'food' | 'activity' | 'stats';
+}
+
+const between = (d: string, from: string, to: string) => d >= from && d <= to;
+const daysBetween = (a: string, b: string) =>
+ Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000);
+
+const PROTEIN_IDEAS: Record = {
+ vegan: 'tofu, tempeh, lentils or soy yogurt',
+ vegetarian: 'Greek yogurt, eggs, cottage cheese or lentils',
+ pescatarian: 'Greek yogurt, eggs or a tin of tuna',
+};
+
+/** Slope of a least-squares line through the weigh-ins, in kg per week. */
+function kgPerWeek(weights: { date: string; weightKg: number }[]) {
+ const t0 = Date.parse(weights[0].date);
+ const pts = weights.map((w) => [
+ (Date.parse(w.date) - t0) / 86_400_000,
+ w.weightKg,
+ ]);
+ const n = pts.length;
+ const mx = pts.reduce((s, [x]) => s + x, 0) / n;
+ const my = pts.reduce((s, [, y]) => s + y, 0) / n;
+ const sxx = pts.reduce((s, [x]) => s + (x - mx) ** 2, 0);
+ if (sxx === 0) return 0;
+ return (pts.reduce((s, [x, y]) => s + (x - mx) * (y - my), 0) / sxx) * 7;
+}
+
+/** Every check-in that applies today, most useful first. */
+export function checkInsFor(input: CheckInInput): CheckIn[] {
+ const { today } = input;
+ const out: CheckIn[] = [];
+
+ // Logged regularly, then stopped: nothing yesterday or the day before
+ const food = new Set(input.foodDays);
+ const recentFood = [0, 1, 2].some((n) => food.has(addDays(today, -n)));
+ const earlierFood = [...food].filter((d) =>
+ between(d, addDays(today, -14), addDays(today, -3)),
+ );
+ if (!recentFood && earlierFood.length >= 3) {
+ const last = earlierFood.sort().pop()!;
+ const ago = daysBetween(last, today);
+ out.push({
+ rule: 'logging_gap',
+ title: 'Quick catch-up?',
+ body: `No meals logged for ${ago} days. Tap ✨ Smart log and just describe what you ate: it takes seconds, and rough is fine.`,
+ screen: 'food',
+ });
+ }
+
+ // Trained regularly, then nothing for 5 days
+ const workouts = [...new Set(input.workoutDays)].sort();
+ const lastWorkout = workouts[workouts.length - 1];
+ const earlierWorkouts = workouts.filter((d) =>
+ between(d, addDays(today, -14), addDays(today, -5)),
+ );
+ if (
+ lastWorkout &&
+ lastWorkout < addDays(today, -4) &&
+ earlierWorkouts.length >= 3
+ ) {
+ out.push({
+ rule: 'activity_gap',
+ title: 'Ready to get moving again?',
+ body: `It's been ${daysBetween(lastWorkout, today)} days since your last workout. Even a 20-minute walk today keeps the habit alive.`,
+ screen: 'activity',
+ });
+ }
+
+ // Short on protein most logged days this week
+ const logged = input.proteinByDay;
+ if (logged.length >= 4 && input.proteinTarget > 0) {
+ const avg = logged.reduce((s, d) => s + d.proteinG, 0) / logged.length;
+ if (avg < input.proteinTarget * 0.75) {
+ const ideas =
+ PROTEIN_IDEAS[input.dietType ?? ''] ??
+ 'Greek yogurt, eggs, chicken or a tin of tuna';
+ out.push({
+ rule: 'protein_low',
+ title: 'Protein is running low',
+ body: `You've averaged ${Math.round(avg)} g of protein against a ${input.proteinTarget} g target this week. Adding ${ideas} to one meal a day closes most of the gap.`,
+ screen: 'food',
+ });
+ }
+ }
+
+ // Trying to lose weight, but three weeks without change
+ const weights = [...input.weights].sort((a, b) =>
+ a.date.localeCompare(b.date),
+ );
+ if (
+ input.primaryGoal === 'lose_weight' &&
+ weights.length >= 6 &&
+ daysBetween(weights[0].date, weights[weights.length - 1].date) >= 14 &&
+ Math.abs(kgPerWeek(weights)) < 0.1
+ ) {
+ out.push({
+ rule: 'plateau',
+ title: 'Your weight has held steady',
+ body: "Your weight's barely moved in three weeks. That's normal now and then. Open Stats to see what your logs say you burn, and whether your target needs a nudge.",
+ screen: 'stats',
+ });
+ }
+
+ return out;
+}
diff --git a/packages/backend/src/app.module.ts b/packages/backend/src/app.module.ts
index 5b8fe17..5bf753e 100644
--- a/packages/backend/src/app.module.ts
+++ b/packages/backend/src/app.module.ts
@@ -7,6 +7,7 @@ import { PrismaModule } from './prisma/prisma.module';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { FoodModule } from './food/food.module';
+import { MealParseModule } from './meal-parse/meal-parse.module';
import { ActivityModule } from './activity/activity.module';
import { HabitsModule } from './habits/habits.module';
import { SocialModule } from './social/social.module';
@@ -16,6 +17,7 @@ import { NotificationsModule } from './notifications/notifications.module';
import { WorkoutPlanModule } from './workout-plan/workout-plan.module';
import { AlertsModule } from './alerts/alerts.module';
import { ProgressModule } from './progress/progress.module';
+import { HealthModule } from './health/health.module';
import { AppController } from './app.controller';
import { validateEnv } from './config/env';
import { AllExceptionsFilter } from './observability/all-exceptions.filter';
@@ -39,6 +41,7 @@ import { UserThrottlerGuard } from './observability/throttler.guard';
AuthModule,
UsersModule,
FoodModule,
+ MealParseModule,
ActivityModule,
HabitsModule,
SocialModule,
@@ -48,6 +51,7 @@ import { UserThrottlerGuard } from './observability/throttler.guard';
WorkoutPlanModule,
AlertsModule,
ProgressModule,
+ HealthModule,
],
controllers: [AppController],
providers: [
diff --git a/packages/backend/src/challenges/challenges.service.ts b/packages/backend/src/challenges/challenges.service.ts
index cd30c81..fa4b9df 100644
--- a/packages/backend/src/challenges/challenges.service.ts
+++ b/packages/backend/src/challenges/challenges.service.ts
@@ -8,7 +8,7 @@ import {
import type { Challenge } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { NotificationsService } from '../notifications/notifications.service';
-import { dayRange, localToday } from '../common/day';
+import { dayRange, localDateOf, localToday } from '../common/day';
import type { CreateChallengeDto } from './challenges.dto';
import {
GOAL_LIMITS,
@@ -81,6 +81,75 @@ export class ChallengesService {
});
}
+ /**
+ * Steps each user took between two instants. Per local day it takes the
+ * larger of the phone's step count (synced from the health app) and the
+ * steps entered on workouts, so a walk logged by hand isn't counted twice.
+ */
+ private async stepTotals(userIds: string[], from: Date, until: Date) {
+ const [users, logs, days] = await Promise.all([
+ this.prisma.user.findMany({
+ where: { id: { in: userIds } },
+ select: { id: true, utcOffset: true },
+ }),
+ this.prisma.activityLog.findMany({
+ where: {
+ userId: { in: userIds },
+ loggedAt: { gte: from, lt: until },
+ steps: { gt: 0 },
+ },
+ select: { userId: true, loggedAt: true, steps: true },
+ }),
+ this.prisma.healthDay.findMany({
+ where: {
+ userId: { in: userIds },
+ steps: { not: null },
+ // Whole days that overlap the window, in any time zone
+ day: {
+ gte: new Date(from.getTime() - 86_400_000),
+ lt: new Date(until.getTime() + 86_400_000),
+ },
+ },
+ select: { userId: true, day: true, steps: true },
+ }),
+ ]);
+ const offsets = new Map(users.map((u) => [u.id, u.utcOffset]));
+ const perDay = new Map<
+ string,
+ Map
+ >();
+ const slot = (userId: string, date: string) => {
+ const days =
+ perDay.get(userId) ??
+ new Map();
+ perDay.set(userId, days);
+ const entry = days.get(date) ?? { logged: 0, phone: 0 };
+ days.set(date, entry);
+ return entry;
+ };
+ for (const l of logs) {
+ slot(
+ l.userId,
+ localDateOf(l.loggedAt, offsets.get(l.userId) ?? 0),
+ ).logged += l.steps ?? 0;
+ }
+ for (const d of days) {
+ // Only days that fall inside the challenge in the user's own time zone
+ const date = d.day.toISOString().slice(0, 10);
+ const { start } = dayRange(date, offsets.get(d.userId) ?? 0);
+ if (start < new Date(from.getTime() - 1) || start >= until) continue;
+ slot(d.userId, date).phone = d.steps ?? 0;
+ }
+ const totals = new Map();
+ for (const [userId, dates] of perDay) {
+ let total = 0;
+ for (const { logged, phone } of dates.values())
+ total += Math.max(logged, phone);
+ totals.set(userId, total);
+ }
+ return totals;
+ }
+
/**
* Recomputes every participant's score from the workouts they logged
* between the start and the end (or now), and marks the goal reached.
@@ -104,12 +173,20 @@ export class ChallengesService {
_count: { _all: true },
});
const byUser = new Map(sums.map((s) => [s.userId, s]));
+ const steps =
+ c.type === 'steps' || c.type === 'group_steps'
+ ? await this.stepTotals(
+ participants.map((p) => p.userId),
+ c.startDate,
+ until,
+ )
+ : null;
let total = 0;
for (const p of participants) {
const s = byUser.get(p.userId);
const value = scoreFor(c.type, {
- steps: s?._sum.steps ?? 0,
+ steps: steps?.get(p.userId) ?? s?._sum.steps ?? 0,
minutes: s?._sum.durationMin ?? 0,
workouts: s?._count._all ?? 0,
});
diff --git a/packages/backend/src/health/health.controller.ts b/packages/backend/src/health/health.controller.ts
new file mode 100644
index 0000000..e355feb
--- /dev/null
+++ b/packages/backend/src/health/health.controller.ts
@@ -0,0 +1,29 @@
+import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
+import { AuthGuard } from '../auth/auth.guard';
+import { CurrentUser } from '../common/current-user.decorator';
+import { UtcOffset } from '../common/utc-offset.decorator';
+import { HealthImportDto } from './health.dto';
+import { HealthService } from './health.service';
+
+type Me = { supabaseId: string };
+
+@Controller('health')
+@UseGuards(AuthGuard)
+export class HealthController {
+ constructor(private health: HealthService) {}
+
+ /** Workouts, daily steps and sleep, and weigh-ins from the phone's health app. */
+ @Post('import')
+ import(
+ @CurrentUser() user: Me,
+ @Body() body: HealthImportDto,
+ @UtcOffset() offset: number,
+ ) {
+ return this.health.import(user.supabaseId, body, offset);
+ }
+
+ @Get('recent')
+ recent(@CurrentUser() user: Me, @UtcOffset() offset: number) {
+ return this.health.recent(user.supabaseId, offset);
+ }
+}
diff --git a/packages/backend/src/health/health.db-spec.ts b/packages/backend/src/health/health.db-spec.ts
new file mode 100644
index 0000000..3a9e81c
--- /dev/null
+++ b/packages/backend/src/health/health.db-spec.ts
@@ -0,0 +1,171 @@
+import { TestDb } from '../test-utils/db';
+import { addDays, dateMarker, localToday } from '../common/day';
+import { WeightService } from '../progress/weight.service';
+import { ChallengesService } from '../challenges/challenges.service';
+import { HealthService } from './health.service';
+
+describe('HealthService (database)', () => {
+ const db = new TestDb();
+ const health = new HealthService(db.prisma, new WeightService(db.prisma));
+ const challenges = new ChallengesService(db.prisma, db.notifications);
+ const today = localToday(0);
+ afterAll(() => db.cleanup());
+
+ const run = (
+ externalId: string,
+ minutes: number,
+ at = new Date(Date.now() - 3_600_000),
+ ) => ({
+ externalId,
+ activityType: 'running',
+ startedAt: at.toISOString(),
+ durationMin: minutes,
+ });
+
+ it('imports workouts once, updating them when sent again', async () => {
+ const u = await db.user();
+ const first = await health.import(
+ u.supabaseId,
+ {
+ source: 'healthkit',
+ workouts: [run('hk-1', 30), run('hk-2', 20)],
+ days: [],
+ weights: [],
+ },
+ 0,
+ );
+ expect(first.workouts).toEqual({ created: 2, updated: 0 });
+ const again = await health.import(
+ u.supabaseId,
+ {
+ source: 'healthkit',
+ workouts: [run('hk-1', 35)],
+ days: [],
+ weights: [],
+ },
+ 0,
+ );
+ expect(again.workouts).toEqual({ created: 0, updated: 1 });
+
+ const logs = await db.prisma.activityLog.findMany({
+ where: { userId: u.id },
+ orderBy: { durationMin: 'asc' },
+ });
+ expect(logs.map((l) => [l.externalId, l.durationMin, l.source])).toEqual([
+ ['hk-2', 20, 'healthkit'],
+ ['hk-1', 35, 'healthkit'],
+ ]);
+ // Calories estimated when the health app didn't give them
+ expect(logs[0].caloriesBurned).toBeGreaterThan(0);
+ });
+
+ it('stores daily steps and sleep, and weigh-ins with the latest on the profile', async () => {
+ const u = await db.user();
+ const yesterday = addDays(today, -1);
+ await health.import(
+ u.supabaseId,
+ {
+ source: 'health_connect',
+ workouts: [],
+ days: [
+ { date: yesterday, steps: 8000, sleepMinutes: 410 },
+ { date: today, steps: 2500 },
+ ],
+ weights: [
+ { date: today, weightKg: 79.4 },
+ { date: yesterday, weightKg: 80 },
+ ],
+ },
+ 0,
+ );
+ // A later sync only updates what it sends
+ await health.import(
+ u.supabaseId,
+ {
+ source: 'health_connect',
+ workouts: [],
+ days: [{ date: today, steps: 6100 }],
+ weights: [],
+ },
+ 0,
+ );
+
+ const recent = await health.recent(u.supabaseId, 0);
+ expect(recent.days).toEqual([
+ {
+ date: yesterday,
+ steps: 8000,
+ sleepMinutes: 410,
+ source: 'health_connect',
+ },
+ {
+ date: today,
+ steps: 6100,
+ sleepMinutes: null,
+ source: 'health_connect',
+ },
+ ]);
+ expect(
+ (await db.prisma.user.findUnique({ where: { id: u.id } }))?.weightKg,
+ ).toBe(79.4);
+ });
+
+ it('ignores data older than two months', async () => {
+ const u = await db.user();
+ const old = new Date(Date.now() - 90 * 86_400_000);
+ const res = await health.import(
+ u.supabaseId,
+ {
+ source: 'healthkit',
+ workouts: [run('old-1', 30, old)],
+ days: [{ date: addDays(today, -90), steps: 9000 }],
+ weights: [],
+ },
+ 0,
+ );
+ expect(res).toEqual({
+ workouts: { created: 0, updated: 0 },
+ days: 0,
+ weights: 0,
+ });
+ });
+
+ it('step challenges count the phone total without double-counting logged walks', async () => {
+ const u = await db.user();
+ const c = await challenges.createChallenge(
+ u.supabaseId,
+ { title: 'Steps', type: 'steps', goalValue: 20000, durationDays: 7 },
+ 0,
+ );
+ // Today: a logged walk with 3,000 steps, and the phone counted 7,000 in total
+ await db.prisma.activityLog.create({
+ data: {
+ userId: u.id,
+ activityType: 'walking',
+ durationMin: 30,
+ steps: 3000,
+ loggedAt: new Date(),
+ },
+ });
+ await db.prisma.healthDay.create({
+ data: {
+ userId: u.id,
+ day: dateMarker(today),
+ steps: 7000,
+ source: 'healthkit',
+ },
+ });
+ // Before the challenge started: not counted
+ await db.prisma.healthDay.create({
+ data: {
+ userId: u.id,
+ day: dateMarker(addDays(today, -3)),
+ steps: 12000,
+ source: 'healthkit',
+ },
+ });
+
+ const view = await challenges.getChallenge(u.supabaseId, c.id);
+ expect(view.totalProgress).toBe(7000);
+ });
+});
diff --git a/packages/backend/src/health/health.dto.ts b/packages/backend/src/health/health.dto.ts
new file mode 100644
index 0000000..5ddf360
--- /dev/null
+++ b/packages/backend/src/health/health.dto.ts
@@ -0,0 +1,101 @@
+import { Type } from 'class-transformer';
+import {
+ ArrayMaxSize,
+ IsArray,
+ IsIn,
+ IsInt,
+ IsISO8601,
+ IsNumber,
+ IsOptional,
+ IsString,
+ Length,
+ Matches,
+ Max,
+ Min,
+ ValidateNested,
+} from 'class-validator';
+import { ACTIVITY_TYPES } from '../activity/activity.constants';
+import { IsNotFuture } from '../common/validators';
+
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+export class HealthWorkoutDto {
+ // The health app's own ID for the workout
+ @IsString()
+ @Length(1, 120)
+ externalId: string;
+
+ @IsIn(ACTIVITY_TYPES)
+ activityType: string;
+
+ @IsISO8601({ strict: true })
+ @IsNotFuture()
+ startedAt: string;
+
+ @IsInt()
+ @Min(1)
+ @Max(1440)
+ durationMin: number;
+
+ @IsOptional()
+ @IsNumber()
+ @Min(0)
+ @Max(20000)
+ caloriesBurned?: number;
+
+ @IsOptional()
+ @IsInt()
+ @Min(0)
+ @Max(300000)
+ steps?: number;
+}
+
+export class HealthDayDto {
+ @Matches(DATE)
+ date: string;
+
+ @IsOptional()
+ @IsInt()
+ @Min(0)
+ @Max(200000)
+ steps?: number;
+
+ @IsOptional()
+ @IsInt()
+ @Min(0)
+ @Max(1440)
+ sleepMinutes?: number;
+}
+
+export class HealthWeightDto {
+ @Matches(DATE)
+ date: string;
+
+ @IsNumber()
+ @Min(20)
+ @Max(400)
+ weightKg: number;
+}
+
+export class HealthImportDto {
+ @IsIn(['healthkit', 'health_connect'])
+ source: 'healthkit' | 'health_connect';
+
+ @IsArray()
+ @ArrayMaxSize(300)
+ @ValidateNested({ each: true })
+ @Type(() => HealthWorkoutDto)
+ workouts: HealthWorkoutDto[] = [];
+
+ @IsArray()
+ @ArrayMaxSize(62)
+ @ValidateNested({ each: true })
+ @Type(() => HealthDayDto)
+ days: HealthDayDto[] = [];
+
+ @IsArray()
+ @ArrayMaxSize(62)
+ @ValidateNested({ each: true })
+ @Type(() => HealthWeightDto)
+ weights: HealthWeightDto[] = [];
+}
diff --git a/packages/backend/src/health/health.module.ts b/packages/backend/src/health/health.module.ts
new file mode 100644
index 0000000..b753cf5
--- /dev/null
+++ b/packages/backend/src/health/health.module.ts
@@ -0,0 +1,11 @@
+import { Module } from '@nestjs/common';
+import { ProgressModule } from '../progress/progress.module';
+import { HealthController } from './health.controller';
+import { HealthService } from './health.service';
+
+@Module({
+ imports: [ProgressModule],
+ controllers: [HealthController],
+ providers: [HealthService],
+})
+export class HealthModule {}
diff --git a/packages/backend/src/health/health.service.ts b/packages/backend/src/health/health.service.ts
new file mode 100644
index 0000000..f6e6bc8
--- /dev/null
+++ b/packages/backend/src/health/health.service.ts
@@ -0,0 +1,137 @@
+import { Injectable, NotFoundException } from '@nestjs/common';
+import { PrismaService } from '../prisma/prisma.service';
+import { WeightService } from '../progress/weight.service';
+import { addDays, dateMarker, localToday } from '../common/day';
+import { MET } from '../activity/activity.constants';
+import type { HealthImportDto } from './health.dto';
+
+// Older data isn't imported: the app sends at most a month at a time
+const MAX_AGE_DAYS = 62;
+
+/**
+ * Takes what the phone read from Apple Health or Health Connect and stores
+ * it. Safe to send the same data again: workouts are matched on the health
+ * app's ID, days and weigh-ins on their date.
+ */
+@Injectable()
+export class HealthService {
+ constructor(
+ private prisma: PrismaService,
+ private weight: WeightService,
+ ) {}
+
+ async import(supabaseId: string, dto: HealthImportDto, offset: number) {
+ const user = await this.prisma.user.findUnique({ where: { supabaseId } });
+ if (!user) throw new NotFoundException('User not found');
+ const oldest = addDays(localToday(offset), -MAX_AGE_DAYS);
+ const source = dto.source;
+
+ let created = 0;
+ let updated = 0;
+ for (const w of dto.workouts) {
+ const loggedAt = new Date(w.startedAt);
+ if (loggedAt < new Date(`${oldest}T00:00:00Z`)) continue;
+ const caloriesBurned =
+ w.caloriesBurned ??
+ Math.round(
+ (MET[w.activityType] ?? 5) *
+ (user.weightKg ?? 70) *
+ (w.durationMin / 60),
+ );
+ const data = {
+ activityType: w.activityType,
+ durationMin: w.durationMin,
+ caloriesBurned,
+ steps: w.steps ?? null,
+ loggedAt,
+ source,
+ };
+ const existing = await this.prisma.activityLog.findUnique({
+ where: {
+ userId_externalId: { userId: user.id, externalId: w.externalId },
+ },
+ select: { id: true },
+ });
+ if (existing) {
+ await this.prisma.activityLog.update({
+ where: { id: existing.id },
+ data,
+ });
+ updated++;
+ } else {
+ await this.prisma.activityLog.create({
+ data: { ...data, userId: user.id, externalId: w.externalId },
+ });
+ created++;
+ }
+ }
+
+ let days = 0;
+ for (const d of dto.days) {
+ if (
+ d.date < oldest ||
+ (d.steps === undefined && d.sleepMinutes === undefined)
+ )
+ continue;
+ const values = {
+ ...(d.steps !== undefined ? { steps: d.steps } : {}),
+ ...(d.sleepMinutes !== undefined
+ ? { sleepMinutes: d.sleepMinutes }
+ : {}),
+ source,
+ };
+ await this.prisma.healthDay.upsert({
+ where: { userId_day: { userId: user.id, day: dateMarker(d.date) } },
+ update: values,
+ create: { ...values, userId: user.id, day: dateMarker(d.date) },
+ });
+ days++;
+ }
+
+ let weights = 0;
+ // Oldest first, so the profile ends up on the latest
+ for (const w of [...dto.weights].sort((a, b) =>
+ a.date.localeCompare(b.date),
+ )) {
+ if (w.date < oldest) continue;
+ try {
+ await this.weight.logForUser(user.id, w.weightKg, offset, w.date);
+ weights++;
+ } catch {
+ // A date the weight log refuses (e.g. tomorrow in this zone): skip it
+ }
+ }
+
+ return { workouts: { created, updated }, days, weights };
+ }
+
+ /** The last week of synced days, for the app and the coach. */
+ async recent(supabaseId: string, offset: number) {
+ const user = await this.prisma.user.findUnique({ where: { supabaseId } });
+ if (!user) throw new NotFoundException('User not found');
+ const today = localToday(offset);
+ const rows = await this.prisma.healthDay.findMany({
+ where: { userId: user.id, day: { gte: dateMarker(addDays(today, -6)) } },
+ orderBy: { day: 'asc' },
+ });
+ const imported = await this.prisma.activityLog.count({
+ where: {
+ userId: user.id,
+ source: { in: ['healthkit', 'health_connect'] },
+ },
+ });
+ return {
+ days: rows.map((r) => ({
+ date: r.day.toISOString().slice(0, 10),
+ steps: r.steps,
+ sleepMinutes: r.sleepMinutes,
+ source: r.source,
+ })),
+ importedWorkouts: imported,
+ lastSyncedAt: rows.reduce(
+ (latest, r) => (!latest || r.updatedAt > latest ? r.updatedAt : latest),
+ null,
+ ),
+ };
+ }
+}
diff --git a/packages/backend/src/main.ts b/packages/backend/src/main.ts
index 33e7cc3..7517cb3 100644
--- a/packages/backend/src/main.ts
+++ b/packages/backend/src/main.ts
@@ -14,6 +14,10 @@ async function bootstrap() {
// rate limits apply per caller rather than to the proxy
app.set('trust proxy', 1);
+ // Meal photos are sent as base64 JSON, so allow a few MB (Express's
+ // default is 100 kB)
+ app.useBodyParser('json', { limit: '5mb' });
+
// CORS only matters for the web build. CORS_ORIGINS (comma-separated)
// narrows it; unset, any origin is allowed as before.
const origins = process.env.CORS_ORIGINS?.split(',')
diff --git a/packages/backend/src/meal-parse/meal-parse.controller.ts b/packages/backend/src/meal-parse/meal-parse.controller.ts
new file mode 100644
index 0000000..47d5434
--- /dev/null
+++ b/packages/backend/src/meal-parse/meal-parse.controller.ts
@@ -0,0 +1,50 @@
+import {
+ Body,
+ Controller,
+ Delete,
+ Get,
+ Param,
+ Post,
+ UseGuards,
+} from '@nestjs/common';
+import { Throttle } from '@nestjs/throttler';
+import { AuthGuard } from '../auth/auth.guard';
+import { CurrentUser } from '../common/current-user.decorator';
+import { UtcOffset } from '../common/utc-offset.decorator';
+import { MealParseService } from './meal-parse.service';
+import { LogParsedMealDto, ParseMealDto } from './meal-parse.dto';
+
+@Controller('food')
+@UseGuards(AuthGuard)
+export class MealParseController {
+ constructor(private meals: MealParseService) {}
+
+ // The daily cap is the real limit; this stops a stuck retry loop
+ @Throttle({ default: { limit: 10, ttl: 60_000 } })
+ @Post('parse')
+ parse(
+ @CurrentUser() user: { supabaseId: string },
+ @Body() body: ParseMealDto,
+ @UtcOffset() offset: number,
+ ) {
+ return this.meals.parse(user.supabaseId, body, offset);
+ }
+
+ @Post('parse/log')
+ log(
+ @CurrentUser() user: { supabaseId: string },
+ @Body() body: LogParsedMealDto,
+ ) {
+ return this.meals.log(user.supabaseId, body);
+ }
+
+ @Get('memories')
+ memories(@CurrentUser() user: { supabaseId: string }) {
+ return this.meals.listMemories(user.supabaseId);
+ }
+
+ @Delete('memories/:id')
+ forget(@CurrentUser() user: { supabaseId: string }, @Param('id') id: string) {
+ return this.meals.forget(user.supabaseId, id);
+ }
+}
diff --git a/packages/backend/src/meal-parse/meal-parse.db-spec.ts b/packages/backend/src/meal-parse/meal-parse.db-spec.ts
new file mode 100644
index 0000000..bce3828
--- /dev/null
+++ b/packages/backend/src/meal-parse/meal-parse.db-spec.ts
@@ -0,0 +1,241 @@
+import type OpenAI from 'openai';
+import { TestDb } from '../test-utils/db';
+import { localToday } from '../common/day';
+import type { FoodService } from '../food/food.service';
+import { DAILY_PARSES, MealParseService } from './meal-parse.service';
+import { memoryKey } from './meal-parse';
+
+/** A model that always reads the same meal. */
+function fakeModel(reply: unknown) {
+ const calls: unknown[] = [];
+ const client = {
+ responses: {
+ create: (req: unknown) => {
+ calls.push(req);
+ if (reply instanceof Error) return Promise.reject(reply);
+ return Promise.resolve({ output_text: JSON.stringify(reply) });
+ },
+ },
+ } as unknown as OpenAI;
+ return { client, calls };
+}
+
+const item = (over: Record = {}) => ({
+ name: 'Porridge oats',
+ brand: null,
+ portion: '1 bowl',
+ grams: 60,
+ quantityStated: false,
+ kcalPer100g: 380,
+ proteinPer100g: 13,
+ carbsPer100g: 60,
+ fatPer100g: 7,
+ confidence: 'medium',
+ ...over,
+});
+
+describe('MealParseService (database)', () => {
+ const db = new TestDb();
+ const food = {
+ searchFoods: (q: string) =>
+ Promise.resolve(
+ q.toLowerCase().includes('fage')
+ ? [
+ { calories: 0 },
+ { calories: 97, proteinG: 9, carbsG: 3.9, fatG: 5 },
+ ]
+ : [],
+ ),
+ } as unknown as FoodService;
+ afterAll(() => db.cleanup());
+
+ it('grounds items in memory, then the database, then the estimate', async () => {
+ const u = await db.user();
+ await db.prisma.foodMemory.create({
+ data: {
+ userId: u.id,
+ key: memoryKey('Porridge oats'),
+ name: 'Porridge oats',
+ kcalPer100g: 370,
+ proteinPer100g: 12,
+ carbsPer100g: 62,
+ fatPer100g: 8,
+ usualGrams: 80,
+ },
+ });
+ const { client, calls } = fakeModel({
+ items: [
+ item(),
+ item({
+ name: 'Greek yogurt',
+ brand: 'Fage',
+ grams: 150,
+ quantityStated: true,
+ }),
+ // Calories that don't match the macros get corrected
+ item({
+ name: 'Honey',
+ grams: 20,
+ kcalPer100g: 50,
+ proteinPer100g: 0,
+ carbsPer100g: 80,
+ fatPer100g: 0,
+ }),
+ ],
+ question: 'Was the porridge made with milk or water?',
+ });
+ const meals = new MealParseService(db.prisma, food, client, 'test');
+ const out = await meals.parse(
+ u.supabaseId,
+ { text: 'oats, fage yogurt and honey', imageBase64: 'aGVsbG8=' },
+ 0,
+ );
+
+ expect(out.items.map((i) => [i.name, i.source, i.grams])).toEqual([
+ ['Porridge oats', 'memory', 80],
+ ['Greek yogurt', 'database', 150],
+ ['Honey', 'estimate', 20],
+ ]);
+ expect(out.items[0].calories).toBe(296); // 370 × 0.8
+ expect(out.items[1].calories).toBe(146);
+ expect(out.items[2].per100.kcal).toBe(320);
+ expect(out.total.calories).toBe(296 + 146 + 64);
+ expect(out.question).toMatch(/milk or water/);
+
+ // The model is told the names of foods they've logged before
+ expect((calls[0] as { instructions: string }).instructions).toContain(
+ '"Porridge oats"',
+ );
+ // The photo went to the model as an image
+ const req = calls[0] as {
+ input: { content: { type: string; image_url?: string }[] }[];
+ };
+ expect(req.input[0].content[1]).toMatchObject({
+ type: 'input_image',
+ image_url: 'data:image/jpeg;base64,aGVsbG8=',
+ });
+ });
+
+ it('logs confirmed items in grams and learns them', async () => {
+ const u = await db.user();
+ const meals = new MealParseService(
+ db.prisma,
+ food,
+ fakeModel({ items: [], question: null }).client,
+ 'test',
+ );
+ const confirmed = {
+ name: 'Chicken Breast',
+ grams: 180,
+ kcalPer100g: 165,
+ proteinPer100g: 31,
+ carbsPer100g: 0,
+ fatPer100g: 3.6,
+ };
+ const res = await meals.log(u.supabaseId, {
+ mealType: 'dinner',
+ items: [
+ confirmed,
+ {
+ ...confirmed,
+ name: 'Ketchup',
+ grams: 15,
+ kcalPer100g: 100,
+ proteinPer100g: 1,
+ carbsPer100g: 25,
+ fatPer100g: 0,
+ remember: false,
+ },
+ ],
+ });
+ expect(res.logged).toBe(2);
+ const logs = await db.prisma.foodLog.findMany({
+ where: { userId: u.id },
+ orderBy: { calories: 'desc' },
+ });
+ expect(
+ logs.map((l) => [
+ l.name,
+ l.calories,
+ l.proteinG,
+ l.servingQty,
+ l.servingUnit,
+ ]),
+ ).toEqual([
+ ['Chicken Breast', 297, 55.8, 180, 'g'],
+ ['Ketchup', 15, 0.2, 15, 'g'],
+ ]);
+
+ // Logged again with a new portion: one memory, updated
+ await meals.log(u.supabaseId, {
+ mealType: 'lunch',
+ items: [{ ...confirmed, name: 'chicken breast!', grams: 200 }],
+ });
+ const memories = await meals.listMemories(u.supabaseId);
+ expect(memories.map((m) => [m.key, m.usualGrams, m.uses])).toEqual([
+ ['chicken breast', 200, 2],
+ ]);
+
+ await meals.forget(u.supabaseId, memories[0].id);
+ expect(await meals.listMemories(u.supabaseId)).toEqual([]);
+ const other = await db.user();
+ await expect(
+ meals.forget(other.supabaseId, memories[0].id),
+ ).rejects.toThrow('Food not found');
+ });
+
+ it('caps readings per day, and a failed reading does not count', async () => {
+ const u = await db.user();
+ const failing = new MealParseService(
+ db.prisma,
+ food,
+ fakeModel(new Error('down')).client,
+ 'test',
+ );
+ await expect(
+ failing.parse(u.supabaseId, { text: 'toast' }, 0),
+ ).rejects.toThrow("Couldn't read that meal");
+ let row = await db.prisma.user.findUniqueOrThrow({ where: { id: u.id } });
+ expect([row.aiParseDay, row.aiParseCount]).toEqual([localToday(0), 0]);
+
+ const meals = new MealParseService(
+ db.prisma,
+ food,
+ fakeModel({ items: [item()], question: null }).client,
+ 'test',
+ );
+ await db.prisma.user.update({
+ where: { id: u.id },
+ data: { aiParseCount: DAILY_PARSES - 2 },
+ });
+ // Three at once with two left: exactly one is refused
+ const results = await Promise.allSettled(
+ [1, 2, 3].map(() => meals.parse(u.supabaseId, { text: 'oats' }, 0)),
+ );
+ expect(results.filter((r) => r.status === 'rejected')).toHaveLength(1);
+ row = await db.prisma.user.findUniqueOrThrow({ where: { id: u.id } });
+ expect(row.aiParseCount).toBe(DAILY_PARSES);
+
+ // A new day starts again
+ await db.prisma.user.update({
+ where: { id: u.id },
+ data: { aiParseDay: '2000-01-01' },
+ });
+ await expect(
+ meals.parse(u.supabaseId, { text: 'oats' }, 0),
+ ).resolves.toHaveProperty('items');
+ });
+
+ it('needs text or a photo', async () => {
+ const u = await db.user();
+ const meals = new MealParseService(
+ db.prisma,
+ food,
+ fakeModel({ items: [], question: null }).client,
+ 'test',
+ );
+ await expect(meals.parse(u.supabaseId, { text: ' ' }, 0)).rejects.toThrow(
+ 'Describe the meal',
+ );
+ });
+});
diff --git a/packages/backend/src/meal-parse/meal-parse.dto.ts b/packages/backend/src/meal-parse/meal-parse.dto.ts
new file mode 100644
index 0000000..c7e096b
--- /dev/null
+++ b/packages/backend/src/meal-parse/meal-parse.dto.ts
@@ -0,0 +1,96 @@
+import { Type } from 'class-transformer';
+import {
+ ArrayMaxSize,
+ ArrayMinSize,
+ IsArray,
+ IsBoolean,
+ IsIn,
+ IsISO8601,
+ IsNumber,
+ IsOptional,
+ IsString,
+ Length,
+ Matches,
+ Max,
+ Min,
+ ValidateNested,
+} from 'class-validator';
+import { MEAL_TYPES } from '../food/food.dto';
+import { IsNotFuture } from '../common/validators';
+
+export class ParseMealDto {
+ @IsOptional()
+ @IsString()
+ @Length(0, 1000)
+ text?: string;
+
+ // A JPEG, PNG or WebP photo as base64 (no data: prefix). The app resizes
+ // to about 1024 px first, so real photos are a few hundred kB.
+ @IsOptional()
+ @IsString()
+ @Length(1, 4_000_000)
+ @Matches(/^[A-Za-z0-9+/=\s]+$/, { message: 'imageBase64 must be base64' })
+ imageBase64?: string;
+
+ @IsOptional()
+ @IsIn(['image/jpeg', 'image/png', 'image/webp'])
+ imageType?: string;
+}
+
+export class ConfirmedItemDto {
+ @IsString()
+ @Length(1, 200)
+ name: string;
+
+ @IsOptional()
+ @IsString()
+ @Length(0, 200)
+ brand?: string;
+
+ @IsNumber()
+ @Min(1)
+ @Max(5000)
+ grams: number;
+
+ @IsNumber()
+ @Min(0)
+ @Max(900)
+ kcalPer100g: number;
+
+ @IsNumber()
+ @Min(0)
+ @Max(100)
+ proteinPer100g: number;
+
+ @IsNumber()
+ @Min(0)
+ @Max(100)
+ carbsPer100g: number;
+
+ @IsNumber()
+ @Min(0)
+ @Max(100)
+ fatPer100g: number;
+
+ // Off for a one-off, so it doesn't become "your usual"
+ @IsOptional()
+ @IsBoolean()
+ remember?: boolean;
+}
+
+export class LogParsedMealDto {
+ @IsIn(MEAL_TYPES)
+ mealType: string;
+
+ @IsOptional()
+ @IsISO8601({ strict: true })
+ @IsNotFuture()
+ loggedAt?: string;
+
+ @IsArray()
+ @ArrayMinSize(1)
+ @ArrayMaxSize(20)
+ @ValidateNested({ each: true })
+ @Type(() => ConfirmedItemDto)
+ items: ConfirmedItemDto[];
+}
diff --git a/packages/backend/src/meal-parse/meal-parse.module.ts b/packages/backend/src/meal-parse/meal-parse.module.ts
new file mode 100644
index 0000000..50dc267
--- /dev/null
+++ b/packages/backend/src/meal-parse/meal-parse.module.ts
@@ -0,0 +1,12 @@
+import { Module } from '@nestjs/common';
+import { azureOpenAIProviders } from '../ai/azure-openai';
+import { FoodModule } from '../food/food.module';
+import { MealParseController } from './meal-parse.controller';
+import { MealParseService } from './meal-parse.service';
+
+@Module({
+ imports: [FoodModule],
+ controllers: [MealParseController],
+ providers: [...azureOpenAIProviders, MealParseService],
+})
+export class MealParseModule {}
diff --git a/packages/backend/src/meal-parse/meal-parse.service.ts b/packages/backend/src/meal-parse/meal-parse.service.ts
new file mode 100644
index 0000000..8646b07
--- /dev/null
+++ b/packages/backend/src/meal-parse/meal-parse.service.ts
@@ -0,0 +1,297 @@
+import {
+ BadGatewayException,
+ BadRequestException,
+ HttpException,
+ HttpStatus,
+ Inject,
+ Injectable,
+ Logger,
+ NotFoundException,
+} from '@nestjs/common';
+import OpenAI from 'openai';
+import { PrismaService } from '../prisma/prisma.service';
+import { AI_MODEL } from '../ai/azure-openai';
+import { localToday } from '../common/day';
+import { FoodService } from '../food/food.service';
+import {
+ groundItem,
+ mealInstructions,
+ MEAL_SCHEMA,
+ memoryKey,
+ totals,
+ type Memory,
+ type ModelItem,
+ type Per100,
+} from './meal-parse';
+import type { LogParsedMealDto, ParseMealDto } from './meal-parse.dto';
+
+// Each reading is a model call (with a photo, a large one), so cap it per day
+export const DAILY_PARSES = 30;
+const MAX_ITEMS = 12;
+
+@Injectable()
+export class MealParseService {
+ private readonly logger = new Logger(MealParseService.name);
+
+ constructor(
+ private prisma: PrismaService,
+ private food: FoodService,
+ private openai: OpenAI,
+ @Inject(AI_MODEL) private model: string,
+ ) {}
+
+ private async resolveUserId(supabaseId: string) {
+ const user = await this.prisma.user.findUnique({
+ where: { supabaseId },
+ select: { id: true },
+ });
+ if (!user) throw new NotFoundException('User not found');
+ return user.id;
+ }
+
+ /**
+ * Takes one of today's readings, or refuses. Two conditional updates, so
+ * parallel requests can't both take the last one.
+ */
+ private async takeParse(userId: string, today: string) {
+ const fresh = await this.prisma.user.updateMany({
+ where: {
+ id: userId,
+ OR: [{ aiParseDay: null }, { aiParseDay: { not: today } }],
+ },
+ data: { aiParseDay: today, aiParseCount: 1 },
+ });
+ if (fresh.count) return;
+ const more = await this.prisma.user.updateMany({
+ where: {
+ id: userId,
+ aiParseDay: today,
+ aiParseCount: { lt: DAILY_PARSES },
+ },
+ data: { aiParseCount: { increment: 1 } },
+ });
+ if (!more.count) {
+ throw new HttpException(
+ `You can use smart logging ${DAILY_PARSES} times a day. Search or add foods by hand for the rest of today.`,
+ HttpStatus.TOO_MANY_REQUESTS,
+ );
+ }
+ }
+
+ /** A reading that failed on our side doesn't count. */
+ private async giveBack(userId: string, today: string) {
+ await this.prisma.user
+ .updateMany({
+ where: { id: userId, aiParseDay: today, aiParseCount: { gt: 0 } },
+ data: { aiParseCount: { decrement: 1 } },
+ })
+ .catch(() => undefined);
+ }
+
+ /** The first database product with calories for a branded item. */
+ private async lookupBranded(item: ModelItem): Promise {
+ if (!item.brand) return undefined;
+ try {
+ const hits = await this.food.searchFoods(`${item.brand} ${item.name}`);
+ const hit = hits.find((h) => h.calories > 0);
+ return hit
+ ? {
+ kcal: hit.calories,
+ protein: hit.proteinG,
+ carbs: hit.carbsG,
+ fat: hit.fatG,
+ }
+ : undefined;
+ } catch {
+ // The database being down just means we fall back to the estimate
+ return undefined;
+ }
+ }
+
+ async parse(supabaseId: string, dto: ParseMealDto, offset: number) {
+ const text = dto.text?.trim() ?? '';
+ const image = dto.imageBase64?.replace(/\s+/g, '');
+ if (!text && !image) {
+ throw new BadRequestException('Describe the meal or add a photo');
+ }
+
+ const userId = await this.resolveUserId(supabaseId);
+ const today = localToday(offset);
+ await this.takeParse(userId, today);
+ const known = await this.prisma.foodMemory.findMany({
+ where: { userId },
+ orderBy: [{ uses: 'desc' }, { updatedAt: 'desc' }],
+ take: 60,
+ select: { name: true },
+ });
+
+ const content: OpenAI.Responses.ResponseInputContent[] = [
+ {
+ type: 'input_text',
+ text: text || 'What did I eat? (Photo attached.)',
+ },
+ ];
+ if (image) {
+ content.push({
+ type: 'input_image',
+ image_url: `data:${dto.imageType ?? 'image/jpeg'};base64,${image}`,
+ detail: 'auto',
+ });
+ }
+
+ let parsed: { items: ModelItem[]; question: string | null };
+ try {
+ const response = await this.openai.responses.create({
+ model: this.model,
+ instructions: mealInstructions(known.map((m) => m.name)),
+ input: [{ role: 'user', content }],
+ max_output_tokens: 6000,
+ reasoning: { effort: 'low' },
+ store: false,
+ text: {
+ format: {
+ type: 'json_schema',
+ name: 'meal',
+ strict: true,
+ schema: MEAL_SCHEMA as unknown as Record,
+ },
+ },
+ });
+ parsed = JSON.parse(response.output_text) as typeof parsed;
+ if (!Array.isArray(parsed.items)) throw new Error('No items');
+ } catch (err) {
+ this.logger.warn(`Meal parse failed: ${(err as Error).message}`);
+ await this.giveBack(userId, today);
+ throw new BadGatewayException(
+ "Couldn't read that meal right now. Try again, or add it by hand.",
+ );
+ }
+
+ const modelItems = parsed.items
+ .slice(0, MAX_ITEMS)
+ .filter((i) => i?.name?.trim());
+ const keys = modelItems.map((i) => memoryKey(i.name));
+ const memories = await this.prisma.foodMemory.findMany({
+ where: { userId, key: { in: [...new Set(keys)] } },
+ });
+ const byKey = new Map(
+ memories.map((m) => [
+ m.key,
+ {
+ kcal: m.kcalPer100g,
+ protein: m.proteinPer100g,
+ carbs: m.carbsPer100g,
+ fat: m.fatPer100g,
+ usualGrams: m.usualGrams,
+ },
+ ]),
+ );
+ const database = await Promise.all(
+ modelItems.map((i, n) =>
+ byKey.has(keys[n]) ? Promise.resolve(undefined) : this.lookupBranded(i),
+ ),
+ );
+
+ const items = modelItems.map((item, n) => {
+ const grounded = groundItem(
+ {
+ ...item,
+ name: item.name.trim().slice(0, 200),
+ brand: item.brand?.trim().slice(0, 200) || null,
+ },
+ byKey.get(keys[n]),
+ database[n],
+ );
+ return { ...grounded, ...totals(grounded.per100, grounded.grams) };
+ });
+ const total = items.reduce(
+ (t, i) => ({
+ calories: t.calories + i.calories,
+ proteinG: Math.round((t.proteinG + i.proteinG) * 10) / 10,
+ carbsG: Math.round((t.carbsG + i.carbsG) * 10) / 10,
+ fatG: Math.round((t.fatG + i.fatG) * 10) / 10,
+ }),
+ { calories: 0, proteinG: 0, carbsG: 0, fatG: 0 },
+ );
+ const question = parsed.question?.trim()
+ ? parsed.question.trim().slice(0, 200)
+ : null;
+ return { items, total, question };
+ }
+
+ /**
+ * Logs the items the user confirmed, and remembers each food's nutrition
+ * and portion so the next reading of it starts from their numbers.
+ */
+ async log(supabaseId: string, dto: LogParsedMealDto) {
+ const userId = await this.resolveUserId(supabaseId);
+ const loggedAt = dto.loggedAt ? new Date(dto.loggedAt) : new Date();
+
+ return this.prisma.$transaction(async (tx) => {
+ const logs = [];
+ for (const item of dto.items) {
+ const per100 = {
+ kcal: item.kcalPer100g,
+ protein: item.proteinPer100g,
+ carbs: item.carbsPer100g,
+ fat: item.fatPer100g,
+ };
+ const t = totals(per100, item.grams);
+ logs.push(
+ await tx.foodLog.create({
+ data: {
+ userId,
+ name: item.name,
+ brand: item.brand || null,
+ mealType: dto.mealType,
+ calories: t.calories,
+ proteinG: t.proteinG,
+ carbsG: t.carbsG,
+ fatG: t.fatG,
+ servingQty: Math.round(item.grams),
+ servingUnit: 'g',
+ loggedAt,
+ },
+ }),
+ );
+
+ const key = memoryKey(item.name);
+ if (item.remember === false || !key) continue;
+ const values = {
+ name: item.name,
+ kcalPer100g: per100.kcal,
+ proteinPer100g: per100.protein,
+ carbsPer100g: per100.carbs,
+ fatPer100g: per100.fat,
+ usualGrams: item.grams,
+ };
+ await tx.foodMemory.upsert({
+ where: { userId_key: { userId, key } },
+ create: { userId, key, ...values },
+ update: { ...values, uses: { increment: 1 } },
+ });
+ }
+ return { logged: logs.length, logs };
+ });
+ }
+
+ /** The foods GRIT has learned, most used first. */
+ listMemories(supabaseId: string) {
+ return this.resolveUserId(supabaseId).then((userId) =>
+ this.prisma.foodMemory.findMany({
+ where: { userId },
+ orderBy: [{ uses: 'desc' }, { updatedAt: 'desc' }],
+ take: 200,
+ }),
+ );
+ }
+
+ async forget(supabaseId: string, id: string) {
+ const userId = await this.resolveUserId(supabaseId);
+ const { count } = await this.prisma.foodMemory.deleteMany({
+ where: { id, userId },
+ });
+ if (!count) throw new NotFoundException('Food not found');
+ return { ok: true };
+ }
+}
diff --git a/packages/backend/src/meal-parse/meal-parse.spec.ts b/packages/backend/src/meal-parse/meal-parse.spec.ts
new file mode 100644
index 0000000..fe96e1f
--- /dev/null
+++ b/packages/backend/src/meal-parse/meal-parse.spec.ts
@@ -0,0 +1,82 @@
+import {
+ groundItem,
+ memoryKey,
+ saneEstimate,
+ totals,
+ type ModelItem,
+} from './meal-parse';
+
+const item = (over: Partial = {}): ModelItem => ({
+ name: 'Porridge oats',
+ brand: null,
+ portion: '1 bowl',
+ grams: 80,
+ quantityStated: false,
+ kcalPer100g: 370,
+ proteinPer100g: 13,
+ carbsPer100g: 60,
+ fatPer100g: 7,
+ confidence: 'medium',
+ ...over,
+});
+
+describe('meal parsing', () => {
+ it('matches foods regardless of case and punctuation', () => {
+ expect(memoryKey(' Porridge-Oats! ')).toBe('porridge oat');
+ expect(memoryKey('Fried eggs')).toBe(memoryKey('fried egg'));
+ expect(memoryKey('Hummus')).toBe('hummus');
+ expect(memoryKey('Glass of milk')).toBe('glass of milk');
+ });
+
+ it("uses the person's own food and usual portion first", () => {
+ const mem = { kcal: 380, protein: 12, carbs: 62, fat: 8, usualGrams: 60 };
+ expect(groundItem(item(), mem, undefined)).toMatchObject({
+ source: 'memory',
+ grams: 60,
+ portion: 'your usual 60 g',
+ per100: mem,
+ });
+ // An amount they stated wins over the usual
+ expect(
+ groundItem(
+ item({ quantityStated: true, grams: 100, portion: '100 g' }),
+ mem,
+ undefined,
+ ),
+ ).toMatchObject({ grams: 100, portion: '100 g' });
+ });
+
+ it('then the database, then a checked estimate', () => {
+ const db = { kcal: 389, protein: 17, carbs: 66, fat: 7 };
+ expect(groundItem(item({ brand: 'Quaker' }), undefined, db).source).toBe(
+ 'database',
+ );
+ const est = groundItem(item(), undefined, undefined);
+ expect(est.source).toBe('estimate');
+ expect(est.per100.kcal).toBe(370);
+ });
+
+ it('keeps estimates possible', () => {
+ // Calories far from the macros: the macros win (4·10 + 4·20 + 9·10 = 210)
+ expect(
+ saneEstimate({ kcal: 50, protein: 10, carbs: 20, fat: 10 }).kcal,
+ ).toBe(210);
+ // Macros over 100 g are scaled down
+ const s = saneEstimate({ kcal: 500, protein: 80, carbs: 80, fat: 40 });
+ expect(s.protein + s.carbs + s.fat).toBeCloseTo(100, 0);
+ // Nonsense grams are clamped
+ expect(groundItem(item({ grams: -5 }), undefined, undefined).grams).toBe(1);
+ expect(groundItem(item({ grams: 99999 }), undefined, undefined).grams).toBe(
+ 2000,
+ );
+ });
+
+ it('works out totals for the portion', () => {
+ expect(totals({ kcal: 370, protein: 13, carbs: 60, fat: 7 }, 60)).toEqual({
+ calories: 222,
+ proteinG: 7.8,
+ carbsG: 36,
+ fatG: 4.2,
+ });
+ });
+});
diff --git a/packages/backend/src/meal-parse/meal-parse.ts b/packages/backend/src/meal-parse/meal-parse.ts
new file mode 100644
index 0000000..d3f055e
--- /dev/null
+++ b/packages/backend/src/meal-parse/meal-parse.ts
@@ -0,0 +1,215 @@
+/**
+ * Turning an AI reading of a meal into loggable items. The model splits the
+ * meal and estimates portions; nutrition comes from the user's own memory of
+ * a food first, then the food database for branded items, and only then the
+ * model's estimate, which is checked against its own macros.
+ */
+
+export interface ModelItem {
+ name: string;
+ brand: string | null;
+ portion: string;
+ grams: number;
+ /** Whether the user said how much (e.g. "200 g", "2 eggs") */
+ quantityStated: boolean;
+ kcalPer100g: number;
+ proteinPer100g: number;
+ carbsPer100g: number;
+ fatPer100g: number;
+ confidence: 'high' | 'medium' | 'low';
+}
+
+export interface Per100 {
+ kcal: number;
+ protein: number;
+ carbs: number;
+ fat: number;
+}
+
+export interface Memory extends Per100 {
+ usualGrams: number;
+}
+
+export type ItemSource = 'memory' | 'database' | 'estimate';
+
+export interface ParsedItem {
+ name: string;
+ brand: string | null;
+ portion: string;
+ grams: number;
+ per100: Per100;
+ source: ItemSource;
+ confidence: 'high' | 'medium' | 'low';
+}
+
+export const MEAL_SCHEMA = {
+ type: 'object',
+ additionalProperties: false,
+ required: ['items', 'question'],
+ properties: {
+ items: {
+ type: 'array',
+ items: {
+ type: 'object',
+ additionalProperties: false,
+ required: [
+ 'name',
+ 'brand',
+ 'portion',
+ 'grams',
+ 'quantityStated',
+ 'kcalPer100g',
+ 'proteinPer100g',
+ 'carbsPer100g',
+ 'fatPer100g',
+ 'confidence',
+ ],
+ properties: {
+ name: { type: 'string' },
+ brand: { type: ['string', 'null'] },
+ portion: { type: 'string' },
+ grams: { type: 'number' },
+ quantityStated: { type: 'boolean' },
+ kcalPer100g: { type: 'number' },
+ proteinPer100g: { type: 'number' },
+ carbsPer100g: { type: 'number' },
+ fatPer100g: { type: 'number' },
+ confidence: { type: 'string', enum: ['high', 'medium', 'low'] },
+ },
+ },
+ },
+ question: { type: ['string', 'null'] },
+ },
+} as const;
+
+/** The same food, ignoring case, spacing, punctuation and plurals. */
+export function memoryKey(name: string) {
+ return (
+ name
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N} ]/gu, ' ')
+ .split(/\s+/)
+ .filter(Boolean)
+ // "eggs" and "egg" are one food; "hummus" and "glass" stay as they are
+ .map((w) => (w.length > 3 && /[^su]s$/.test(w) ? w.slice(0, -1) : w))
+ .join(' ')
+ );
+}
+
+/**
+ * The instructions, plus the foods this person has logged before, so the
+ * model calls them by the same names and their numbers can be reused.
+ */
+export function mealInstructions(knownFoods: string[]) {
+ if (!knownFoods.length) return MEAL_INSTRUCTIONS;
+ return `${MEAL_INSTRUCTIONS}
+
+Foods this person has logged before: ${knownFoods.map((f) => JSON.stringify(f)).join(', ')}.
+When an item is one of these (same food, even if described differently), use that exact name.`;
+}
+
+const clamp = (n: number, lo: number, hi: number) =>
+ Math.min(hi, Math.max(lo, Number.isFinite(n) ? n : lo));
+
+/**
+ * Keeps an estimate physically possible: macros within 100 g, and calories
+ * consistent with them (4/4/9 kcal per gram). Where the stated calories and
+ * the macros disagree by more than 30%, the macros win.
+ */
+export function saneEstimate(p: Per100): Per100 {
+ let protein = clamp(p.protein, 0, 100);
+ let carbs = clamp(p.carbs, 0, 100);
+ let fat = clamp(p.fat, 0, 100);
+ const mass = protein + carbs + fat;
+ if (mass > 100) {
+ protein = (protein / mass) * 100;
+ carbs = (carbs / mass) * 100;
+ fat = (fat / mass) * 100;
+ }
+ const fromMacros = protein * 4 + carbs * 4 + fat * 9;
+ let kcal = clamp(p.kcal, 0, 900);
+ if (fromMacros > 0 && Math.abs(kcal - fromMacros) / fromMacros > 0.3)
+ kcal = fromMacros;
+ return {
+ kcal: round1(kcal),
+ protein: round1(protein),
+ carbs: round1(carbs),
+ fat: round1(fat),
+ };
+}
+
+/** Picks where each item's nutrition comes from, and its portion. */
+export function groundItem(
+ item: ModelItem,
+ memory: Memory | undefined,
+ database: Per100 | undefined,
+): ParsedItem {
+ const grams = clamp(Math.round(item.grams), 1, 2000);
+ if (memory) {
+ return {
+ name: item.name,
+ brand: item.brand,
+ portion: item.quantityStated
+ ? item.portion
+ : `your usual ${Math.round(memory.usualGrams)} g`,
+ // "Oats" with no amount means their usual amount
+ grams: item.quantityStated ? grams : Math.round(memory.usualGrams),
+ per100: memory,
+ source: 'memory',
+ confidence: 'high',
+ };
+ }
+ if (database) {
+ return {
+ name: item.name,
+ brand: item.brand,
+ portion: item.portion,
+ grams,
+ per100: database,
+ source: 'database',
+ confidence: item.confidence,
+ };
+ }
+ return {
+ name: item.name,
+ brand: item.brand,
+ portion: item.portion,
+ grams,
+ per100: saneEstimate({
+ kcal: item.kcalPer100g,
+ protein: item.proteinPer100g,
+ carbs: item.carbsPer100g,
+ fat: item.fatPer100g,
+ }),
+ source: 'estimate',
+ confidence: item.confidence,
+ };
+}
+
+/** An item's totals for its grams. */
+export function totals(per100: Per100, grams: number) {
+ const f = grams / 100;
+ return {
+ calories: Math.round(per100.kcal * f),
+ proteinG: round1(per100.protein * f),
+ carbsG: round1(per100.carbs * f),
+ fatG: round1(per100.fat * f),
+ };
+}
+
+function round1(n: number) {
+ return Math.round(n * 10) / 10;
+}
+
+export const MEAL_INSTRUCTIONS = `You read meals for a calorie tracker. Split what the person ate into separate foods.
+
+For each food:
+- name: short and generic ("fried egg", "sourdough toast"), brand only if they named one or it's clearly visible.
+- grams eaten: use their amount if they said it; otherwise a realistic portion for what they described or what the photo shows. Say in "portion" what you assumed ("2 large eggs", "1 tbsp").
+- quantityStated: true only if they gave the amount.
+- nutrition per 100 g as eaten (cooked, with typical preparation).
+- Hidden calories are the usual reason trackers undercount: list cooking oil, butter, dressings, sauces, sugar in drinks and toppings as their own items when they're likely to be there.
+- confidence: how sure you are of the portion.
+
+If one detail would change the total a lot and you can't tell (portion size of the main food, fried or grilled, sugar in a drink), ask about it in "question" (one short question). Otherwise question is null.
+Don't give advice. Only food the person ate.`;
diff --git a/packages/backend/src/notifications/notifications.service.ts b/packages/backend/src/notifications/notifications.service.ts
index 09de76a..56b1732 100644
--- a/packages/backend/src/notifications/notifications.service.ts
+++ b/packages/backend/src/notifications/notifications.service.ts
@@ -11,7 +11,8 @@ export type NotificationType =
| 'challenge_joined'
| 'challenge_ended'
| 'streak_at_risk'
- | 'weekly_progress';
+ | 'weekly_progress'
+ | 'coach_checkin';
export interface NewNotification {
type: NotificationType;
diff --git a/packages/backend/src/progress/adaptive.db-spec.ts b/packages/backend/src/progress/adaptive.db-spec.ts
new file mode 100644
index 0000000..bb81dce
--- /dev/null
+++ b/packages/backend/src/progress/adaptive.db-spec.ts
@@ -0,0 +1,110 @@
+import { TestDb } from '../test-utils/db';
+import { addDays, localToday } from '../common/day';
+import { AdaptiveService } from './adaptive.service';
+import { TrendsService } from './trends.service';
+import { WeightService } from './weight.service';
+
+describe('AdaptiveService (database)', () => {
+ const db = new TestDb();
+ const adaptive = new AdaptiveService(db.prisma, new TrendsService(db.prisma));
+ const weight = new WeightService(db.prisma);
+ const today = localToday(0);
+ afterAll(() => db.cleanup());
+
+ async function history(
+ userId: string,
+ supabaseId: string,
+ days: number,
+ kcal: number,
+ kgPerDay: number,
+ ) {
+ for (let i = days; i >= 1; i--) {
+ const date = addDays(today, -i);
+ const at = (h: number) =>
+ new Date(`${date}T${String(h).padStart(2, '0')}:00:00Z`);
+ await db.prisma.foodLog.createMany({
+ data: [
+ {
+ userId,
+ name: 'Lunch',
+ mealType: 'lunch',
+ calories: kcal / 2,
+ loggedAt: at(12),
+ },
+ {
+ userId,
+ name: 'Dinner',
+ mealType: 'dinner',
+ calories: kcal / 2,
+ loggedAt: at(19),
+ },
+ ],
+ });
+ await weight.log(supabaseId, 85 + kgPerDay * (days - i), 0, date);
+ }
+ }
+
+ it('shows progress until there is enough data', async () => {
+ const u = await db.user();
+ await history(u.id, u.supabaseId, 5, 2000, 0);
+ const r = await adaptive.checkIn(u.supabaseId, 0);
+ expect(r.estimate).toBeNull();
+ expect(r.suggestion).toBeNull();
+ expect(r.progress).toMatchObject({
+ loggedDays: 5,
+ weighIns: 5,
+ needs: { loggedDays: 10, weighIns: 4, spanDays: 14 },
+ });
+ });
+
+ it('estimates burn from intake and weight trend, and suggests a target once', async () => {
+ const u = await db.user();
+ await db.prisma.user.update({
+ where: { id: u.id },
+ data: {
+ calorieGoal: 2000,
+ primaryGoal: 'lose_weight',
+ pace: 'moderate',
+ gender: 'male',
+ heightCm: 180,
+ weightKg: 85,
+ dateOfBirth: new Date('1990-01-01'),
+ activityLevel: 'active',
+ },
+ });
+ // Eating 2,000 and losing ~0.5 kg/week → burning about 2,550
+ await history(u.id, u.supabaseId, 28, 2000, -0.5 / 7);
+
+ const r = await adaptive.checkIn(u.supabaseId, 0);
+ expect(r.estimate?.tdee).toBeGreaterThan(2400);
+ expect(r.estimate?.tdee).toBeLessThan(2750);
+ expect(r.estimate?.trendKgPerWeek).toBeLessThan(0);
+ // Already losing at the chosen pace: the target barely needs to move
+ expect(r.suggestion === null || Math.abs(r.suggestion.change) <= 200).toBe(
+ true,
+ );
+
+ await adaptive.apply(u.supabaseId, 1900);
+ const after = await adaptive.checkIn(u.supabaseId, 0);
+ expect(after.suggestion).toBeNull(); // settling for a week
+ expect(
+ (await db.prisma.user.findUnique({ where: { id: u.id } }))?.calorieGoal,
+ ).toBe(1900);
+ });
+
+ it('suggests more food when maintaining on too little, and can be put off', async () => {
+ const u = await db.user();
+ await db.prisma.user.update({
+ where: { id: u.id },
+ data: { calorieGoal: 1800, primaryGoal: 'maintain' },
+ });
+ // Eating 1,800 and losing 0.35 kg/week while meaning to maintain
+ await history(u.id, u.supabaseId, 28, 1800, -0.05);
+ const r = await adaptive.checkIn(u.supabaseId, 0);
+ expect(r.suggestion?.change).toBeGreaterThan(0);
+ expect(r.suggestion?.suggested).toBeLessThanOrEqual(2000);
+
+ await adaptive.snooze(u.supabaseId);
+ expect((await adaptive.checkIn(u.supabaseId, 0)).suggestion).toBeNull();
+ });
+});
diff --git a/packages/backend/src/progress/adaptive.service.ts b/packages/backend/src/progress/adaptive.service.ts
new file mode 100644
index 0000000..5351580
--- /dev/null
+++ b/packages/backend/src/progress/adaptive.service.ts
@@ -0,0 +1,114 @@
+import {
+ BadRequestException,
+ Injectable,
+ NotFoundException,
+} from '@nestjs/common';
+import { PrismaService } from '../prisma/prisma.service';
+import { TrendsService } from './trends.service';
+import {
+ estimateExpenditure,
+ formulaTdee,
+ isLoggedDay,
+ MIN_LOGGED_DAYS,
+ MIN_SPAN_DAYS,
+ MIN_WEIGH_INS,
+ suggestTarget,
+ type AdaptiveDay,
+} from './adaptive';
+
+const WINDOW_DAYS = 35;
+const SNOOZE_DAYS = 7;
+// After a change, give it a week before suggesting another
+const SETTLE_DAYS = 6;
+
+@Injectable()
+export class AdaptiveService {
+ constructor(
+ private prisma: PrismaService,
+ private trends: TrendsService,
+ ) {}
+
+ /** The current estimate and, if it's worth it, a new target to suggest. */
+ async checkIn(supabaseId: string, offset: number) {
+ const user = await this.prisma.user.findUnique({ where: { supabaseId } });
+ if (!user) throw new NotFoundException('User not found');
+ const { days } = await this.trends.trends(supabaseId, WINDOW_DAYS, offset);
+
+ const series: AdaptiveDay[] = days.map((d, i) => ({
+ date: d.date,
+ // Today isn't over, so its intake doesn't count
+ intake:
+ i < days.length - 1 &&
+ isLoggedDay(d.calories, d.foodEntries, user.calorieGoal)
+ ? d.calories
+ : null,
+ weightKg: d.weightKg,
+ }));
+ const prior = formulaTdee(user);
+ const estimate = estimateExpenditure(series, prior);
+
+ const now = new Date();
+ const settled =
+ !user.adaptiveAppliedAt ||
+ now.getTime() - user.adaptiveAppliedAt.getTime() >
+ SETTLE_DAYS * 86_400_000;
+ const snoozed =
+ !!user.adaptiveSnoozedUntil && user.adaptiveSnoozedUntil > now;
+ const suggestion =
+ estimate && settled && !snoozed
+ ? suggestTarget(estimate, user.calorieGoal, user.primaryGoal, user.pace)
+ : null;
+
+ const firstWeigh = series.findIndex((d) => d.weightKg != null);
+ const sinceWeigh = firstWeigh < 0 ? [] : series.slice(firstWeigh);
+ return {
+ estimate,
+ suggestion,
+ formulaTdee: prior,
+ // What's still missing before there's an estimate
+ progress: {
+ loggedDays: series.filter((d) => d.intake != null).length,
+ weighIns: series.filter((d) => d.weightKg != null).length,
+ spanDays: sinceWeigh.length,
+ needs: {
+ loggedDays: MIN_LOGGED_DAYS,
+ weighIns: MIN_WEIGH_INS,
+ spanDays: MIN_SPAN_DAYS,
+ },
+ },
+ snoozedUntil: snoozed ? user.adaptiveSnoozedUntil : null,
+ };
+ }
+
+ /** Takes the suggested target (or one the user adjusted). */
+ async apply(supabaseId: string, calorieGoal: number) {
+ if (
+ !Number.isInteger(calorieGoal) ||
+ calorieGoal < 1200 ||
+ calorieGoal > 10000
+ ) {
+ throw new BadRequestException(
+ 'calorieGoal must be a whole number from 1200 to 10000',
+ );
+ }
+ return this.prisma.user.update({
+ where: { supabaseId },
+ data: {
+ calorieGoal,
+ adaptiveAppliedAt: new Date(),
+ adaptiveSnoozedUntil: null,
+ },
+ select: { calorieGoal: true },
+ });
+ }
+
+ /** Not now: ask again in a week. */
+ async snooze(supabaseId: string) {
+ const until = new Date(Date.now() + SNOOZE_DAYS * 86_400_000);
+ await this.prisma.user.update({
+ where: { supabaseId },
+ data: { adaptiveSnoozedUntil: until },
+ });
+ return { snoozedUntil: until };
+ }
+}
diff --git a/packages/backend/src/progress/adaptive.spec.ts b/packages/backend/src/progress/adaptive.spec.ts
new file mode 100644
index 0000000..aaefca9
--- /dev/null
+++ b/packages/backend/src/progress/adaptive.spec.ts
@@ -0,0 +1,108 @@
+import {
+ estimateExpenditure,
+ isLoggedDay,
+ suggestTarget,
+ weightTrend,
+ type AdaptiveDay,
+} from './adaptive';
+
+/** n days, eating `intake`, weight moving `kgPerDay` from 80 kg, weighed every `every` days. */
+function series(
+ n: number,
+ intake: number | null,
+ kgPerDay: number,
+ every = 1,
+): AdaptiveDay[] {
+ return Array.from({ length: n }, (_, i) => ({
+ date: `d${i}`,
+ intake,
+ weightKg: i % every === 0 ? 80 + kgPerDay * i : null,
+ }));
+}
+
+describe('adaptive targets', () => {
+ it('judges whether a day was logged fully', () => {
+ expect(isLoggedDay(1500, 3, 2000)).toBe(true);
+ expect(isLoggedDay(600, 3, 2000)).toBe(false);
+ expect(isLoggedDay(1500, 1, 2000)).toBe(false);
+ });
+
+ it('smooths weigh-ins and carries the trend over gaps', () => {
+ const t = weightTrend([
+ { date: 'a', intake: null, weightKg: 80 },
+ { date: 'b', intake: null, weightKg: null },
+ { date: 'c', intake: null, weightKg: 82 },
+ ]);
+ expect(t).toEqual([80, 80, 80.2]);
+ });
+
+ it('needs enough days, logging and weigh-ins', () => {
+ expect(estimateExpenditure(series(10, 2000, 0), 2400)).toBeNull();
+ expect(estimateExpenditure(series(28, null, 0), 2400)).toBeNull();
+ expect(estimateExpenditure(series(28, 2000, 0, 10), 2400)).toBeNull();
+ });
+
+ it('finds maintenance when weight holds steady', () => {
+ const est = estimateExpenditure(series(28, 2300, 0), 2300)!;
+ expect(est.tdee).toBe(2300);
+ expect(est.confidence).toBe('high');
+ expect(est.trendKgPerWeek).toBe(0);
+ });
+
+ it('sees a higher burn when eating 2,000 while losing weight', () => {
+ // Losing 0.5 kg/week on 2,000 kcal → 2,000 + 0.5 × 7,700 / 7 = 2,550 burned
+ const est = estimateExpenditure(series(28, 2000, -0.5 / 7), null)!;
+ expect(est.tdee).toBe(2550);
+ expect(est.trendKgPerWeek).toBe(-0.5);
+ });
+
+ it('is steady against noisy weigh-ins', () => {
+ const noise = [0.6, -0.4, 0.2, -0.7, 0.5, -0.1, 0.3, -0.5];
+ const days = series(28, 2000, -0.5 / 7).map((d, i) => ({
+ ...d,
+ weightKg: d.weightKg! + noise[i % noise.length],
+ }));
+ const est = estimateExpenditure(days, null)!;
+ expect(Math.abs(est.tdee - 2550)).toBeLessThan(120);
+ });
+
+ it('leans on the formula when data is thin', () => {
+ const thin = series(14, 2000, 0, 3).map((d, i) => ({
+ ...d,
+ intake: i % 1 === 0 ? 2000 : null,
+ }));
+ const est = estimateExpenditure(thin, 3000)!;
+ expect(est.tdee).toBeGreaterThan(2000);
+ expect(est.confidence).toBe('low');
+ });
+
+ it('suggests a target for the goal in limited steps', () => {
+ const est = {
+ tdee: 2600,
+ confidence: 'high' as const,
+ loggedDays: 28,
+ weighIns: 20,
+ spanDays: 28,
+ trendKgPerWeek: -0.2,
+ avgIntake: 2400,
+ };
+ // Ideal for losing 0.5 kg/week is 2,050; from 2,400 the first step is −200
+ const s = suggestTarget(est, 2400, 'lose_weight', 'moderate')!;
+ expect(s).toMatchObject({
+ current: 2400,
+ suggested: 2200,
+ change: -200,
+ ideal: 2050,
+ });
+ expect(s.reason).toContain('losing 0.2 kg a week');
+ // Already there: nothing to suggest
+ expect(suggestTarget(est, 2060, 'lose_weight', 'moderate')).toBeNull();
+ // Maintaining, eating too little
+ expect(suggestTarget(est, 2300, 'maintain', null)?.suggested).toBe(2500);
+ // Never below the floor
+ expect(
+ suggestTarget({ ...est, tdee: 1300 }, 1400, 'lose_weight', 'aggressive')
+ ?.suggested,
+ ).toBe(1200);
+ });
+});
diff --git a/packages/backend/src/progress/adaptive.ts b/packages/backend/src/progress/adaptive.ts
new file mode 100644
index 0000000..fa1e6cd
--- /dev/null
+++ b/packages/backend/src/progress/adaptive.ts
@@ -0,0 +1,225 @@
+/**
+ * Adaptive calorie targets: estimate what someone actually burns from what
+ * they logged eating and how their weight trend moved, then suggest a target
+ * for their goal. Pure functions; the service feeds them daily data.
+ */
+
+export const KCAL_PER_KG = 7700;
+const TREND_ALPHA = 0.1; // smoothing for the weight trend (about a 10-day memory)
+export const MIN_SPAN_DAYS = 14;
+export const MIN_LOGGED_DAYS = 10;
+export const MIN_WEIGH_INS = 4;
+const MAX_STEP_KCAL = 200; // the most a single check-in moves the target
+const MIN_CHANGE_KCAL = 50; // smaller changes aren't worth suggesting
+export const FLOOR_KCAL = 1200;
+
+export interface AdaptiveDay {
+ date: string;
+ /** Calories logged, or null if the day wasn't logged fully enough to trust */
+ intake: number | null;
+ /** A weigh-in that day, if any */
+ weightKg: number | null;
+}
+
+export interface Estimate {
+ /** Estimated daily expenditure, kcal */
+ tdee: number;
+ confidence: 'low' | 'medium' | 'high';
+ loggedDays: number;
+ weighIns: number;
+ spanDays: number;
+ /** Weight trend change, kg per week (negative = losing) */
+ trendKgPerWeek: number;
+ /** Average logged intake on logged days */
+ avgIntake: number;
+}
+
+/** Whether a day's food log looks complete enough to use. */
+export function isLoggedDay(calories: number, entries: number, goal: number) {
+ return entries >= 2 && calories >= goal * 0.4;
+}
+
+/**
+ * An exponentially smoothed weight trend over every day from the first
+ * weigh-in, carrying the trend through days without one.
+ */
+export function weightTrend(days: AdaptiveDay[]): (number | null)[] {
+ let trend: number | null = null;
+ return days.map((d) => {
+ if (d.weightKg != null) {
+ trend =
+ trend == null ? d.weightKg : trend + TREND_ALPHA * (d.weightKg - trend);
+ }
+ return trend;
+ });
+}
+
+/** Least-squares slope of weight against day number, kg per day. */
+export function weightSlopePerDay(days: AdaptiveDay[]): number {
+ const points = days
+ .map((d, i) => [i, d.weightKg] as const)
+ .filter((p): p is readonly [number, number] => p[1] != null);
+ const n = points.length;
+ if (n < 2) return 0;
+ const mx = points.reduce((s, [x]) => s + x, 0) / n;
+ const my = points.reduce((s, [, y]) => s + y, 0) / n;
+ let num = 0;
+ let den = 0;
+ for (const [x, y] of points) {
+ num += (x - mx) * (y - my);
+ den += (x - mx) ** 2;
+ }
+ return den === 0 ? 0 : num / den;
+}
+
+/**
+ * Observed expenditure = average intake − energy stored in the weight change.
+ * Blended toward the formula estimate (`prior`) when data is thin. Null until
+ * there's enough data to say anything.
+ */
+export function estimateExpenditure(
+ days: AdaptiveDay[],
+ prior: number | null,
+): Estimate | null {
+ const firstWeigh = days.findIndex((d) => d.weightKg != null);
+ if (firstWeigh < 0) return null;
+ const window = days.slice(firstWeigh);
+ const spanDays = window.length;
+ const logged = window.filter((d) => d.intake != null);
+ const weighIns = window.filter((d) => d.weightKg != null).length;
+ if (
+ spanDays < MIN_SPAN_DAYS ||
+ logged.length < MIN_LOGGED_DAYS ||
+ weighIns < MIN_WEIGH_INS
+ ) {
+ return null;
+ }
+
+ // The weight change over the window, from a straight-line fit through the
+ // weigh-ins: steady against day-to-day water swings, and unlike a smoothed
+ // trend it doesn't lag behind a steady loss or gain
+ const change = weightSlopePerDay(window) * (spanDays - 1);
+ const avgIntake =
+ logged.reduce((s, d) => s + (d.intake as number), 0) / logged.length;
+ const observed =
+ avgIntake - (change * KCAL_PER_KG) / Math.max(1, spanDays - 1);
+
+ // How much to trust the observation over the formula
+ const weight = Math.min(1, logged.length / 21) * Math.min(1, weighIns / 8);
+ const tdee =
+ prior != null ? weight * observed + (1 - weight) * prior : observed;
+ const confidence =
+ logged.length >= 21 && weighIns >= 10
+ ? 'high'
+ : logged.length >= 14 && weighIns >= 6
+ ? 'medium'
+ : 'low';
+
+ return {
+ tdee: Math.round(tdee / 10) * 10,
+ confidence,
+ loggedDays: logged.length,
+ weighIns,
+ spanDays,
+ trendKgPerWeek:
+ Math.round((change / Math.max(1, spanDays - 1)) * 7 * 100) / 100,
+ avgIntake: Math.round(avgIntake),
+ };
+}
+
+const PACE_KG_PER_WEEK: Record = {
+ slow: 0.25,
+ moderate: 0.5,
+ aggressive: 1,
+};
+
+/** The target for the goal at that expenditure, before limits. */
+export function idealTarget(tdee: number, goal: string, pace: string | null) {
+ const kgPerWeek = PACE_KG_PER_WEEK[pace ?? 'moderate'] ?? 0.5;
+ const daily = (KCAL_PER_KG * kgPerWeek) / 7;
+ if (goal === 'lose_weight') return tdee - daily;
+ // Lean gain: half the pace
+ if (goal === 'build_muscle' || goal === 'build_strength')
+ return tdee + daily / 2;
+ return tdee;
+}
+
+export interface Suggestion {
+ current: number;
+ suggested: number;
+ change: number;
+ /** The goal's ideal target, which a single step may not reach */
+ ideal: number;
+ reason: string;
+}
+
+/**
+ * The next target: toward the ideal, at most 200 kcal per check-in, never
+ * below 1,200, and only when the change is worth making.
+ */
+export function suggestTarget(
+ est: Estimate,
+ current: number,
+ goal: string,
+ pace: string | null,
+): Suggestion | null {
+ const ideal = Math.max(
+ FLOOR_KCAL,
+ Math.round(idealTarget(est.tdee, goal, pace) / 10) * 10,
+ );
+ const delta = Math.max(
+ -MAX_STEP_KCAL,
+ Math.min(MAX_STEP_KCAL, ideal - current),
+ );
+ const suggested = Math.max(
+ FLOOR_KCAL,
+ Math.round((current + delta) / 10) * 10,
+ );
+ const change = suggested - current;
+ if (Math.abs(change) < MIN_CHANGE_KCAL) return null;
+
+ const trend = est.trendKgPerWeek;
+ const moving =
+ trend < -0.05
+ ? `losing ${Math.abs(trend)} kg a week`
+ : trend > 0.05
+ ? `gaining ${trend} kg a week`
+ : 'holding steady';
+ const reason =
+ `Over ${est.spanDays} days you ate about ${est.avgIntake.toLocaleString('en-US')} kcal a day and were ${moving}, ` +
+ `so you burn roughly ${est.tdee.toLocaleString('en-US')} kcal a day.` +
+ (suggested === ideal
+ ? ''
+ : ` Moving ${change > 0 ? 'up' : 'down'} in steps keeps the change manageable.`);
+ return { current, suggested, change, ideal, reason };
+}
+
+const ACTIVITY = {
+ sedentary: 1.2,
+ lightly_active: 1.375,
+ active: 1.55,
+ very_active: 1.725,
+} as Record;
+
+/** Mifflin-St Jeor × activity, from the profile; null if it's incomplete. */
+export function formulaTdee(
+ u: {
+ gender: string | null;
+ weightKg: number | null;
+ heightCm: number | null;
+ dateOfBirth: Date | null;
+ activityLevel: string | null;
+ },
+ now = new Date(),
+): number | null {
+ if (!u.weightKg || !u.heightCm || !u.dateOfBirth) return null;
+ const age = (now.getTime() - u.dateOfBirth.getTime()) / (365.25 * 86_400_000);
+ const base = 10 * u.weightKg + 6.25 * u.heightCm - 5 * age;
+ const bmr =
+ u.gender === 'male'
+ ? base + 5
+ : u.gender === 'female'
+ ? base - 161
+ : base - 78;
+ return Math.round(bmr * (ACTIVITY[u.activityLevel ?? ''] ?? 1.2));
+}
diff --git a/packages/backend/src/progress/progress.controller.ts b/packages/backend/src/progress/progress.controller.ts
index dab45e7..0b43c5b 100644
--- a/packages/backend/src/progress/progress.controller.ts
+++ b/packages/backend/src/progress/progress.controller.ts
@@ -14,6 +14,13 @@ import { UtcOffset } from '../common/utc-offset.decorator';
import { LogWeightDto, RangeQueryDto, WeightQueryDto } from './progress.dto';
import { TrendsService } from './trends.service';
import { WeightService } from './weight.service';
+import { AdaptiveService } from './adaptive.service';
+import { IsInt } from 'class-validator';
+
+class ApplyTargetDto {
+ @IsInt()
+ calorieGoal: number;
+}
type Me = { supabaseId: string };
@@ -23,8 +30,25 @@ export class ProgressController {
constructor(
private weight: WeightService,
private trends: TrendsService,
+ private adaptive: AdaptiveService,
) {}
+ /** Estimated burn from intake and weight trend, and a suggested target. */
+ @Get('targets/adaptive')
+ checkIn(@CurrentUser() user: Me, @UtcOffset() offset: number) {
+ return this.adaptive.checkIn(user.supabaseId, offset);
+ }
+
+ @Post('targets/adaptive/apply')
+ apply(@CurrentUser() user: Me, @Body() body: ApplyTargetDto) {
+ return this.adaptive.apply(user.supabaseId, body.calorieGoal);
+ }
+
+ @Post('targets/adaptive/snooze')
+ snooze(@CurrentUser() user: Me) {
+ return this.adaptive.snooze(user.supabaseId);
+ }
+
/** Weigh-ins for the last 30, 90 (default) or 365 days. */
@Get('weight')
history(
diff --git a/packages/backend/src/progress/progress.module.ts b/packages/backend/src/progress/progress.module.ts
index 572e80c..113737f 100644
--- a/packages/backend/src/progress/progress.module.ts
+++ b/packages/backend/src/progress/progress.module.ts
@@ -2,10 +2,11 @@ import { Module } from '@nestjs/common';
import { ProgressController } from './progress.controller';
import { TrendsService } from './trends.service';
import { WeightService } from './weight.service';
+import { AdaptiveService } from './adaptive.service';
@Module({
controllers: [ProgressController],
- providers: [WeightService, TrendsService],
- exports: [WeightService],
+ providers: [WeightService, TrendsService, AdaptiveService],
+ exports: [WeightService, AdaptiveService],
})
export class ProgressModule {}