Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
name: CI

on:
push:
branches: [main]
pull_request:

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
backend:
name: Backend
runs-on: ubuntu-latest
timeout-minutes: 20
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: grit
POSTGRES_PASSWORD: grit
POSTGRES_DB: grit
ports: ['5432:5432']
options: >-
--health-cmd "pg_isready -U grit"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
# A throwaway database for migrations and the database tests
DATABASE_URL: postgresql://grit:grit@localhost:5432/grit
DIRECT_URL: postgresql://grit:grit@localhost:5432/grit
SHADOW_DATABASE_URL: postgresql://grit:grit@localhost:5432/grit_shadow
defaults:
run:
working-directory: packages/backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Install
working-directory: .
run: npm install --no-audit --no-fund
- name: Generate Prisma client
run: npx prisma generate
- name: Apply migrations
run: npx prisma migrate deploy
- name: Check the schema matches the migrations
run: |
PGPASSWORD=grit psql -h localhost -U grit -d grit -c 'CREATE DATABASE grit_shadow'
npx prisma migrate diff --from-migrations prisma/migrations --to-schema-datamodel prisma/schema.prisma --shadow-database-url "$SHADOW_DATABASE_URL" --exit-code
- name: Format
run: npx prettier --check "src/**/*.ts" "test/**/*.ts"
- name: Lint
run: npx eslint "src/**/*.ts"
- name: Typecheck
run: npx tsc --noEmit -p tsconfig.json
- name: Unit tests
run: npm test
- name: Database tests
run: npm run test:db
- name: Build
run: npm run build && test -f dist/main.js

mobile:
name: Mobile
runs-on: ubuntu-latest
timeout-minutes: 20
defaults:
run:
working-directory: apps/mobile
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Install
working-directory: .
run: npm install --no-audit --no-fund
- name: Typecheck
run: npx tsc --noEmit
- name: Lint
run: npx eslint .
- name: Unit tests
run: npm test -- --ci
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS).
| `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 |
| `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 |

**Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood
Expand Down Expand Up @@ -142,6 +143,9 @@ cd packages/backend && npm run start:dev

# Unit tests, and database tests against DATABASE_URL (a throwaway Postgres)
cd packages/backend && npm test && npm run test:db

# Mobile lint and unit tests
cd apps/mobile && npm run lint && npm test
```

### Environment
Expand All @@ -150,7 +154,9 @@ cd packages/backend && npm test && npm run test:db
cp packages/backend/.env.example packages/backend/.env
```

