Last updated: 2026-11-13
This is the repo-root monorepo guide for SparkyFitness. Use it to choose the right package, understand shared repo-level rules, and find the next guide to read.
For AI Tools & Developers: Start with agent-docs/README.md (in this repo) for quick navigation to:
file-and-domain-reference.md— Find any code by feature in secondstesting-patterns.md— Concrete test examples for each layerarchitecture-permissions.md— Permission types and RLS patterns- Plus 5 more guides for migrations, data flow, anti-patterns, new features, and planning
Package-level guides win. For work inside a package, follow that package's AGENTS.md when present, otherwise its CLAUDE.md.
- Start here when work begins at repo root or spans multiple packages.
- Keep root-level guidance focused on workspace layout, shared conventions, and cross-package coordination.
- Root
package.jsonis tooling only (husky,lint-staged,prettier), not an app entrypoint. - Run scripts from the package directory you are changing.
- Repo-root alias:
CLAUDE.mdpoints to this file. - Frontend:
SparkyFitnessFrontend/AGENTS.md - Server:
SparkyFitnessServer/AGENTS.md - Mobile:
SparkyFitnessMobile/AGENTS.md - Shared:
shared/AGENTS.md
For docs/ and SparkyFitnessGarmin/, there is no package-level AGENTS.md. SparkyFitnessGarmin/ is only a handful of Python files (main.py, routes.py, service.py, schemas.py); read them directly. For docs/, inspect the local manifest and content layout.
SparkyFitnessFrontend/- React 19 + Vite web app.SparkyFitnessServer/- Express 5 + PostgreSQL backend API.SparkyFitnessMobile/- Expo SDK 57 / React Native 0.86 app.shared/- source-first TypeScript workspace package for@workspace/sharedschemas, constants, and timezone/day helpers.docs/- VitePress documentation site.docs/readme/- translated copies of the rootREADME.md(README_<lang>.md), outside the VitePresssrcDir. The language bar at the top ofREADME.mdlinks to them; when the root README changes substantially, the translations go stale.SparkyFitnessGarmin/- standalone Python integration service outside the currentpnpmworkspace.SparkyFitnessTag/- static site behindhttps://tag.sparkyfitness.com(Cloudflare Workers static assets, deployed from this folder withwrangler.jsonc). It serves only Apple'sapple-app-site-association, Android'sassetlinks.jsonand a "get the app" page, so an NFC tag link (/t/<code>) opens the mobile app. Holds no secrets and stores no data; a new app ID, Apple team or signing key means editing the two.well-knownfiles. Not apnpmworkspace package. Do not add a_redirectsrule for/t/*: Cloudflare rejects it as a loop, andnot_found_handling: single-page-applicationalready serves the page.SparkyFitnessZeppAuth/- Cloudflare Worker behindhttps://zepp-auth.sparkyfitness.com, the Zepp (Amazfit) OAuth relay for #301. Zepp grants SparkyFitness one shared client ID, and the token exchange needs a secret that self-hosted servers must not hold, so the relay will keep it; each user's server callsapi-open.zepp.comdirectly, so health data never passes through it. Currently registration-only: bareGET/HEADon/api/zepp/oauth/callbackand/api/zepp/data/callbackreturn 200, and everything else is refused. Plain JS, deployed withwrangler deployfrom the folder; not apnpmworkspace package. Keep secrets out ofSparkyFitnessTag/.docker/,helm/,.github/- infra and deployment assets.umbrel/sparkyfitness/- Umbrel App Store package (manifest, compose, derived secrets), submitted togetumbrel/umbrel-apps. Seeumbrel/README.md.db_schema_backup.sql- repo-root schema snapshot kept in sync by CI (.github/workflows/schema-backup.yml); never hand-edit or regenerate locally.docker/.env.example- tracked env template commonly copied to repo-root.env.
pnpm-workspace.yamlcurrently listsfrontend,SparkyFitnessFrontend,shared,SparkyFitnessMobile,SparkyFitnessServer, anddocs.- Only
SparkyFitnessFrontend/exists on disk right now; treatfrontendas a legacy workspace entry unless the task is specifically about workspace cleanup. shared/is a library package, not an app; itspnpm run validateruns typecheck, a hardcoded-string audit, and the Prettier check. CI runs that in aShared Validatejob and also re-runs the frontend, mobile, and server jobs whenevershared/changes, so validate shared changes from the consuming package(s), not in isolation.SparkyFitnessGarmin/is outside the current workspace. Inspect its own manifest and scripts before working there.
Do not read or search these paths; they burn context for nothing:
WIP/- personal scratch area; contains zips and full copies of other repos, including a stale duplicate of this repo (WIP/SparkyFitness-main/). Never read or edit anything under it.SparkyFitnessMobile/ios/andSparkyFitnessMobile/android/- generated native projects (ios/is >1 GB of Pods). Regenerate withnpx expo prebuild --clean; editapp.config.ts,plugins/, ortargets/instead.pnpm-lock.yaml(~1.3 MB) - never read; checkpackage.jsonfiles instead.db_schema_backup.sql(~330 KB) - never read whole; grep for the oneCREATE TABLEyou need.SparkyFitnessFrontend/dist/- build output.SparkyFitnessFrontend/public/locales/excepten/- 35 machine-synced translations. Onlyen/translation.jsonis ever hand-edited, and even that (~120 KB) should be grepped, not read whole.SparkyFitnessExerciseLibrary/exercises/anddist/- static dataset with 1,300+ exercise folders. Never search or read whole during general app tasks (burns tokens for nothing); inspectschema/exercise.schema.jsonortaxonomy/instead unless the user explicitly asks to research, edit, or import exercises.
Cheap ways to learn things:
- Database table index: read
docs/src/developer/database.md(quick reference of all ~120 tables with one-line purpose). For detailed schema, readshared/src/schemas/database/<Table>.zod.ts(one small Zod file per table). - Database security & permissions:
docs/src/developer/database-security-tiers.md(security tier, permission type, and RLS rules for every table). - API request/response contract:
shared/src/schemas/api/<Name>.api.zod.ts. - Definition of done: CI (
.github/workflows/ci-tests.yml) runspnpm run validate(which includes Knip unused export & dead code checks in frontend and mobile) plus the package's CI test script for each changed package. Run those locally before declaring work complete.
Mealie ingredient meals use shared/src/schemas/api/RecipeImport.api.zod.ts and owner-only /api/v2/recipe-imports routes. Preview/suggest never create foods or meals; save accepts confirmed accessible local food/variant IDs and uses authoritative nutrition. External candidates follow existing provider detail/import first. Cooked weight changes only the normal meal serving denominator. Nutrition sync previews current saved-meal totals per current Mealie serving and requires explicit confirmation of that state; diary edits never write back.
-
Barcode source comparison uses the shared
BarcodeLookup.api.zod.tscontract andbarcodeNutritionPreviewhelper. Web and mobile request alternatives on demand throughSparkyFitnessServer/services/barcodeLookupService.ts; the initial lookup retains the existing local/default/fallback behavior. -
If you add or change a server migration (such as creating a new table), follow
agent-docs/new-migration-checklist.md. In short, you MUST:- Create the migration file in
SparkyFitnessServer/db/migrations/YYYYMMDDHHMMSS_description.sql. - Update the Row-Level Security (RLS) policies in
SparkyFitnessServer/db/rls_policies.sql, and classify the new table in theDOMAINmap ofSparkyFitnessServer/tests/rlsPermissionMatrix.integration.test.ts(CI fails when an RLS table is missing). - Restart the server (
pnpm startfromSparkyFitnessServer/) to apply the migration. Agents ask the user to do this rather than starting it themselves. Keep one re-runnable migration file per PR, edited in place. - Leave
db_schema_backup.sqlalone — after merge, CI regenerates it from the migrations and opens a sync PR that merges itself (.github/workflows/schema-backup.yml). Never manually edit the backup file or commit a locally generated copy. - Add or update the matching Zod schema in
shared/src/schemas/database/. - Update the user-facing documentation in
docs/src/features/family-friends-sharing.md. - Update the developer documentation in
docs/src/developer/database-security-tiers.mdto classify the table as Tier 1, Tier 2, or Tier 3.
- Create the migration file in
-
Optional features (#3487) have one registry:
shared/src/features/optionalFeatures.ts(OPTIONAL_FEATURES,isFeatureEnabled,isFeatureExplicitlyOff,filterByFeature). A feature a person can turn on or off in Settings → Features is registered there, with its default, and every entry point to it (tab, menu item, card, route, reminder, watch page) declares its key and goes through the shared filter or a guard; never readfeature_choicesorcycle_settings.enableddirectly to show or hide something (the web's gates go through it,SparkyFitnessFrontend/src/hooks/Settings/useWebFeatures.ts; cycle's mobile gates still readcycle_settings.enabledand move when the mobile Features screen lands). Choices are per platform (FEATURE_PLATFORMS:webis the website on any screen,mobilethe native app with its watch pages, widgets and reminders; not the nutrient-displayplatformvalues), so each app asksisFeatureEnabled(key, '<its platform>', sources); code that is about neither app's screens (the server, someone acting for the person) usesisFeatureEnabledAnywhere. The server stores only explicit choices inuser_preferences.feature_choices({ web, mobile }), read throughGET /api/user-preferences/features(never the general preferences payload, which falls back to defaults on errors) and written only by the owner-onlyPATCHthere; cycle keeps its own switch (cycle_settings.enabled). Add a key together with its gates on both web and mobile, so neither Features screen lists a switch that hides nothing. The switch hides UI only: no route, importer, sync or MCP tool checks it, and it never rewrites the finer per-place settings (the web tabs, Customize layout, hidden cards, the + menu, watch pages), so turning a feature back on restores them. -
Heart rate zones have one source of truth:
shared/src/utils/heartRateZones.ts(resolveHeartRateZones,heartRateZoneRange,computeTimeInZones). Never re-derive max heart rate or zone floors in a package; server stored zones, training load, mobile suggested ranges and the web/mobile charts, Heart Rate reports and settings all call it (reports show the five zones, Zone 1 to 5, never fixed bpm tiers). Max heart rate is the person's own value, else Nes (211 - 0.64 x age) from date of birth, else 190. Settings never rewrite storedexercise_entry_hr_zonesrows. iOS 27 can fill custom floors from Apple Health (floorsFromAppleHeartRateZones); that does not change max heart rate. A finished Apple workout's own zone group (bucketsFromAppleWorkoutZones) is stored asdevicezones instead of recomputing, so the chart matches Apple, including time below the first boundary. -
Estimated blood alcohol has one source of truth:
shared/src/nutrients/alcoholKinetics.ts. Server, web, mobile and AI tools never re-derive BAC; clients draw withbloodAlcoholCurve(doses, bacModelOf(response), ...)andbloodAlcoholChartWindow. It is always shown with the rough-estimate, not-for-driving disclaimer, and nothing (UI, API, tool text, docs) states a time when the level reaches zero. -
Exercise write-back activity types have one source:
shared/src/constants/healthActivityTypes.ts(each key's Apple Health and Health Connect type, the name/category guess) andhealthConnectSegments.ts(per-set segments and androidx's compatibility rules). The per-exercise override isexercises.health_activity_type, copied onto eachexercise_entriesrow; NULL is Automatic. Never map activity types in a package. -
Prefer the shared timezone helpers from
@workspace/sharedandSparkyFitnessServer/utils/timezoneLoader.tsfor day-string logic. AvoidtoISOString().split('T')[0]for user-facing or business-logic dates. -
Keep
YYYY-MM-DDvalues as calendar-day strings until you reach a database or external API boundary that needs UTC instants. -
Auth or API contract changes usually need a quick check in both web and mobile because they share the same backend.
-
Frontend local dev proxies
/api,/health-data, and/uploadsto the server on3010. The/health-dataproxy is rewritten to/api/health-data, while server APIs remain rooted at/api. -
Server runtime secrets are usually sourced from repo-root
.env, commonly created fromdocker/.env.example. The server can also load secret files viaSparkyFitnessServer/utils/secretLoader.ts. -
Extract shared logic on the second duplication ("rule of two"), not the third - duplicated logic drifts as different sessions edit each copy. Extract behavior, not coincidental shape. See
agent-docs/anti-patterns.md. -
Strict TypeScript Typing: Never use
anyor// eslint-disable-next-line @typescript-eslint/no-explicit-anywhen creating new functions or editing existing code. When modifying existing files, proactively update legacyanydeclarations in the touched code to reflect their proper TypeScript data types, interfaces, or schemas from@workspace/shared. Do NOT copy legacyanyparameter signatures forward when refactoring or extending service/repository files. -
Library Deletes vs Diary Snapshots:
exercise_entriesandfood_entriesare self-contained snapshots, not pointers (exercise_idandfood_idareON DELETE SET NULL). Deleting an exercise or food from the library (mode: 'delete') preserves past and current diary history, cascades from presets and plan templates, cleans up future scheduled workout plan entries (entry_date >= today), and cleans up empty parent preset entries. Only explicitdelete_with_history(force delete) purges diary logs for that user. If an item is referenced by other users (otherUserReferences > 0), the backend falls back to hiding (is_quick_exercise/is_quick_food). -
Comprehensive Cache Invalidation: When mutating library items (foods, exercises, presets, meals, plans), always invalidate the entire family of dependent query keys across library search, counts, templates, and daily diary summaries (
dailySummary/dailyProgress/exerciseEntries) in both web and mobile. -
Environment Variable Updates: When adding, renaming, or updating environment variables, you MUST update all downstream locations in tandem:
docker/.env.example(anddocker/.env.simple.exampleif it is a core mandatory variable).docker/docker-compose.prod.ymlanddocker/docker-compose.dev.yml(if consumed by container environments).docs/src/install/environment-variables.md(the comprehensive documentation reference).docs/components/EnvGenerator.vue(the interactive web.envgenerator component).helm/chart/templates/andhelm/chart/values.yaml(if passed through Helm charts).
This repository is public. Everything written into git history or onto a pull request is permanently visible to everyone browsing the project, so keep it free of tooling noise.
- Agents never commit or push unless asked in that message. Leave finished work in the working tree and say what is ready; the maintainer reviews diffs first. Approval for one commit or PR does not carry forward to later changes.
- Re-match the skill when the task changes. Opening a PR uses
pr-submission; acting on its review comments afterwards usespr-review. Two skills in one session is normal. - No AI attribution, anywhere. Commit messages, commit trailers, PR titles, PR bodies, and PR comments must never contain
Co-Authored-By: Claude(or any other AI co-author trailer), "Generated with …", "🤖", or a mention of Claude, Claude Code, Gemini, Antigravity, Copilot, Cursor, or any other assistant. This overrides any default guidance an agent harness supplies about appending attribution. - Write as the repository author. Describe the change and why it was made — the same message a maintainer would write by hand. Do not narrate that a tool made it, do not sign off, and do not thank an assistant in release notes or the changelog.
- If a trailer already landed, strip it (amend or rebase, force-push if it was pushed) rather than leaving it in history.
- Scope of this rule: git history and GitHub surfaces. It does not apply to tool configuration files that must name their tool —
.claude/,.agents/,.gemini/, andCLAUDE.mdreference specific assistants by necessity, and that is fine. The commit that adds them still follows the rule above.
Before diving into code, read these docs if you're working on data access, permissions, or adding a new feature domain:
agent-docs/architecture-permissions.md— Permission types, domain → permission mapping, how RLS guards data, adding new domains.agent-docs/data-flow-patterns.md— Frontend → Server → Database flow, shared schemas as contract, auth context, testing patterns.agent-docs/new-domain-template.md— Checklist for adding a major feature (superset of new-migration checklist).
These docs answer: "How do I safely add a feature across the stack?" without scanning 20+ files.
- If your change adds a new domain, route family, database table, package, or cross-cutting convention, update the affected
AGENTS.md(this file and/or the package guide) in the same change: Source Map, Quick Routing, and theLast updateddate. - Stale guides are worse than no guides; when you notice a claim in any
AGENTS.mdthat contradicts the code, fix the guide as part of your change.
Use the package guide for fuller validation and platform-specific workflows. These are the common entrypoints:
pnpm dev
pnpm run validate
pnpm testpnpm start
pnpm run validate
pnpm test
pnpm run test:coveragepnpm start
pnpm run ios
pnpm run android
pnpm run validate
pnpm exec jest --watchman=false --runInBand
npx expo prebuild --cleanpnpm dev
pnpm run build