See [`packages/backend/.env.example`](./packages/backend/.env.example). The app refuses to boot without `DATABASE_URL`, `DIRECT_URL`, `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_API_KEY`. `SUPABASE_SERVICE_KEY` and the Upstash vars are not read by the code yet. Optional: `EXPO_ACCESS_TOKEN` (if push security is on for the Expo project) and `PUSH_DISABLED=true` (don't send pushes, e.g. locally).
See [`packages/backend/.env.example`](./packages/backend/.env.example). The app refuses to boot without `DATABASE_URL`, `DIRECT_URL`, `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_API_KEY`. `SUPABASE_SERVICE_KEY` and the Upstash vars are not read by the code yet. Optional: `EXPO_ACCESS_TOKEN` (if push security is on for the Expo project), `PUSH_DISABLED=true` (don't send pushes, e.g. locally), `RATE_LIMIT_PER_MINUTE` (default 300 per signed-in session) and `CORS_ORIGINS` (comma-separated web origins; default any). The server checks its settings at boot and lists anything missing or malformed.

Every response carries an `x-request-id` (also in error bodies), matching one log line per request. Logs are JSON when `NODE_ENV=production`. Sign-in tokens are verified locally against the Supabase project's published signing key. `GET /health` reports the API and database; `POST /client-errors` records crashes reported by the app.

Profile photos go to a public Supabase Storage bucket, `avatars`, which the privacy migration creates along with rules that let each user write only to their own folder.

Expand Down Expand Up @@ -211,7 +217,13 @@ A cloud instance can't run a simulator. Use it for type-checking and linting, or

### Deploying the backend (Railway)

[`packages/backend/railway.toml`](./packages/backend/railway.toml) builds with Nixpacks (`npm run build`) and starts `node dist/main`. Set the root directory to `packages/backend`, add the env vars above in Railway, and run `npx prisma migrate deploy` before or as part of each release.
[`packages/backend/railway.toml`](./packages/backend/railway.toml) builds with Nixpacks (`npm run build`) and starts `node dist/main`. Set the root directory to `packages/backend`, add the env vars above in Railway, and run `npx prisma migrate deploy` before or as part of each release. Railway's health check calls `GET /health`, which also checks the database.

**One migration waits for a deploy:** `20261105130000_drop_users_push_token` drops a column that Phase 2 servers read. Apply it only after Railway is running Phase 3 or later.

### CI

[`.github/workflows/ci.yml`](./.github/workflows/ci.yml) runs on every pull request and push to `main`: the backend job applies the migrations to a throwaway Postgres, checks they match the schema, and runs prettier, eslint, tsc, unit tests, database tests and the build; the mobile job runs tsc, eslint and unit tests.

---

Expand Down
21 changes: 21 additions & 0 deletions apps/mobile/__tests__/challenges.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { amount, daysLeftLabel, hasEnded, measureName } from '@/lib/challenges';

describe('challenge labels', () => {
it('formats amounts by type', () => {
expect(amount('steps', 12400)).toBe('12,400 steps');
expect(amount('group_steps', 1)).toBe('1 step');
expect(amount('active_minutes', 95)).toBe('95 min');
expect(amount('workouts', 1)).toBe('1 workout');
expect(measureName('workouts')).toBe('workouts');
});
it('knows when a challenge has ended', () => {
const soon = new Date(Date.now() + 3600_000).toISOString();
const past = new Date(Date.now() - 1000).toISOString();
expect(hasEnded({ endedAt: null, endDate: soon })).toBe(false);
expect(hasEnded({ endedAt: null, endDate: past })).toBe(true);
expect(hasEnded({ endedAt: past, endDate: soon })).toBe(true);
expect(daysLeftLabel(soon)).toBe('Last day');
expect(daysLeftLabel(new Date(Date.now() + 3.5 * 86_400_000).toISOString())).toBe('4d left');
expect(daysLeftLabel(past)).toBe('Ended');
});
});
26 changes: 26 additions & 0 deletions apps/mobile/__tests__/date.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { addDaysStr, dayLabel, loggedAtFor, weekLabel, weekStartStr } from '@/lib/date';

describe('local dates', () => {
it('adds days across months and years', () => {
expect(addDaysStr('2026-12-31', 1)).toBe('2027-01-01');
expect(addDaysStr('2026-03-01', -1)).toBe('2026-02-28');
expect(addDaysStr('2028-03-01', -1)).toBe('2028-02-29');
});
it('labels days', () => {
expect(dayLabel('2026-11-04', '2026-11-04')).toBe('Today');
expect(dayLabel('2026-11-03', '2026-11-04')).toBe('Yesterday');
expect(dayLabel('2026-11-02', '2026-11-04')).toBe('Mon 2 Nov');
});
it('finds the Monday and labels the week', () => {
expect(weekStartStr('2026-11-08')).toBe('2026-11-02'); // Sunday
expect(weekStartStr('2026-11-02')).toBe('2026-11-02');
expect(weekLabel('2026-11-02')).toBe('2 – 8 Nov');
expect(weekLabel('2026-10-26')).toBe('26 Oct – 1 Nov');
});
it('back-dated logs land at local midday; today uses the server clock', () => {
expect(loggedAtFor('2026-11-04', '2026-11-04')).toBeUndefined();
const iso = loggedAtFor('2026-11-01', '2026-11-04')!;
expect(new Date(iso).getHours()).toBe(12);
expect(new Date(iso).getDate()).toBe(1);
});
});
17 changes: 17 additions & 0 deletions apps/mobile/__tests__/notificationRoute.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { notificationRoute } from '@/lib/notificationRoute';

describe('where an alert opens', () => {
it('sends each type to its screen', () => {
expect(notificationRoute('follow_request')).toEqual({ pathname: '/friends', params: { tab: 'requests' } });
expect(notificationRoute('kudos', { userId: 'u1' })).toEqual({ pathname: '/profile/[id]', params: { id: 'u1' } });
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');
});
it('falls back to the inbox when ids are missing or the type is unknown', () => {
expect(notificationRoute('follow')).toBe('/notifications');
expect(notificationRoute('challenge_joined')).toBe('/(tabs)/social');
expect(notificationRoute('something_new')).toBe('/notifications');
expect(notificationRoute(undefined)).toBe('/notifications');
});
});
17 changes: 17 additions & 0 deletions apps/mobile/__tests__/quickFoods.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { foodKey, portionAsFood, portionLabel } from '@/lib/quickFoods';

describe('quick foods', () => {
it('matches the server key', () => {
expect(foodKey(' Greek Yogurt ', 'Fage')).toBe('greek yogurt|fage');
expect(foodKey('Oats')).toBe('oats|');
});
it('labels portions', () => {
expect(portionLabel({ servingQty: 150, servingUnit: 'g' })).toBe('150 g');
expect(portionLabel({ servingQty: 1, servingUnit: 'serving' })).toBe('1 serving');
expect(portionLabel({ servingQty: 2.25, servingUnit: 'serving' })).toBe('2.3 servings');
});
it('turns a saved portion into a loggable food', () => {
const food = portionAsFood({ name: 'Oats', brand: null, barcode: null, calories: 300, proteinG: 10, carbsG: 50, fatG: 6, servingQty: 80, servingUnit: 'g' });
expect(food).toMatchObject({ portion: true, offId: '', calories: 300, servingQty: 80 });
});
});
35 changes: 35 additions & 0 deletions apps/mobile/__tests__/tdee.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { calcAdjustedCalories, calcBMR, calcMacros, calcTDEE, calcTimeline } from '@/lib/tdee';

describe('calorie maths', () => {
it('Mifflin-St Jeor BMR', () => {
// 10*80 + 6.25*180 - 5*30 = 1775
expect(calcBMR('male', 80, 180, 30)).toBe(1780);
expect(calcBMR('female', 80, 180, 30)).toBe(1614);
expect(calcBMR('other', 80, 180, 30)).toBe(1697);
});

it('TDEE by activity level, sedentary when unknown', () => {
expect(calcTDEE(1780, 'active')).toBe(2759);
expect(calcTDEE(1780, 'nonsense')).toBe(2136);
});

it('deficit or surplus by goal and pace, never under 1200 to lose', () => {
expect(calcAdjustedCalories(2500, 'lose_weight', 'moderate')).toBe(1950);
expect(calcAdjustedCalories(2500, 'build_muscle', 'slow')).toBe(2775);
expect(calcAdjustedCalories(2500, 'maintain', 'aggressive')).toBe(2500);
expect(calcAdjustedCalories(1500, 'lose_weight', 'aggressive')).toBe(1200);
});

it('macro splits match the backend', () => {
expect(calcMacros(2000, 'high_protein')).toEqual({ proteinG: 200, carbsG: 150, fatG: 67 });
expect(calcMacros(2000, 'balanced')).toEqual({ proteinG: 150, carbsG: 200, fatG: 67 });
expect(calcMacros(2000, 'low_carb')).toEqual({ proteinG: 150, carbsG: 100, fatG: 111 });
expect(calcMacros(2000)).toEqual(calcMacros(2000, 'balanced'));
});

it('weeks to goal', () => {
expect(calcTimeline(90, 80, 'moderate')).toBe(20);
expect(calcTimeline(80, 80, 'moderate')).toBeNull();
expect(calcTimeline(90, 80, 'unknown')).toBeNull();
});
});
15 changes: 15 additions & 0 deletions apps/mobile/__tests__/units.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { formatHeight, formatWeight, kgToUnit, unitToKg } from '@/lib/units';

describe('units', () => {
it('converts weight both ways to one decimal', () => {
expect(kgToUnit(80, 'lb')).toBe(176.4);
expect(unitToKg(176.4, 'lb')).toBe(80);
expect(kgToUnit(80, 'kg')).toBe(80);
});
it('formats weight and height', () => {
expect(formatWeight(78.46, 'kg')).toBe('78.5 kg');
expect(formatWeight(null, 'lb')).toBe('—');
expect(formatHeight(175, 'cm')).toBe('175 cm');
expect(formatHeight(175, 'ft')).toBe('5′9″');
});
});
13 changes: 13 additions & 0 deletions apps/mobile/app.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Adds build-specific settings on top of app.json.
//
// Plain-HTTP traffic is only allowed in development builds, which may talk to
// a backend on the local network. Store builds (EAS "preview" and
// "production") only use HTTPS.
module.exports = ({ config }) => {
const profile = process.env.EAS_BUILD_PROFILE;
const development = profile ? profile === 'development' : process.env.NODE_ENV !== 'production';
return {
...config,
android: { ...config.android, usesCleartextTraffic: development },
};
};
41 changes: 37 additions & 4 deletions apps/mobile/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,48 @@
"usesAppleSignIn": true,
"infoPlist": {
"ITSAppUsesNonExemptEncryption": false
},
"privacyManifests": {
"NSPrivacyAccessedAPITypes": [
{
"NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryUserDefaults",
"NSPrivacyAccessedAPITypeReasons": [
"CA92.1"
]
},
{
"NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryFileTimestamp",
"NSPrivacyAccessedAPITypeReasons": [
"C617.1"
]
},
{
"NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategorySystemBootTime",
"NSPrivacyAccessedAPITypeReasons": [
"35F9.1"
]
},
{
"NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryDiskSpace",
"NSPrivacyAccessedAPITypeReasons": [
"E174.1"
]
}
]
}
},
"android": {
"package": "com.gritapp.mobile",
"minSdkVersion": 26,
"usesCleartextTraffic": true,
"usesCleartextTraffic": false,
"adaptiveIcon": {
"backgroundColor": "#0D0D0D",
"foregroundImage": "./assets/android-icon-foreground.png"
},
"permissions": [
"android.permission.CAMERA",
"android.permission.CAMERA"
],
"blockedPermissions": [
"android.permission.RECORD_AUDIO"
]
},
Expand All @@ -44,7 +74,9 @@
[
"expo-camera",
{
"cameraPermission": "GRIT uses your camera to scan food barcodes."
"cameraPermission": "GRIT uses your camera to scan food barcodes.",
"microphonePermission": false,
"recordAudioAndroid": false
}
],
[
Expand All @@ -59,7 +91,8 @@
"expo-image-picker",
{
"photosPermission": "GRIT uses your photos so you can choose a profile picture.",
"cameraPermission": false
"cameraPermission": false,
"microphonePermission": false
}
]
],
Expand Down
2 changes: 1 addition & 1 deletion apps/mobile/app/(auth)/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export default function LoginScreen() {
New here?
</Text>
<Link href="/onboarding" asChild>
<Pressable>
<Pressable accessibilityRole="button">
<Text
style={{
color: Colors.orange,
Expand Down
2 changes: 1 addition & 1 deletion apps/mobile/app/(tabs)/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ function FloatingTabBar({ state, descriptors, navigation }: BottomTabBarProps) {
const color = isFocused ? Colors.orange : Colors.muted;

return (
<Pressable
<Pressable accessibilityRole="tab" aria-selected={isFocused} accessibilityLabel={label}
key={route.key}
onPress={() => {
const event = navigation.emit({
Expand Down
2 changes: 1 addition & 1 deletion apps/mobile/app/(tabs)/activity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ export default function ActivityScreen() {
</View>

{/* Log button */}
<Pressable
<Pressable accessibilityRole="button"
onPress={() => {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
setShowSheet(true);
Expand Down
Loading
Loading