Skip to content

LynCareOS — Architecture

Version: 3.62
Last Updated: 2026-08-06 13:33:14


LynCareOS is a multi-tenant family support care platform — not a medical app. One deployment serves many independent subscriber accounts (“tenants”). Tenant-owned data carries tenant_id; API handlers enforce isolation in application code and PostgreSQL Row-Level Security provides defence-in-depth. A super-admin may act on behalf of any tenant using the X-Tenant-ID header. Carers and observers are restricted to patients via patient_access; tenant admins may manage all patients in their account. Regulatory posture: 26-REGULATORY-APPLICABILITY-AND-CONTROL-MAP.md.

This document describes two states of the architecture:

  • Current state — a single-region deployment: React PWA → FastAPI → PostgreSQL, with Redis for cache and coordination (not scan durability). Eleven HTTP module surfaces cover the shipped care domains; additional clinical schema exists ahead of matching APIs. Cross-cutting concerns today include in-app care alerts (no Web Push), platform identity encryption with per-tenant DEK provisioning for future column encryption, PostgreSQL-backed async prescription scanning, and hybrid analytics (materialized aggregates plus live timelines where needed). English-only UI. API contracts: OpenAPI export + generated api.types.ts are in the quality gate (REQ-PLAT-10 / B1). High-traffic clinical routes use response_model=; remaining hand-written interfaces in lib/api.ts are documented as pending migration (see Type system and API contracts). Layering: every router is SQL-free; services are HTTP-free except services/http_errors.py (ADR 0001 AuditContext).
  • Target state — evolution required by 02-REQUIREMENTS.md: broad module coverage, i18n, Capacitor native clients with optional native push and health-data bridges, and full contract adoption (all public responses typed in OpenAPI; UI imports generated schemas only).

Where a section describes something not yet built, it is marked [Target]. Where a section describes what is already implemented, it is unmarked or marked [Current]. Capability-level current → target contrast is in Architecture evolution. Implementation inventory (migration IDs, sprint B-items, file paths) lives in 04-ROADMAP, 03-SOLUTION-DESIGN.md, and operations guides — not duplicated here. ADRs: adr/00-INDEX.md.

See Multi-tenancy, accounts, and patient access and the access control audit for authoritative isolation rules.


This section compares architectural postures (how the system is shaped and what it optimizes for). It does not track sprint completion, migration numbers, or per-file layering — see 04-ROADMAP §2 — Platform & engineering and 03-SOLUTION-DESIGN.md for that ledger.

LayerPosture
DeliveryOne FastAPI application serves a React PWA (browser install). No App Store native shell yet.
Domain coverageEleven HTTP module surfaces for shipped care workflows (coordination, medication, observations, help board, condition templates, and related areas). Additional clinical tables exist without matching APIs yet.
AwarenessCare alerts are durable in PostgreSQL and consumed in-app by the care team (bell + icon badge where the platform supports it). Web Push was retired in favour of this model.
ContractsPipeline shipped; adoption partial (audit 2026-07-31): committed openapi/openapi.json + api.types.ts, drift gate. 36 route decorators use response_model= across 10 files, covering 14% of /api operations. Remaining hand-written interfaces in lib/api.ts are documented and unverified against the schema — prefer api.contracts.ts aliases for new work.
Localeen-AU default; fr-FR enabled for app QA (react-i18next).
PersistencePostgreSQL is system of record; Redis supports cache, rate limits, and pub/sub — not prescription-scan durability.
SecurityTenant isolation in app code plus RLS. Identity PHI encrypted at rest with platform keys and blind-index lookups; per-tenant DEKs provisioned for a future column-encryption tranche. MFA uses a separate crypto envelope.
AnalyticsDashboard aggregates prefer a refreshed materialized view; some timelines still read live transactional rows.
Async workPrescription scanning is a database-queued pipeline (claim, worker, notify/stream) rather than holding API connections during vision inference.
Code structureRouter → Service → Repository complete (2026-07-17): 0 SQL execute sites in routers/. Services are HTTP-free except http_errors.py; clinical mutations take AuditContext (ADR 0001). Quality gates: scripts/run-quality-gates.ps1.

External - Current

Care alerts - Current

Data - Current

Backend - Current

Client - Current

HTTPS api

React 19 SPA

delivered as PWA

(browser install only)

FastAPI

11 active module routers

uvicorn :8020, workers=2

PostgreSQL 16

system of record

Redis 7

SSE , cache , rate limits , pub/sub

(scan queue now PG-native)

PostgreSQL care_alerts

in-app bell + icon badge

Cloudflare Tunnel

app.lyncareos.com

Stripe

billing

LM Studio

Qwen2.5-VL

prescription scan

The target architecture adds four major capability layers on top of the current foundation without replacing it. Each layer is independently deliverable.

External

Health Data - Target

i18n - Target

Native push - Target

Data - Target

Backend - Target

Client Layer

APNs [Target]

FCM [Target]

read [Target]

read [Target]

React 19 SPA / PWA

(current)

Capacitor Native App

iOS App Store + Google Play

[Target - §7.36]

FastAPI

30+ module routers

[11 current + 20+ Target]

PostgreSQL 16

88 applied + 20+ new domain tables

[V083-V088 schema-complete]

Redis 7

+ optional native device tokens

[Target - Capacitor]

APNs

iOS native mirror of care_alerts

[Target - Capacitor]

FCM

Android native mirror

[Target - Capacitor]

react-i18next

11 Wave-1 languages

+ RTL-ready layout

[Target - §7.35]

Apple HealthKit

[Target - post Capacitor]

Google Health Connect

[Target - post Capacitor]

Cloudflare Tunnel

Stripe

LM Studio

DimensionCurrentTarget
Client deliveryPWA (browser install)PWA + Capacitor free store clients (Play first, then App Store) + website Windows installer; website Stripe remains commerce SoT (consumption-only store binaries)
Care awarenessIn-app alerts + icon badge (Badging API)In-app alerts + optional native push (APNs/FCM) when Capacitor ships
Module coverage8 built modules8 built + 15 Future modules
UI languageEnglish only11 Wave-1 languages + RTL readiness (react-i18next)
Frontend type contractsB1 pipeline live (openapi.json, api.types.ts, CI drift gate); 66 Schema<> aliases in api.contracts.ts; 72 manual response interfaces in api.ts; alerts / care-tasks / calendar-actions fully response_model-backedEvery public route has response_model (or equivalent return type); UI imports wire types from api.contracts.ts only; api.ts is transport (fetch/auth/errors), not duplicate shapes
Health dataNot availableHealthKit / Health Connect read via Capacitor plugin
App Store presenceNone (direct web install only)Free Google Play + Apple App Store listings (Capacitor); paid features unlocked via website entitlements
CommerceStripe on webUnchanged Stripe SoT on web; store builds hide payment CTAs (REQ-NATIVE-08/10)
Distribution modelDirect (single region, AU operations host)Direct + country operator tier (operator_tenants)

Production runs on DigitalOcean Sydney VPS lyncareos-prod-syd1 with docker compose --env-file .env.production --profile production and repo-root docker-compose.yml. Public app URL: https://app.lyncareos.com via Cloudflare Tunnel on the VPS to http://127.0.0.1:8020. Details: 03%20-%20DEPLOYMENT%20AND%20PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md; day-2 ops: ../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md §12–§17.

app.lyncareos.com → Tunnel

lyncareos.com / www

outbound only

Cloudflare Edge

(proxied CNAMEs)

DigitalOcean VPS

lyncareos-prod-syd1

Docker Compose production profile

app , pgbouncer , postgres

redis , scan_worker

+ cloudflared → :8020

Cloudflare Pages

marketing + _worker.js

private-beta gate

Optional: LM Studio

(Qwen2.5-VL 7B)

Key points:

  • One Dockerfile (backend/Dockerfile) builds the app image; production hosts docker compose … build app on the VPS (or a future CI push).
  • Postgres data lives on a 50 GB block volume at /data/pg on the VPS.
  • Cloudflare Tunnel is outbound-only from the VPS; no inbound firewall holes are required for the app port if only the tunnel is used.
  • LM Studio is optional — see backend/services/lmstudio.py.
  • Marketing is Cloudflare Pages (lyncareos.com / www); the product API is the app service on the VPS. Private-beta gate: marketing/palliative/_worker.js reads Cloudflare Pages env PREVIEW_SECRET (workstation MARKETING_PREVIEW_SECRET in .env.production, synced by scripts/deploy-marketing-pages.ps1). Preview cookie stores an HMAC grant token — not the raw secret. Worker adds CSP and security headers on all responses.

Legacy: Workstation hosting was decommissioned 2026-05-20. docker-compose.prod.yml is a retired VM-era file; do not use it. Use docker-compose.yml + production profile.


Presentation tools and vitals UI patterns: see 14-FRONTEND-PRESENTATION-STACK.md (hybrid graphics, Motion, mobile capture sheet, component map).

What developers run on their machines to work on this repo:

AreaTechnologyNotes
Language (backend)Python 3.11+Match production: Docker image uses Python 3.12 (backend/Dockerfile).
API frameworkFastAPI 0.115.6App entry: backend/main.py. Async throughout; OpenAPI at /api/docs and /api/redoc.
ASGI server (local dev)Uvicorn with reloadStarted via backend/run_server.py — binds 127.0.0.1:8021 on Windows with reload=True.
DatabasePostgreSQL 16Started with Docker Compose (postgres service only for typical dev). Host port 5432.
DB driverpsycopg v3psycopg[binary,pool] — AsyncConnectionPool in backend/database.py.
Language (frontend)TypeScript ~5.9frontend/tsconfig + tsc -b in production build.
UIReact 19, Vite 8Dev server default port 5173 (VITE_PORT overrides).
StylingTailwind CSS 3.4, PostCSS, Autoprefixerfrontend/tailwind.config.js, frontend/src/index.css. Dark-mode via class strategy.
Design tokensCustom brand.* + lyn.* palettetailwind.config.js — sky-blue brand, slate-based panels. See 03-DESIGN-SYSTEM.md.
RoutingReact Router 7frontend/src/App.tsx.
ChartsApache ECharts 6echarts, echarts-for-react; theme helpers in frontend/src/lib/chartTheme.ts.
Date utilitiesdate-fns 4.xDate formatting, arithmetic, and locale helpers throughout the app.
Vision AI (prescription scanning)LM Studio — Qwen2.5-VL 7BLocal inference server. OpenAI-compatible API at LMSTUDIO_BASE_URL/v1/chat/completions with optional Authorization: Bearer via LMSTUDIO_API_KEY. Called server-side only from scan_worker / services/lmstudio.py; never exposed to the browser. Image sent as base64 content part. Timeout: 10 s connect / 120 s read / 30 s write. See 08-PRESCRIPTIONS-MODULE.md.
Auth (API)PyJWT (HS256, PyJWT[crypto]), bcryptAccess + refresh tokens; optional Google sign-in (google-auth on the server; client uses OAuth2 implicit redirect to /login + hash, or PWA handoff on iOS).
MFApyotp (TOTP), qrcode[pil]TOTP secrets encrypted at rest via Fernet (services/crypto.py, mfa:v1: prefix; MFA_ENCRYPTION_KEY or HKDF from SECRET_KEY).
PHI at restcryptography Fernet + HMAC blind indexIdentity fields in DB via services/field_crypto.py (phi:v1:); see Field-level PHI encryption (B4).
HTTP client (backend)httpx 0.27Used for LM Studio inference and external HTTP calls.
HTTP client (frontend)fetchCentralised in frontend/src/lib/api.ts (no React Query / TanStack Query in this repo).
Modal / list UXHeadless UI 2Dialog, Listbox in frontend/src/components/ui/Modal.tsx, Select.tsx.
IconsLucide React 1.x (primary), @heroicons/react 2.x (secondary)Navigation and UI icons.
UI motionmotion 12.xDiscrete state animations (motion/react); vitals sheet, colour knob, volume count-up. Respects prefers-reduced-motion via usePrefersReducedMotion. See 14-FRONTEND-PRESENTATION-STACK.md.
Pain / body-map UIbody-muscles, react-muscle-highlighterMuscle highlighter SVG for pain body-map page (PainTracking.tsx).
Image cropreact-advanced-cropper 0.20.xProfile photo and prescription image upload cropping.
Drag-and-drop@dnd-kit/core, @dnd-kit/sortable, @dnd-kit/utilitiesMedication schedule management (MedicationSchedule.tsx).
Background jobsAPScheduler 3.10 (AsyncIOScheduler) backed by SQLAlchemyJobStoreservices/scheduler.py — per-tenant 06:00 local timezone-aware jobs (shopping list reset, etc.). Jobs survive restarts; safe under multi-replica deploy.
CachingRedis (via redis==5.2.0 and services/redis_client.py)SSE tickets, rate limits, shopping pub/sub, hot-caches (modules, patients, medicines, catalog).
Rate limitingslowapi — Redis in production, memory:// in devmiddleware/rate_limit.py. Avoids ~2s Redis connect penalty per request when Redis is stopped locally. JWT signature hashed for bucket keys.
Care alertsPostgreSQL care_alerts + APScheduleralert_service, alert_scheduler, routers/alerts.py
Billingstripe==11.4.1Checkout sessions, webhooks, upgrade flows.
Cryptocryptography==44.0.0Fernet for MFA (crypto.py) and PHI (field_crypto.py); HKDF key derivation for both.
PWA / Service WorkerCustom sw.js (cache-first app shell, network-only API)frontend/public/sw.js; installable via manifest.json. See PWA and Mobile section.
Dark / light modeThemeContextThree states: light, dark, system. localStorage persistence; CSS class toggling on <html>.
Local orchestrationPowerShelldev-start.ps1 — Compose Postgres + backend + Vite; dev-stop.ps1 — stop. start.ps1 — unified launcher (production or -Dev for dev servers; reads PORT / DEV_PORT from backend/.env).
Tests (backend)pytest, pytest-asynciobackend/tests/ — auth, care, dispensings, prescriptions, medication schedule, auto-dispense, shopping, catalog admin, migration runner, LM Studio mocks, etc.; DB tests optional via TEST_DATABASE_URL.
Tests (frontend)Vitest, Playwrightfrontend/ — npm run test, npm run test:e2e.

Environment for local API and tools is loaded from backend/.env (python-dotenv in main.py; override=True so shell env does not silently override file). The frontend can use frontend/.env for VITE_* variables (for example VITE_GOOGLE_CLIENT_ID, VITE_API_URL, VITE_PORT).


Docker full-stack stack (Compose production profile)

Section titled “Docker full-stack stack (Compose production profile)”

The same container image (backend/Dockerfile) and Compose layout (app + postgres + volumes) are used for:

  1. UAT / rehearsal on a non-production machine — docker-compose.yml, profile production, volumes on that PC.
  2. Production — the same docker-compose.yml and profile on the operations host that serves https://app.lyncareos.com, with live lyncare_pg_data / lyncare_uploads.

Do not equate “I ran docker compose --profile production” with a harmless test: on the production host, that is the live database. See 00-INDEX.md — Terminology and 03%20-%20DEPLOYMENT%20AND%20PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md.

ServiceImage / buildRole
postgrespostgres:16-alpinePrimary data store. Env: POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB (defaults: lyncare / lyncare / lyncareos). Named volume lyncare_pg_data. Host port 5433 on loopback by default (POSTGRES_HOST_PORT). Healthcheck: pg_isready.
pgbounceredoburu/pgbouncer:latestConnection pooler; app and scan_worker use DATABASE_URL → pgbouncer:5432.
redisredis:7-alpineSSE tickets, rate limits, cache, shopping pub/sub (scan queue is Postgres-native).
appBuild: backend/Dockerfile (context: repository root)FastAPI + built React SPA (single origin). Profile: production only — see below.
scan_workerSame image as app; python -m workers.scan_workerPrescription image scan pipeline (Postgres scan_jobs queue + uploads volume). Profile: production.
VolumeUsed byPurpose
lyncare_pg_datapostgresAll relational data for this Compose stack’s Postgres. On a UAT machine it is throwaway or rehearsal data; on the production host it is authoritative. Backup (volume or pg_dump) before destructive operations.
lyncare_uploadsapp, scan_workerMounted at /app/uploads — prescription images, shopping/dispensing photos, scan staging (UPLOADS_DIR). New files are stored under /app/uploads/<tenant_id>/ (bare UUID filename in DB). No flat legacy path fallback at serve time — pre-tenant-layout files must be migrated with backend/scripts/migrate_uploads_to_tenant_dirs.py. Contact attachments: contact_attachments/<tenant_id>/. Must persist across container restarts; copy this volume when moving hosts (Postgres restore alone is not enough).
  • app uses env_file: backend/.env so local and containerised runs can share the same keys (secrets, LMSTUDIO_*, pool sizes, etc.).
  • Compose overrides ENVIRONMENT=production, DATABASE_URL=postgresql://…@postgres:5432/…, and UPLOADS_DIR=/app/uploads — these win over conflicting values in the file for the container runtime.
  • The image itself does not bake in .env; runtime env comes from Compose + env_file.

Multi-stage build:

  1. Stage build-frontend: node:22-alpine, npm ci, npm run build → static assets in /app/frontend/dist inside the build stage.
  2. Stage app: python:3.12-slim, installs libpq5, pip install -r requirements.txt, copies backend/ to /app, copies frontend build to ../frontend/dist relative to backend (i.e. /frontend/dist from filesystem root inside the image).

Runtime:

  • CMD: python -m uvicorn main:app --host 0.0.0.0 --port 8020 --workers 2
  • Port: 8020 exposed to the host (8020:8020).
  • Workers: 2 uvicorn workers — suitable for moderate load; scale via replicas/orchestrator if needed.
  • Static files: main.py mounts /assets (and /icons if present) from frontend/dist and uses an SPA fallback so client routes resolve to index.html.

Starting the Compose production profile (local UAT or rehearsal)

Section titled “Starting the Compose production profile (local UAT or rehearsal)”

The app service is under profiles: [production], so docker compose up -d starts only Postgres (typical dev: DB in Docker, API on host). Full stack on a workstation:

Terminal window
docker compose --profile production up -d --build

The app is then on host port 8020 with /api/... and the SPA on the same origin (no Vite proxy). If this is a UAT machine, data is non-authoritative; if it is the production host, this is the live stack (doc 07 §13).

Compose exposes HTTP on :8020. For internet-facing deployments, place HTTPS in front (reverse proxy, load balancer, or Cloudflare Tunnel). Operational steps and tunnel notes: [../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md](../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md). ALLOWED_ORIGINS must list the browser-visible origin(s) (scheme + host + port).

Outbound dependencies (containerised app — local UAT or cloud)

Section titled “Outbound dependencies (containerised app — local UAT or cloud)”
DependencyRole
PostgreSQLRequired — same Compose service or external DSN via DATABASE_URL.
RedisRequired — rate limits, SSE tickets, pub/sub, caches.
StripeRequired for billing — webhook endpoint registration, Checkout session creation.
LM Studio (optional)Prescription scan only — if unset/unreachable, scan fails; other routes work. Configure LMSTUDIO_* in backend/.env.

⚠️ Development vs local UAT vs cloud production database (read this once)

Section titled “⚠️ Development vs local UAT vs cloud production database (read this once)”

Local UAT (Compose profile production on a PC): The app container uses DATABASE_URL → hostname postgres on the Docker network. Data lives in lyncare_pg_data. lyncare_uploads holds uploads. Never run docker compose down -v without a verified backup if this volume matters.

Production (operations host): Same pattern (app + Postgres + Redis + PgBouncer in Compose), .env.production, and Cloudflare Tunnel to localhost:8020. See 00-INDEX.md — Terminology and doc 20.

Typical local dev: Postgres in Compose or native Windows; backend on 8021 → lyncareos_dev. Windows caveat: native Postgres vs Docker often fight for 5432; many setups use 5433:5432 for Docker — align DATABASE_URL.

Inspecting DB when Postgres is in Docker (local UAT): docker compose exec postgres psql -U lyncare -d lyncareos.

┌─ Development (local, typical) ────────────────────────────────────────────┐
│ Browser → http://localhost:5173 (Vite HMR) │
│ │ /api/* → FastAPI :8021 (host process) │
│ ▼ │
│ FastAPI ──→ lyncareos_dev (native or Compose postgres) │
└────────────────────────────────────────────────────────────────────────────┘
┌─ Local UAT (Compose profile `production` on THIS machine) ─────────────────┐
│ Browser → http://localhost:8020 — app + postgres containers │
│ Volume lyncare_pg_data on the PC — NOT cloud production │
└────────────────────────────────────────────────────────────────────────────┘
┌─ Production (operations host — live subscribers) ──────────────────────────┐
│ Browser → https://app.lyncareos.com — see doc 07 §12, doc 20 │
└────────────────────────────────────────────────────────────────────────────┘
scan_worker ──▶ HTTP LMSTUDIO_BASE_URL
(default http://192.168.7.104:1234)
POST /v1/chat/completions
Authorization: Bearer LMSTUDIO_API_KEY (when set)
Model: qwen/qwen2.5-vl-7b
Timeouts: connect 10 s / read 120 s / write 30 s
(prescription scanning only — all other routes unaffected)
  • LM Studio is an outbound dependency of scan_worker only (not the browser). If unreachable or returns 401 without a token, the SSE stream ends with a structured error; all other API routes are unaffected.
  • Called server-side only — never exposed to the browser.
  • Scan jobs are enqueued in PostgreSQL (scan_jobs); scan_worker claims rows, calls LM Studio, and publishes results via pg_notify to SSE subscribers (services/scan_queue_pg.py / scan_queue.py facade) so the browser never holds an open HTTP connection during model inference.
Browser → http://localhost:5173 (Vite)
│ /api/* proxied to VITE_API_URL or http://localhost:8021
▼
FastAPI (run_server.py :8021)
│
├──▶ TCP localhost:5432
│ Native Windows PostgreSQL (dev database)
│
├──▶ TCP localhost:6379
│ Redis (Docker or native)
│
└──▶ HTTP LMSTUDIO_BASE_URL (default http://192.168.7.104:1234)
LM Studio — Qwen2.5-VL 7B
  • Vite proxy is configured in frontend/vite.config.ts (/api → backend).
  • Default proxy target is 8021 to match run_server.py and dev-start.ps1.
  • cookieDomainRewrite on the proxy ensures the lyncare_refresh HttpOnly cookie round-trips correctly through Vite in dev.

Docker Compose production profile — request path (detail)

Section titled “Docker Compose production profile — request path (detail)”
Browser → http://host:8020
│ same origin: /api/* + static /
▼
uvicorn (:8020, workers=2)
│
├──▶ TCP pgbouncer:5432 (Docker internal) → postgres:5432
│ PostgreSQL (lyncare_pg_data volume — PRODUCTION data)
│
└──▶ TCP redis:6379 (Docker internal)
Redis — caches, rate limits, SSE, notifications

On startup (main.py lifespan):

  1. open_pool() — opens the primary psycopg AsyncConnectionPool and, if DATABASE_READ_URL is set, the read-replica pool.
  2. init_db() — on a greenfield database (no public.tenants), applies backend/schema/lyncareos_v1_baseline.sql once, then runs the migration runner (migrations/runner.py), then ensures UPLOADS_DIR exists and applies backend/schema.sql (idempotent CREATE TABLE IF NOT EXISTS / indexes). On brownfield hosts (existing dev/VPS), baseline is skipped; only pending active migrations run, then schema.sql. Migrations-before-schema prevents startup failure when schema.sql references columns added only in a pending migration (e.g. audit_log.patient_id from V099). The runner holds an advisory lock so concurrent replicas cannot clash on rolling deploys.
  3. Stripe price-map seed — reads STRIPE_PRICE_MAP env and populates the stripe_prices mapping (non-fatal).
  4. APScheduler start — services/scheduler.py, AsyncIOScheduler backed by SQLAlchemyJobStore (PostgreSQL). Per-tenant 06:00 local-timezone triggers (e.g. recurring shopping list reset via services/shopping_service.py). Jobs survive restarts.
  5. SSE ticket cleanup task (no-op — Redis TTL + GETDEL handles eviction). Task kept for compatibility.
  6. Yield → serve requests.
  7. Shutdown: cancel cleanup task → scheduler shutdown → close Redis → close_pool().

Migration files are named VNNN__description.sql in backend/migrations/ (not subdirectories). Pre-v1 history (V001–V114 incremental files) is archived under backend/migrations/archive/pre-v1/ and is not executed by the runner. The runner records applied versions in schema_migrations and applies only pending active files in numeric order. On a database where all active migrations have been applied, the runner is a no-op. Additive schema evolution after v1 uses new active migration files (V002__… onward), not only editing schema.sql. Schema is PostgreSQL-only.

Active repo migration (2026-06-04): V001__lyncareos_v1_baseline.sql — no-op marker; full DDL for greenfield is in backend/schema/lyncareos_v1_baseline.sql. Dev (lyncareos_dev): schema_migrations through V016__patient_appointments_oncology_type (V011–V012 Care Module + marketing; V013 PRN medical descriptions; V014 patient-scoped reason codes; V015 per-patient hub JSONB; V016 optional patient_appointments.appointment_type for Cancer calendar sync). VPS production: through V010 until next deploy ships V011–V016. VPS image deploy-20260604-1821 (Care Start); pending migrations on prod apply. Apply dev: .\migrate.ps1 -Target Dev or cd backend; $env:DATABASE_URL=…/lyncareos_dev; python -m migrations.runner (11-DATABASE-SAFETY §2i–§2n). Rollback: 24 §6.5. Forward changes: add V017__… onward after V016. Verify with .\migration-audit.ps1 -Target Dev|Vps -NonInteractive — ORPHAN must be zero.

Middleware stack (outermost → innermost)

Section titled “Middleware stack (outermost → innermost)”
  1. SlowAPIMiddleware — Redis-backed rate limiter (JWT-signature-keyed buckets).
  2. SecurityHeadersMiddleware — X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(). HSTS added in production only. Content-Security-Policy on all API/SPA responses (default-src 'self'; frame-ancestors 'none'; Stripe connect-src where needed).
  3. CORSMiddleware — ALLOWED_ORIGINS from config; allow_credentials=True; allowed header X-Tenant-ID; exposed header X-Tenant-ID.

Production config fail-fast (2026-06-25): When ENVIRONMENT=production, startup requires explicit PHI_ENCRYPTION_KEY, PHI_BLIND_INDEX_KEY, and LMSTUDIO_BASE_URL. Development may omit PHI keys (HKDF fallback from SECRET_KEY); LMSTUDIO_BASE_URL defaults to http://127.0.0.1:1234 — no hardcoded LAN IP in config.py.

  • API prefixes (all JSON unless noted): routers use paths under /api/...:
Router filePath prefix(es)Module gate
auth.py/api/auth/*Public (login/register/refresh); authed for logout/MFA/change-password
users.py/api/users/*require_tenant_member / admin / super-admin
invitations.py/api/invitations/* (incl. POST /{id}/shared to record delivery channel)require_tenant_admin; verify is public/token-scoped
tenants.py/api/tenants/*require_tenant_member / admin / super-admin
subscriptions.py/api/subscriptions/*, /api/admin/subscriptions, GET /api/modules/available (public, 60/min IP rate limit)require_tenant_member (read), admin (write); /api/modules/available unauthenticated
reason_types.py/api/reason-types?patient_id= (required), CRUDmedication_dispensing
dispensings.py/api/dispensings/*medication_dispensing
analytics.py/api/analytics/*medication_dispensing — includes reason_pattern on /by-reason and GET /care-module-events for board sparklines
audit.py/api/audit/*medication_dispensing (admin-only)
medication_groups.py/api/patients/{id}/medication-groups/*, /api/patients/{id}/dispense-view, batch/dispense endpointsmedication_dispensing
patients.py/api/patients/*care_calendar
care_shifts.py/api/care-groups/*, /api/care-shifts/*, /api/care-tasks/*care_calendar
patient_appointments.py/api/patients/{id}/appointments/*care_calendar — optional appointment_type (oncology preset) on create/PATCH
scripts.py/api/patients/{id}/scripts/* (scan, alerts, medicine-summary, fills, image)prescription_management
sleep.py/api/patients/{id}/sleepsleep_tracking
vitals.py/api/patients/{id}/vitals/*vitals_tracking
pain.py/api/patients/{id}/pain/*pain_tracking
mind.py/api/patients/{id}/mind/*pain_tracking
pain_settings.py/api/pain-settings/*Auth-only — no module gate (settings viewable without subscription)
shopping.py/api/patients/{id}/shopping/*, catalog consumer routesshopping
key_contacts.py/api/patients/{id}/contacts/*key_contacts
admin_shopping.py/api/admin/shopping/*require_super_admin / require_tenant_admin — no module gate
pwa_auth.py/api/pwa-auth/*Unauthenticated + rate limits; opaque session_id credential
stripe.py/api/stripe/*Mix: /webhook public; signup/upgrade authed
billing.py/api/billing/*Public (tiers, FX for marketing) + authed (tenant billing context)
onboarding.py/api/onboarding/*require_tenant_member / admin
alerts.py/api/alerts/*, /api/admin/alert-settingsrequire_tenant_member / admin
dev_tools.py/api/dev/*Non-production only
care_modules/routers/status.py/api/care-modules/statusCARE_MODULE_BOARDS_ENABLED + preview user (404 when off)
care_modules/routers/board.py/api/patients/{id}/care-modules/board, …/events, …/sessions/complete, PATCH …/settings, GET …/visit-prep, GET …/dashboard-chips, GET …/comfort-checkin (+ /dates, /spoke-averages, /week-series)Same gate + require_patient_access

SPA routes (not in table above): /care/cancer-at-home, /care/cancer-at-home/visit-prep, /care/breathing — registered only when VITE_CARE_MODULE_BOARDS=true; gated by preview user, server flag, and care_profile_slug. See Care Module plugins.

Consult OpenAPI at /api/docs for the authoritative list.

require_module(slug) checks subscriptions for active or trial status and returns HTTP 402 when the tenant lacks an active entitlement.

Care Profile interactive boards (/care/cancer-at-home, /care/breathing) are not subscription modules in tiers.json. They are optional product plugins gated independently so the base app can ship without hub UI.

Cancer Board V2 (2026-06-10, Care Profile Capability Platform proof point): Full hub on /care/cancer-at-home — context-first, action-led layout (header: patient name + Home · title + Where cancer is pill → CancerTodayContextPanel — cc-card composing CancerDayPicker + CancerModeToggle (Actions for today / Your treatment only; no Comfort mode toggle in UI); PATCH …/settings on tap + scroll to plan → CancerStatusSummary (2026-07-31: Mon–Sun spoke week narrative from GET …/comfort-checkin/week-series + comfortWeekInsightNarrative.ts (1–7 days; spoke-specific when-to-call copy; hub fallback only if no daily status in the week)) → CancerTodayPlan (Today’s care plan, subtitle from buildPlanSubtitle(), steps from buildTodayPlan() — day-type blocks and treatment-mode add-ons only (2026-07-31: daily status and breakthrough review are not numbered plan cards; use InlineComfortCheckIn and Watch closely / hub tiles); gentle/palliative comfort-first path when gentle_mode set in settings) → optional comfort override + site tip → CancerComfortDateStrip → Daily status via InlineComfortCheckIn → Other cancer tasks today → Watch closely (#cancer-watch-closely) → Activated across LynCareOS → Clinic and handover). /calendar — CalendarFocusDayPanel with writable calendar_actions pills for the focus date; module tasks show manifest task_prompt plus response_kind button sets (yes/no, medication, arrangement, …) persisted on care_tasks (V027) via PATCH /api/care-tasks/{id} { "response_code" }; the month grid marks days with applied actions using manifest icon keys from GET …/care-modules/calendar-actions/range — up to five per-action icons on desktop (lg+); phone and tablet show one module icon via careModuleDayIconsForViewport() (see 15-CARE-CALENDAR-COMPOSITION.md). V2 sections derived in-browser via cancerBoardV2Model.ts (no new board APIs). Home: CareBoardDashboardPanel + GET …/dashboard-panel. CareFlowRail retained, not mounted. Breathing remains Phase A shell.

GateConfigDefault (production)
ServerCARE_MODULE_BOARDS_ENABLED in backend/config.pyfalse
Preview usersCARE_MODULE_PREVIEW_USER_IDS (comma-separated)1
Frontend buildVITE_CARE_MODULE_BOARDS=true in frontend/.envomitted / false
Runtime (per user)GET /api/subscriptions/active → feature_flags.care_module_boardsdeploy on and user in preview list

When disabled: no care-board routes in the SPA bundle (build flag); board APIs return 404; families use existing routes (/log, /calendar, /observations, Care Start apply on admin).

When enabled for a preview user: lazy-loaded frontend/src/care-modules/*; useCareModuleFlags() reads feature_flags.care_module_boards from ModuleContext (single GET /api/subscriptions/active). Requires both build and server flags. Board visible only when activePatient.care_profile_slug matches (cancer_at_home | breathing_difficulties). Platform super-admin still calls /subscriptions/active for feature_flags (all subscription modules granted, but care boards are not forced off).

Capture wizards: CaptureSession → CareCaptureOverlay for pathway bundles (fever, infusion ack, tablet safety). Daily status is inline on the hub page (InlineComfortCheckIn + 8-spoke ECharts radar) — not an overlay. Each spoke tap POSTs a capture step; session_completed when all eight spokes are saved (automatic — no Save button). GET …/comfort-checkin for the board merges latest value per spoke across all capture_instance_id values on the selected care_date (retrospective partial edits keep the full spider). Overlay: portal to document.body, z-[1100], opaque bg-canvas; phone full-screen / tablet ~85vw / desktop ~50% main column. Layouts: wizard or stacked (legacy overlay path; still in manifest). Widgets: traffic_light_3, emoji_face_5, segmented_bar (SegmentedBar.tsx — fallback / overlay); inline radar maps manifest steps to 1–4 per spoke via tap on chart. Pass layout={sessionDef?.layout} into CaptureSession when opening non-inline sessions from tiles.

Commerce unchanged: pack unlock + Care Start seed still flow through condition_packs / care_start routers. Boards are Layer 2 UX on top.

Spec: 29-CARE-MODULE-UI-ARCHITECTURE.md · 30-CARE-MODULE-PLUGIN-ARCHITECTURE.md · 31-CANCER-AT-HOME-SUPPORT-FLOW-UX.md · support-flow mockup

Backend:

PathRole
backend/care_modules/flags.pyDeploy + preview user gate
backend/care_modules/routers/status.pyGET /api/care-modules/status
backend/care_modules/routers/board.pyBoard state, capture events, settings patch, visit prep, dashboard chips, dashboard-panel, comfort-checkin date/average/snapshot
backend/care_modules/services/cancer_hub_service.pyHub aggregate (build_hub_state), calendar day sync, breakthrough log route, site tips, comfort override, _primary_cta(), _visible_tiles(), visit prep, dashboard chips; breakthrough/check-in 7d trends
backend/care_modules/services/dashboard_panel_service.pyHome Care board panel — status chips + actions_for_today + treatment_modes icon rows
backend/care_modules/services/comfort_checkin_service.pyDate-scoped comfort snapshots (merged latest per spoke across instances when capture_instance_id omitted), calendar dates with check-ins, rolling spoke averages (30→2 day fallback); get_comfort_checkin_week_series (Mon–Sun levels per anchor date)
backend/care_modules/visit_prep_narrative.pyAbbreviated story.lines builder for oncology visit prep (CANC-H01)
backend/care_modules/services/board_service.pyManifest + zone + hub payload for cancer_at_home
backend/care_modules/services/calendar_actions_service.pyManifest calendar_actions: apply/undo date-scoped tasks, range read, audit on apply/undo
backend/care_modules/calendar_task_manifest.pyNormalizes manifest tasks[] (object or legacy string) → id, title, prompt, response_kind
backend/care_modules/calendar_task_responses.pyAllowed response_kind → option codes; validates PATCH response_code
backend/care_modules/routers/calendar_actions.pyGated calendar action endpoints (require_care_module_access)
backend/repositories/care_tasks.pyDate-scoped care_tasks SQL (V026 apply; V027 response columns on read/write)
backend/care_modules/manifest_loader.pyLoads manifests/{slug}.json; mtime-keyed lru_cache so manifest edits apply without API restart
backend/care_modules/cancer_board_visual.pyTile/mode/day icon keys, enrich_tiles(), telemetry + breakthrough sparkline on hub tiles
backend/care_modules/cancer_defaults.pyDay types, treatment modes, checklist defs, PRIMARY_SITE_TIPS, ONCOLOGY_APPOINTMENT_TYPES
backend/repositories/care_module_settings.pycare_module_patient_settings CRUD
backend/care_modules/manifests/*.jsonPack UI manifest + capture_sessions per slug
backend/migrations/V011__care_module_events.sqlEvent log table
backend/migrations/V012__cancer_at_home_marketing_copy.sqlcondition_packs.description + feature_bullets for cancer_at_home
backend/migrations/V015__care_module_patient_settings.sqlPer-patient hub JSONB (today_day_type, checklists, visit prep questions, visit_prep_discussed)
backend/migrations/V016__patient_appointments_oncology_type.sqlOptional appointment_type on patient_appointments (IV infusion, labs, clinic review, …)
backend/migrations/V026__care_tasks_date_scoped.sqlDate-scoped module tasks; RLS on care_tasks; idempotent apply index
backend/migrations/V027__care_task_module_responses.sqlStructured module task answers: task_prompt, response_kind, response_code, recorded at/by

Subscriptions commerce (pack card): condition_packs.feature_bullets (JSONB, seeded in V012 for Cancer) drives marketing highlights on ConditionPackCard and the “What you get” section in ConditionPackPreviewDialog; other slugs still use seed-inventory preview until similar copy ships.

Pack list pricing (GET /api/condition-packs): condition_packs_service.list_packs_with_access() resolves one AUD→billing-currency rate via stripe_service.aud_minor_units_per_aud() (Redis key fx:pack:aud:{currency}, 12h TTL) and applies it to all paid packs — not one Frankfurter HTTP call per pack. Checkout still uses convert_pack_price_aud() per session.

Frontend:

PathRole
frontend/src/care-modules/cancer/CareBoardPage.tsx, cancer/cancerBoardV2Model.ts, cancer/comfortWeekInsightNarrative.ts, cancer/cancerCareFlow.ts, cancer/cancerRadarConfig.ts, cancer/radarTapGeometry.ts, cancer/VisitPrepPage.tsx, cancer/components/* (CancerTodayContextPanel, CancerTodayPlan, CancerStatusSummary, CancerDayPicker, CancerModeToggle, InlineComfortCheckIn, CancerComfortDateStrip, CancerComfortRadar, CancerComfortRadarChart, BecauseLine, NextStepFork, CollapsibleSection, CancerPrimarySitePicker; CareFlowRail retained, not mounted)
frontend/src/lib/radarHealth.tsShared red→green health gradient for comfort radar web and dots
frontend/src/components/dashboard/CareBoardDashboardPanel.tsxHome Care board card — dashboard-panel API; CareProfileIconStrip (540px layout)
frontend/src/pages/calendar/CalendarFocusDayPanel.tsxFocus-date calendar_actions + module task response buttons (CAL_LIST_ROW styling)
frontend/src/lib/calendarModuleTaskResponses.tsFrontend mirror of calendar_task_responses.py option sets
frontend/src/components/calendar/ModuleTaskResponseButtons.tsxTappable answers per module task row
frontend/src/components/dashboard/CareActionsForTodayBlock.tsxDeleted 2026-07-31 — replaced by calendar focus-day panel
frontend/src/components/dashboard/CancerTodayStrip.tsxLegacy status chips (superseded on Home by CareBoardDashboardPanel when boards on)
frontend/src/components/care-capture/CareCaptureOverlay (shared portal shell), CaptureSession, TrafficLight3, SegmentedBar
frontend/src/context/ModuleContext.tsxGET /api/subscriptions/active — modules + feature_flags.care_module_boards
frontend/src/context/CareModuleFlagsContext.tsxuseCareModuleFlags() hook (reads ModuleContext; no separate provider)

The table below lists all planned module slugs. Built modules have a live router and migration-backed tables. Future modules are specified in 02-REQUIREMENTS.md §7.15–§7.34 and are placeholders for the subscription provisioning model — their routers and tables do not yet exist.

Module slugStatusGated features
medication_dispensingBuiltMedicines, reason types, dispensings, analytics, audit, medication schedule (auto-dispense)
care_calendarBuiltPatients, care shifts (groups, shifts, tasks), patient appointments
prescription_managementBuiltPatient scripts, fills, scan, images, alerts — routers/scripts.py
sleep_trackingBuiltSleep pattern API — routers/sleep.py
vitals_trackingBuiltVitals (BP, SpO2, weight, temp, etc.) — routers/vitals.py
pain_trackingBuiltBody-map pain, mind tracking — routers/pain.py, routers/mind.py
shoppingBuiltPatient shopping lists + catalog consumer API — routers/shopping.py
key_contactsBuiltPatient key contacts — routers/key_contacts.py (Family and Complete)
care_observationsFutureStructured shift observation records and body-map skin integrity — routers/care_observations.py
therapy_recordsFuturePhysiotherapy, occupational therapy, and speech therapy sessions — routers/therapy_records.py
equipment_managementFutureEquipment register, servicing schedule, loan tracking — routers/equipment.py
goals_of_careFutureGoals of care, advance care planning, escalation directives — routers/goals_of_care.py
clinical_episodesFutureHospital admissions, crisis episodes, infections — routers/clinical_episodes.py
caregiver_wellbeingFutureCarer stress, fatigue, burnout logs — routers/caregiver_wellbeing.py
patient_voiceFuturePatient self-report: mood, comfort, preferences — routers/patient_voice.py
care_intelligenceFutureAI-generated care summaries and longitudinal trend insights — routers/care_intelligence.py
respiratory_oxygenFutureSpO₂ trends, oxygen therapy orders, exacerbation events — routers/respiratory.py
behaviour_trackingFutureBehavioural events with triggers, severity, and intervention outcomes — routers/behaviour.py
care_protocolsFutureCrisis plans, breathlessness plans, exacerbation protocols — routers/care_protocols.py
observational_painFutureNon-verbal pain assessment scales (Abbey, PAINAD) — routers/observational_pain.py
swallowing_safetyFutureSwallowing assessments, texture/fluid grades, aspiration risk — routers/swallowing.py
falls_trackingFutureFalls events with context, injury grading, intervention records — routers/falls.py
cognitive_trackingFutureCognitive assessments (MMSE/MoCA), orientation, delirium screening — routers/cognitive.py
family_journalFutureFamily-authored journal entries, milestones, memory capture — routers/family_journal.py
preventive_careFutureVaccination records, screening schedules, preventive appointments — routers/preventive_care.py
frailty_trackingFutureFrailty assessments (CFS/PRISMA-7), nutritional screening — routers/frailty.py

pain_settings is mounted without a module gate — tenant settings for the pain feature set are viewable regardless of subscription.

When a Future module router is built, it must:

  1. Be added to database.py MODULES tuple alongside the slug.
  2. Use require_module(slug) as a Depends on every endpoint.
  3. Have a dedicated migration file VNNN__<slug>_tables.sql for its schema.
  4. Be added to the router inventory table in the HTTP surface section.
  5. Be reflected in the access control audit on the next review cycle.

Request path (typical authenticated route)

Section titled “Request path (typical authenticated route)”

Write path (mutations, transactional reads):

HTTP request
→ SlowAPI rate-limit check (Redis)
→ SecurityHeadersMiddleware
→ CORS check
→ FastAPI route
→ Depends(get_current_user) — JWT decode + user row (one get_db slot; cached per request)
→ Depends(resolve_tenant_id) — tenant id from JWT (no pool slot on normal login path)
→ Depends(require_tenant_member) — membership + RLS on same get_db connection
→ Depends(require_module / require_tenant_admin / require_patient_access) as applicable
→ Handler — service/repo call (routers contain no SQL)
→ On exception: get_db rolls back transaction

Read path (analytics, audit list, onboarding progress — get_ro_db / get_ro_db_with_rls):

HTTP request
→ … same middleware …
→ Depends(get_current_user)
→ Depends(resolve_tenant_id)
→ Depends(require_tenant_member_read) — membership + RLS on one get_ro_db connection
→ Depends(get_ro_db_with_rls) — returns the same cached RO connection (not a second slot)
→ Handler — SELECT only

Rule (2026-05-30): Never stack Depends(require_tenant_member) (write pool) with Depends(get_ro_db_with_rls) on the same handler — that held two pool connections per request and exhausted DB_POOL_MAX under parallel Dashboard loads (30 s PoolTimeout per queued call). Use require_tenant_member_read for ctx on read-only routes.

Layer boundaries (Router → Service → Repository)

Section titled “Layer boundaries (Router → Service → Repository)”

Enforced in .cursor/rules/rules.mdc and by the D6 CI gate (backend/scripts/check_router_sql.py). All router endpoints delegate SQL to services or repositories; baseline is {} (zero router execute sites).

LayerLocationResponsibilityMust not
Routerbackend/routers/HTTP: Pydantic validation, Depends auth, call service/repo, return response modelsawait db.execute / conn.execute (new calls blocked by CI); business rules; cross-router imports
Servicebackend/services/Business logic, orchestration, audit side-effects, external I/O orchestrationHTTP types (Request/Response); acquire its own DB connection
Repositorybackend/repositories/Parameterised SQL only; tenant_id in WHERE for tenant-scoped tablesHTTP; branching business rules beyond query parameters

optional

HTTP request

Router

Service

Repository

PostgreSQL

Redis, LM Studio, Stripe

Delegation today: All routers under backend/routers/ delegate data access to services/* and/or repositories/* — 0 legacy await db/conn.execute call sites (router_sql_baseline.json is {}; D6 Resolved 2026-07-17). CI gate python scripts/check_router_sql.py blocks any regression.

backend/
├── main.py FastAPI app, middleware, router includes, static SPA
├── run_server.py Dev entry (Windows-friendly uvicorn :8021 + reload)
├── config.py Environment-driven settings; fails fast in production if unsafe
├── database.py Pool (primary + optional RO replica), get_db(), get_ro_db(),
│ init_db(), MODULES tuple
├── auth.py JWT, password hashing, tenant/module/patient-access dependencies
├── models.py Pydantic models (request/response shapes)
├── schema.sql Idempotent DDL supplement (PostgreSQL)
├── schema/
│ └── lyncareos_v1_baseline.sql Full consolidated DDL for greenfield DBs (v1 baseline)
├── seed_admin.py Super-admin / tenant seed (sync psycopg)
├── requirements.txt Production Python dependencies
├── requirements-dev.txt Dev/test-only dependencies
│
├── routers/ Feature routers (one file per domain area)
│ ├── auth.py JWT login, register, refresh, logout, MFA, Google OAuth
│ ├── users.py User management, invitations acceptance, MFA setup
│ ├── invitations.py Admin invite generate/CRUD, share-channel tracking, public token verify (role set at approval)
│ ├── tenants.py Tenant CRUD, membership management
│ ├── subscriptions.py Module subscription state
│ ├── reason_types.py Dispensing reason types
│ ├── dispensings.py Manual dose records (create, list, patch, delete)
│ ├── analytics.py Dispensing time-series, aggregates
│ ├── audit.py Append-only audit log queries (admin)
│ ├── medication_groups.py Medication schedule groups + auto-dispense
│ ├── patients.py Patient CRUD, member listing, photo
│ ├── care_shifts.py Care groups, shifts, tasks, group members
│ ├── patient_appointments.py Patient appointments
│ ├── scripts.py Prescription scripts + tenant catalogue (V103; scan, fills, stock)
│ ├── sleep.py Sleep pattern entries
│ ├── vitals.py Vitals tracking (BP, SpO2, weight, temp, etc.)
│ ├── pain.py Body-map pain entries
│ ├── mind.py Mind / mood tracking
│ ├── pain_settings.py Tenant pain module settings (no module gate)
│ ├── shopping.py Patient shopping lists + catalog consumer
│ ├── key_contacts.py Patient key contacts
│ ├── admin_shopping.py Super-admin catalog management (delegates to `repositories/shopping`)
│ ├── condition_packs.py Condition archetypes and pack marketplace (`custom_observations` gate)
│ ├── observations.py Flexible patient observations + Bollinger trends (service/repo)
│ ├── help_requests.py Family help board (service only — no router SQL)
│ ├── pwa_auth.py PWA ↔ Safari OAuth session handoff
│ ├── stripe.py Stripe Checkout signup, upgrade, webhook
│ ├── billing.py Public tiers/FX + authed billing context
│ ├── onboarding.py Onboarding step tracker
│ ├── alerts.py Care alerts list, open-count, resolve, admin channel settings
│ └── dev_tools.py Non-production test helpers
│
├── services/ Business logic and cross-cutting concerns
│ ├── cache.py Redis TTL caches (modules, patients, medicines, catalog)
│ ├── crypto.py Fernet + HKDF for MFA TOTP secrets (mfa:v1: prefix)
│ ├── field_crypto.py Fernet + HMAC blind index for PHI columns (phi:v1: prefix)
│ ├── google_auth_service.py Google OAuth; user lookup by email_idx; encrypt on create
│ ├── images.py WebP store/serve helpers; tenant-partitioned paths under UPLOADS_DIR
│ ├── lmstudio.py LM Studio HTTP client (prescription scan)
│ ├── mfa_service.py TOTP enrolment, verify, recover, disable
│ ├── mind_service.py Mind entry persistence + escalation triggers
│ ├── alert_service.py Raise/resolve shared care alerts (policy + dedup)
│ ├── alert_scheduler.py APScheduler: shift reminders, overdue-dose sweep
│ ├── alert_tasks.py Dedicated pool connection for background alert jobs
│ ├── alert_fire.py Fire-and-forget alert tasks (own DB connection)
│ ├── pain_service.py Pain entry persistence + escalation triggers
│ ├── pwa_auth_service.py Redis-backed PWA OAuth session store
│ ├── redis_client.py Shared Redis async client (lazy init, close on shutdown)
│ ├── scan_queue_pg.py PostgreSQL scan_jobs queue (V075; FOR UPDATE SKIP LOCKED)
│ ├── scan_queue.py Public facade over scan_queue_pg (enqueue, SSE stream; B6)
│ ├── analytics_refresh.py REFRESH MV analytics_dispensing_summary; optional conn= for tests (B5)
│ ├── patients_service.py Patient CRUD + access (router SQL-free; SQL in service)
│ ├── script_stock.py Prescription stock (baseline + legacy formulas; single enrich path)
│ ├── patient_scripts_service.py Prescriptions + catalogue (B3)
│ ├── medication_groups_service.py Schedule groups + auto-dispense (B3)
│ ├── schedule_from_script.py Build medication schedule items from a prescription
│ ├── scheduler.py APScheduler factory, per-tenant job bootstrap
│ ├── shopping_service.py Shopping list CRUD, catalog, recurring reset
│ ├── signup_service.py Pending signup CRUD + Google username derivation
│ ├── sse_tickets.py Redis-backed one-time SSE ticket (GETDEL)
│ ├── stripe_provisioning.py Tenant/user/subscription creation from Stripe webhook
│ ├── stripe_service.py Stripe price-map seed, tier helpers
│ ├── tenant_deletion_service.py Cascade-delete a tenant and all its data
│ ├── tier_limits.py Subscription tier limit enforcement
│ ├── care_shifts_service.py Care shift business logic — extracted in D6 pass 1
│ ├── vitals_service.py Vitals entry persistence helpers
│ ├── observations_service.py Observation types, entries, Bollinger trends
│ ├── help_requests_service.py Family help request lifecycle
│ └── condition_packs_service.py Pack catalogue helpers (used by condition_packs router)
│
├── repositories/ Pure SQL data-access functions (11 modules; partial coverage)
│ ├── care_shifts.py Care shift, task, and group SQL (B3)
│ ├── medication_groups.py Medication schedule groups + dispense-view SQL (B3)
│ ├── patient_scripts.py Prescription scripts + merged medicine catalogue (B3 / V103)
│ ├── alerts.py care_alerts, care_alert_events, tenant settings
│ ├── analytics.py analytics_dispensing_summary MV reads (B5)
│ ├── condition_packs.py Condition pack and archetype SQL
│ ├── dispensings.py Dispensing list/aggregate SQL
│ ├── help_requests.py Family help-board SQL
│ ├── observations.py patient_observations and observation_types SQL
│ ├── pain.py Pain entry queries
│ └── shopping.py Shopping list and catalog queries
│
├── workers/
│ └── scan_worker.py Dequeues scan_jobs (PG) → LM Studio → pg_notify for SSE
│
├── middleware/
│ └── rate_limit.py SlowAPI Redis limiter + JWT-signature key function
│
├── migrations/ Active VNNN__*.sql + runner.py; pre-v1 archive in archive/pre-v1/
│ └── scripts/
│ └── encrypt_phi_fields.py Idempotent B4 backfill (patients, users, care_groups, tenants)
└── scripts/ CI gates, Stripe tier seed, catalog tooling
├── check_router_sql.py D6 gate: fails CI on *new* `await db/conn.execute` in routers
└── router_sql_baseline.json Per-router allowed SQL call counts (update with `--update` after extraction)

Layering (D6 — complete 2026-07-17): Router → Service → Repository is enforced for all routers (see Layer boundaries above). Inventory: 36 router modules under backend/routers/, 19+ repository modules, 38+ service modules; 0 baseline-gated router SQL call sites (router_sql_baseline.json is {}). CI gate: python scripts/check_router_sql.py from backend/ — fails on any new router SQL. Git-free security review: scripts/security-review-static.ps1 at repo root (Ruff, router-SQL scan, secret patterns, Tier-3 checklist). RLS (V034) is defence-in-depth. Prefix normalisation (TODO(C3) / D15) unchanged — see 32 D15.


frontend/src/main.tsx — ThemeProvider (dark/light/system) wraps App. App.tsx nests AuthProvider → BrowserRouter → routes. Authenticated shell: ProtectedRoute → ModuleProvider → PatientProvider → AlertProvider → Layout (outlet). Care boards: useCareModuleFlags() reads ModuleContext — there is no CareModuleFlagsProvider wrapper.

ContextFilePurpose
AuthContextcontext/AuthContext.tsxJWT access token (in-memory), refresh (HttpOnly cookie), user object, login/logout, _tryRefresh() on bootstrap.
PatientContextcontext/PatientContext.tsxLoads GET /api/patients once on login; keeps activePatientId in localStorage; list is already filtered server-side for non-admins.
ModuleContextcontext/ModuleContext.tsxLoads active module slugs + feature_flags.care_module_boards via GET /api/subscriptions/active; super-admins get all module slugs but still use API feature_flags for care boards.
AlertContextcontext/AlertContext.tsxOpen alert count, Badging API (navigator.setAppBadge), 60s polling while session active.
ThemeContextcontext/ThemeContext.tsxlight / dark / system preference stored in localStorage; system listens to prefers-color-scheme. Toggles dark class on <html>.

All routes under the ProtectedRoute wrapper require an approved authenticated session. ModuleGate wraps routes that require a subscription module. AdminGate wraps admin-only routes.

RouteComponentGate
/loginLoginPublic
/registerRegisterPublic
/pendingPendingApprovalPublic
/billing/successBillingSuccessPublic (post-Stripe redirect)
/billing/cancelBillingCancelPublic
/billing/upgrade-successBillingUpgradeSuccessPublic
/DashboardProtected
/calendarCalendarProtected + care_calendar
/scheduleScheduleProtected + care_calendar
/logLogDoseProtected + medication_dispensing
/historyHistoryProtected + medication_dispensing — Dispensing and Adverse Reactions History Log: dose records plus coral-highlighted adverse reaction events; deep link ?adverseReaction={check_id}
/analyticsAnalyticsProtected + medication_dispensing
/auto-dispenseAutoDispenseProtected + medication_dispensing
/medication-scheduleMedicationScheduleProtected + medication_dispensing
/scriptsScripts (nav: Medications)Protected + prescription_management
/scripts/:scriptIdScriptDetailProtected + prescription_management
/admin/medicinesRedirect → /scriptsProtected + prescription_management
/sleepSleepPatternProtected + sleep_tracking
/vitalsVitalsTrackingProtected + vitals_tracking
/painPainTrackingProtected + pain_tracking
/shoppingShoppingProtected + shopping
/contactsKeyContactsProtected + key_contacts
/care-archetypesRedirect → /subscriptionsLegacy URL (exploratory page removed 2026-06-26)
/observationsObservationsProtected + custom_observations (requires active patient)
/help-requestsHelpRequestsProtected + family_help (discover via More)
/planning-aheadPlanningAhead (planned D31)Protected + care_pathways — Future; spec 33
/accountAccountProtected
/settingsSettingsProtected (admin-only — non-admins redirect to /)
/peoplePeopleReadOnlyProtected
/moreMoreProtected
/getting-startedGettingStartedProtected
/module-upgradeModuleUpgradeProtected
/subscriptionsSubscriptionsProtected (require_tenant_member; all roles — purchase via admin, members may request modules)
/admin/subscriptionsRedirect → /subscriptionsProtected
/admin/patientsPatientsAdminProtected + AdminGate
/admin/shopping-catalogShoppingCatalogAdminProtected + AdminGate
/admin/alertsAlertSettingsProtected + AdminGate
*Redirect to /—
frontend/src/
├── main.tsx Entry — ThemeProvider → App
├── App.tsx BrowserRouter, providers, route tree
│
├── context/
│ ├── AuthContext.tsx JWT + refresh + user state
│ ├── PatientContext.tsx Active patient selection
│ ├── ModuleContext.tsx Active modules + `feature_flags.care_module_boards` (one `/subscriptions/active`)
│ ├── CareModuleFlagsContext.tsx `useCareModuleFlags()` hook only — **no Provider** (reads ModuleContext)
│ ├── AlertContext.tsx Open alert count, Badging API, 60s poll
│ └── ThemeContext.tsx Light / dark / system theme
│
├── pages/ Route-level page components
│ ├── Login.tsx, Register.tsx, PendingApproval.tsx
│ ├── Dashboard.tsx, LogDose.tsx, History.tsx, Analytics.tsx
│ ├── Calendar.tsx, Schedule.tsx, AutoDispense.tsx, MedicationSchedule.tsx
│ ├── Scripts.tsx, ScriptDetail.tsx
│ ├── SleepPattern.tsx, VitalsTracking.tsx, PainTracking.tsx
│ ├── Shopping.tsx, KeyContacts.tsx
│ ├── Account.tsx, Settings.tsx, More.tsx, GettingStarted.tsx, PeopleReadOnly.tsx
│ ├── ModuleUpgrade.tsx, BillingSuccess.tsx, BillingCancel.tsx, BillingUpgradeSuccess.tsx
│ └── admin/
│ ├── Subscriptions.tsx, Patients.tsx, ShoppingCatalogAdmin.tsx, AlertSettings.tsx
│
├── care-modules/ Care Profile plugins (lazy when VITE_CARE_MODULE_BOARDS)
│ ├── CareModuleRoutes.tsx Conditional /care/* routes (lazy + Suspense + ErrorBoundary per route)
│ ├── registry.ts Manifest per slug
│ ├── hooks/useCareBoard.ts Board state + capture API
│ ├── shared/ CareBoardShell, CareBoardGate
│ ├── cancer/CareBoardPage.tsx Visual hub (LEARNING layout) + CaptureSession
│ ├── cancer/cancerCareFlow.ts buildCancerCareFlow, buildComfortBecauseLine, NextForkAction
│ ├── cancer/cancerBoardVisual.ts Icon map + hub tile types
│ ├── cancer/cancerRadarConfig.ts 8-spoke metadata, health scores, usual-week targets (**`fever_worry`:** stored level 4 = fever/chills — **`higherIsBetter: false`**, target **1** = no signs)
│ ├── cancer/radarTapGeometry.ts Tap hit-test for chart ring dots
│ ├── cancer/components/ InlineComfortCheckIn, CancerComfortRadar, CancerComfortRadarChart, CareFlowRail, BecauseLine, NextStepFork, CollapsibleSection, CancerPrimarySitePicker, CancerTileCard, …
│ ├── cancer/VisitPrepPage.tsx Week-at-home summary for clinic (bullet lines + questions + larger text)
│ └── breathing/CareBoardPage.tsx
│
├── components/
│ ├── Layout.tsx, ProtectedRoute.tsx App shell, route guard
│ ├── calendar/ Shift card, views, drag interactions
│ ├── charts/ ECharts wrappers + theme
│ ├── dose/ LogDose modals, dose history items
│ ├── history/ History list, audit tab
│ ├── layout/ Nav, sidebar, header
│ ├── medication/ Schedule editor, group modals
│ ├── medication-schedule/ MedicationSchedule sub-components (D6 pass 1)
│ │ ├── PrnDosePills.tsx PRN dose pill badges
│ │ ├── ScheduleChangedMark.tsx Visual indicator for schedule change
│ │ ├── ScheduleChangePanel.tsx Change detail panel (who/when/snapshot)
│ │ └── medScheduleUtils.ts Pure utility functions (cellKey, fmtTime, canUserDispense, …)
│ ├── alerts/ AlertBell, AlertInbox, AlertRow
│ ├── pain/ Body map, pain entry forms, vitals forms
│ ├── scripts/ Script card, scan modal, fill modal
│ ├── settings/ Settings sections, user management
│ ├── shopping/ Shopping list tiles, catalog browser, ShoppingDashboardWidget
│ ├── care-capture/ CareCaptureOverlay, CaptureSession, TrafficLight3, SegmentedBar
│ ├── dashboard/ TodayHero, CareBoardDashboardChip, …
│ ├── sleep/ Sleep chart, entry forms
│ ├── admin/ Admin tables, subscription management
│ └── ui/ Modal, Select, Button, Toast, and other primitives
│
├── hooks/
│ ├── useMatchMedia.ts Responsive breakpoint hook (preferred over hardcoded widths)
│ ├── useRequest.ts Typed fetch wrapper with loading/error state
│ ├── useAuthenticatedImage.ts Fetch image blobs that require auth headers
│ ├── useContainerWidth.ts ResizeObserver-based container width measurement
│ ├── useShoppingSync.ts Redis pub/sub → SSE → local state sync for shopping lists
│ ├── usePainConfig.ts Pain module settings loader
│ ├── usePainDateData.ts Pain entries paginated data loader
│ └── usePainTrends.ts Pain trend aggregation helper
│
├── lib/
│ ├── api.ts ALL API calls — `request()`, `uploadForm()`, typed helpers per domain.
│ │ `credentials: 'include'` everywhere; shared refresh-on-401 logic.
│ │ Re-exports domain types from lib/types/* — existing import paths unchanged.
│ ├── types/ Domain-scoped TypeScript type files (split from api.ts; Phase 0 H-07)
│ │ └── care.ts Care shift, task, appointment types (CareShift, ShiftCreate, …)
│ ├── chartTheme.ts ECharts theme tokens
│ ├── calendarHelpers.ts Shift layout, slot calculations
│ ├── calendarViewHelpers.ts Month grid helpers — `dayActivityIndicators`, `careModuleDayIconKeys`, month list builders
│ ├── doseFormat.ts Dose volume/unit display formatting
│ ├── medicineColors.ts Colour assignment for medicines
│ ├── trendChart.ts Trend chart data transformers
│ ├── errors.ts API error shape, typed error helpers
│ ├── dispensingsEvents.ts Cross-page refresh after dose log / history delete
│ ├── scriptsEvents.ts Cross-page refresh after script fill / stock edit
│ ├── scriptAlerts.ts Prescription alert banner copy + deep links
│ └── … Other domain helpers
│
└── config/ Feature flags, build-time constants
  • Bootstrap: AuthContext calls _tryRefresh() on mount — exchanges the lyncare_refresh HttpOnly cookie for a new in-memory access token without asking the user to log in again. No cookie → HTTP 204 (silent logged-out bootstrap; not 401).
  • Access token: in-memory (JS variable) — lost on page reload; restored via refresh cookie.
  • Refresh token: lyncare_refresh HttpOnly, SameSite=Lax, Secure-in-production cookie.
  • Refresh-on-401: lib/api.ts intercepts any 401 response, attempts one refresh, retries the original request.
  • Logout: POST /api/auth/logout clears the cookie server-side.
  • Google sign-in: Full-page OAuth redirect from /login; PWA handoff on iOS via pwa_auth (Redis-backed session store).

Identity encryption at the auth boundary (B4): Plaintext identity columns were removed in V091; handlers use services/field_crypto.py at read/write boundaries.

FlowEncrypt on writeLookup / decrypt on read
Email/password login—email_blind_index → users.email_idx; decrypt_user before JWT payload
Register / invite acceptencrypt_field on email; patient/care-group names as applicabledecrypt_user, decrypt_patient, decrypt_tenant in responses
Google OAuth (google_auth_service)Encrypt new user email; blind index on createprocess_google_user resolves by email_idx
Stripe signup (signup_service, stripe_provisioning)Tenant and user identity fields encrypted in provisioning transactionAdmin/tenant displays via decrypt helpers
Cross-router reads—users, invitations, patients, tenants, care_shifts, alerts routers call decrypt helpers before returning names/emails

Keys: PHI_ENCRYPTION_KEY, PHI_BLIND_INDEX_KEY (independent of MFA crypto.py). Full column map: Field-level PHI encryption (B4).


Shared care alerts replace per-user push/inbox fan-out. One open row per real-world issue (dedup_key); all carers and admins with patient_access see the same queue. Resolving an alert writes care_alert_events (who / when / optional note).

Overdue dose consolidation: Multiple missed medication groups for the same patient on the same calendar day share one open alert (dedup_key overdue_dose:{patient_id}:{dose_date}). metadata.miss_count and the alert body reflect how many groups are still overdue (e.g. “3 scheduled doses not recorded”). Recording a dose triggers a background refresh that decrements the count or resolves the alert when none remain. Legacy per-group open rows are auto-resolved when the consolidated alert syncs.

Shopping consolidation: Active (unpurchased) shopping list items for a patient share one open alert (dedup_key shopping:{patient_id}). metadata.item_count and the alert body reflect how many items still need collecting (e.g. “4 items on the shopping list.”). Adding, purchasing, unpurchasing, removing, or recurring-resetting items triggers sync_shopping_alert_for_patient after HTTP commit; the count updates in place or the alert auto-resolves when no active items remain. Legacy per-item open rows (shopping:{item_id}) are auto-resolved when the consolidated alert syncs. Discrete alerts (help requests, shifts, calendar events) stay one row per actionable item.

First-dose adverse reaction (REQ-MED-16): The first dispense for a patient + normalized medicine name raises first_dose_reaction (structured Answer required — generic Done blocked). On Yes, the service resolves that alert and raises urgent adverse_reaction_reported with metadata.reaction_notes; tap opens AdverseReactionDetailModal. History deep link: /history?patientId={id}&adverseReaction={check_id}. Uses the first_dose_reaction notification channel toggle.

Alert typeSeverityBehaviour
first_dose_reactionnormalAnswer via POST /api/first-dose-reactions/{check_id}/respond
adverse_reaction_reportedurgentTap card → detail modal; Mark done when handled
EndpointPurpose
POST /api/first-dose-reactions/{check_id}/respondStructured Yes/No; Yes triggers adverse_reaction_reported
GET /api/first-dose-reactions/{check_id}Check detail for modals / deep links
GET /api/patients/{patient_id}/adverse-reaction-logObserved reactions for history timeline

Table patient_medicine_first_dose_checks (migration V004): one row per patient + normalized medicine name; adverse_reaction_observed NULL | FALSE | TRUE.

PostgreSQLalert_service"FastAPI alerts router""React AlertBell"PostgreSQLalert_service"FastAPI alerts router""React AlertBell"Clinical event pain, shift, shoppingnavigator.setAppBadge countcheck tenant_notification_settingsUPSERT care_alerts open dedup_keyGET open alert count poll on logincount payloadGET open alerts listPOST resolve alertUPDATE care_alerts and INSERT care_alert_events
FileRole
backend/services/first_dose_reaction_service.pyFirst-dose prompt detection; structured respond; adverse-reaction follow-up
backend/routers/first_dose_reactions.pyPOST …/respond, GET …/{check_id}, GET …/adverse-reaction-log
backend/repositories/first_dose_reactions.pypatient_medicine_first_dose_checks SQL
backend/migrations/V004__first_dose_reaction_checks.sqlFirst-dose checks table + notification channel
frontend/src/components/medication/FirstDoseReactionModal.tsxPost-dispense prompt; post-Yes → detail modal
frontend/src/components/medication/AdverseReactionDetailModal.tsxReaction note, seek advice, clinical contacts
frontend/src/lib/contactRoles.tsShared role labels; pickAdverseReactionContacts()
backend/migrations/V005__key_contacts_palliative_specialist.sqlpalliative_specialist on key_contacts.role_tag
backend/routers/alerts.pyList open alerts, open-count, resolve, events, admin channel settings
backend/services/alert_service.pyPolicy check → upsert open alert (nine tenant channels + master toggle)
backend/services/alert_scheduler.pyShift reminders (24h), overdue-dose hourly sweep (per patient, consolidated)
backend/services/alert_dose_sync.pyUpsert/resolve consolidated overdue-dose alert from live group counts
backend/services/alert_dose_helpers.pyConsolidated dedup keys, overdue-window checks, “dose recorded today”
backend/services/alert_dose_hooks.pyschedule_refresh_overdue_dose_alert() after dispense commits
backend/services/alert_shopping_sync.pyUpsert/resolve consolidated shopping alert from active item counts
backend/services/alert_shopping_helpers.pyShopping dedup key, active-item count query, alert body text
backend/services/alert_fire.pyschedule_alert(fn) — background tasks with dedicated pool connection
backend/repositories/alerts.pySQL for care_alerts, care_alert_events, settings (incl. family_help)
frontend/src/context/AlertContext.tsxOpen-count polling, Badging API
frontend/src/components/alerts/AlertBell, AlertInbox, AlertRow
frontend/src/pages/admin/AlertSettings.tsxTenant channel toggles (/admin/alerts)
backend/migrations/V073__care_alerts.sqlcare_alerts, care_alert_events
backend/migrations/V100__care_alerts_metadata.sqlcare_alerts.metadata JSONB (miss_count for overdue dose; item_count for shopping)
backend/migrations/V093__alert_settings_family_help.sqltenant_notification_settings.family_help channel toggle
backend/migrations/V094__subscriptions_add_family_help_module.sqlsubscriptions.module CHECK includes family_help
backend/migrations/V063__notifications.sqlLegacy tables + tenant_notification_settings (still used for toggles)

Channels (tenant toggles): shift reminder/cancelled, calendar events, handover notes, shopping, family help (new_help_request, help_request_taken), body pain high, mind elevated, overdue dose, first-dose adverse reaction (first_dose_reaction + adverse_reaction_reported).

Event triggers call schedule_alert(lambda conn: …) from routers/services after HTTP commit (appointments, shifts, shopping, pain, mind, help requests). Help requests: help_requests_service commits, then schedules; take resolves new_help_request:{id} and raises help_request_taken. Dispense endpoints call schedule_refresh_overdue_dose_alert() (alias schedule_clear_overdue_dose_alert) after commit to refresh the consolidated overdue count. Shopping mutations call sync_shopping_alert_for_patient (via shopping_service._schedule_shopping_alert_sync) after commit to refresh the consolidated item count. Observers may list alerts but cannot resolve (403).

Future: native push mirror (APNs + FCM) [Target — REQ-NATIVE-03]

Section titled “Future: native push mirror (APNs + FCM) [Target — REQ-NATIVE-03]”

The PWA keeps in-app care alerts as the source of truth. When Capacitor ships, optional native push mirrors new open care_alerts to device tokens — lock-screen awareness only, not a second inbox.

FCMAPNsPostgreSQLalert_serviceFastAPICapacitor appFCMAPNsPostgreSQLalert_serviceFastAPICapacitor appEvent opens care_alertRegister native push device tokenUPSERT push_subscriptionsUPSERT care_alerts openEnqueue native push for tenant membersSend iOS notificationSend Android notificationLock-screen notificationLock-screen notificationGET alerts authoritative state

Backend changes required:

  • New or extended push_subscriptions with delivery_type (apns | fcm) and device_token — no VAPID path.
  • native_push_service (or hook in alert_fire) reads open alerts and fans out to registered tokens.
  • APNS_* and FCM_* env vars in .env.example.

Frontend / Capacitor:

  • @capacitor/push-notifications registers token with the API; tap opens the app to /alerts (or deep link).
  • PWA build unchanged — AlertContext polling + Badging API only.

Prescription script alerts (Dashboard / Medications) [Current]

Section titled “Prescription script alerts (Dashboard / Medications) [Current]”

Stock-count mismatch also syncs into care_alerts (alert_type prescription_stock_count, dedup per script) via services/alert_script_sync.py + alert_script_hooks.await_sync_prescription_stock_count_alert (inline on the request connection after commit, so the bell sees resolve/raise before the HTTP response). Runs after dispense, stock PATCH, and pharmacy fill. Auto-resolves when on-hand > 0; Mark done remains for handled-without-fix. Visible in the bell / Care alerts inbox for admins (deep_link → /scripts/{id}?setup=stock). Tenant members still use inline guidance, not this inbox row.

Computed script banners (other types) remain on read from GET /api/patients/{id}/scripts/alerts, filtered per user by script_alert_dismissals (migration V105, 2026-06-03) on Home and Medications only.

typeSeverityWhen
stock_tracking_incompleteAmberstatus = active, no doses logged yet (total_dispensed = 0), and stock setup incomplete: quantity_per_fill or total_fills_authorised missing or ≤ 0 (REQ-SCRIP-STOCK-02). Suppressed once doses are logged — use stock_count_needed instead.
stock_lowAmberStock tracking complete (quantity_per_fill and total_fills_authorised both > 0); derived stock_on_hand ≤ low_stock_threshold (default 7). Requires fills_completed > 0.
stock_count_neededAmberAdmin / super_admin only (filtered in get_script_alerts). Dose log total_dispensed > 0 and derived stock_on_hand is 0 or null — count out of step with ongoing dispensing (includes manual baseline 0 and total_fills_authorised = 0 edge cases). Links to ?setup=stock. Not shown to tenant members (inline StockCountGuidancePanel on Log Dose / schedule). Banners on Home and Medications only.
approaching_last_fillAmberfills_completed = total_fills_authorised − 1.
exhausted / expiredRedScript status.

Excluded: paused, superseded, archived. Stock: services/script_stock.py (single brain) via repositories/patient_scripts.enrich_script() / derive_stock(). Result round() to a whole unit; null without quantity_per_fill and no manual baseline.

Prescription stock — what families see vs backend — Done 2026-06-03 (baseline V112–V113, family copy 2026-06-03)

Section titled “Prescription stock — what families see vs backend — Done 2026-06-03 (baseline V112–V113, family copy 2026-06-03)”

Stock is derived, never stored as stock_on_hand. Family UI shows Doses available (and Last counted when set) only — not lifetime doses logged. Backend still tracks total_dispensed for mismatch alerts.

ConceptSourceUI label
Pharmacy supplyfills_completed × quantity_per_fill (legacy path) or SUM(script_fills.quantity_added) since baselineImplied by fills / pack size (not a separate card line today)
Dose log total (API only)SUM(dispensings.volume) lifetimetotal_dispensed — alert logic only; not shown on family UI
On hand nowBaseline path (V112): last_physical_count + fills_since − dispensings_since. Legacy path: round(fills×qty + stock_adjustment − lifetime_dispensed)Doses available (stock_on_hand)
Last physical auditlast_physical_count, last_physical_count_at (persisted on PATCH pills_available)Last counted: N on <date> (LastPhysicalCountLine)

Manual physical count takes precedence: PATCH pills_available sets last_physical_count, last_physical_count_at = clock_timestamp(), stock_adjustment = 0. Lifetime dose-log volume does not reduce on-hand after that moment; only dispensings with created_at > last_physical_count_at subtract (V113: dispensings.created_at defaults to clock_timestamp() so since-audit works inside one transaction).

Pharmacy fill (POST …/fills): record_fill() sets last_physical_count = prior on_hand + quantity_added and a new baseline timestamp so a new pack is not reduced by historical dose log (e.g. 0 on hand + fill 28 → 28, not 21 when seven doses were logged). low_stock_threshold is alert-only — never subtracted from stock.

Stock mismatch (zero on hand, doses still logged): Dose logging is never blocked when stock_on_hand is 0. StockCountGuidancePanel on Log Dose (form + success screen), Medication schedule batch dispense, and schedule dispense sheet explains the mismatch; admins link to Update doses on hand (/scripts/{id}?setup=stock). Recurring mismatch → stock_count_needed computed banner (Home/Medications) plus durable prescription_stock_count in Care alerts (bell, admin-only) for tenant admins (V114). Tapping the care alert opens EditScriptModal with How many doses do you have available? highlighted and scrolled into view (emphasizeStockField). No alert while on-hand and dose log are both zero — mismatch appears only after at least one logged dose.

Exhausted scripts and medicine-summary: status = exhausted means no pharmacy repeats left, not zero tablets. GET …/medicine-summary total_stock_on_hand uses the same computed on-hand as list/detail for all statuses (not forced to 0 for non-active).

Admin dose count on hand (PATCH pills_available) — Done 2026-06-03

Section titled “Admin dose count on hand (PATCH pills_available) — Done 2026-06-03”

Admins set doses available via edit label DOSES_ON_HAND_PROMPT (“How many doses do you have available?”). Unit-agnostic amount with prescription unit. They do not edit raw stock_adjustment in the UI.

ItemDetail
APIScriptUpdate.pills_available (optional, ge=0). On PATCH …/scripts/{id}, persists baseline columns; 400 if both pills_available and stock_adjustment are sent. Response includes total_dispensed (lifetime float) and stock_on_hand.
Serviceservices/script_stock.py — load_lifetime_dispensed_totals, load_since_baseline_aggregates, enrich_scripts_stock; used by list, detail, medicine-summary, alerts
Repositoryenrich_script() delegates to script_stock; legacy adjustment_for_pills_available() retained for tests only
Frontendlib/scriptStock.ts — DOSES_AVAILABLE_LABEL, DOSES_ON_HAND_PROMPT, needsStockCountGuidance(), stockCountdownBar(). LastPhysicalCountLine, StockCountGuidancePanel. Edit modal asks How many doses do you have available?; dispensingsEvents → notifyScriptsChanged().
TestsTestStockAdjustment; TestFillManagement::test_record_fill_after_zero_stock_ignores_prior_dose_log; TestScriptAlerts::test_stock_count_needed_admin_only, test_stock_count_needed_when_total_fills_zero_but_doses_logged; frontend/src/test/lib/scriptStock.test.ts
Rules.cursor/rules/medications-database-master.mdc; review artefact medications-database-master.mdc

Remaining backlog (not launch blockers):

IssueImpact
quantity_added on script_fills only in since-baseline SUM; legacy path still uses fills×quantity_per_fillPartial pharmacy pick semantics — document in spec before changing legacy scripts
Denormalized total_dispensed_volume on patient_scriptsDeferred until profiling shows SUM hot

Per-user dismiss (3-day snooze) — Done 2026-06-03

Section titled “Per-user dismiss (3-day snooze) — Done 2026-06-03”
ItemDetail
Tablescript_alert_dismissals — (user_id, patient_id, script_id, alert_type) unique; dismissed_at timestamp
SnoozeBanner hidden for 3 days after Ignore; returns if the condition still applies
Resolved conditionWhen the alert would no longer fire (e.g. stock above threshold), the snooze row is deleted on the next GET …/alerts so a new issue is not blocked
APIPOST /api/patients/{id}/scripts/alerts/dismiss — body { script_id, alert_type } → 204
UIScriptAlertBanner — Ignore pill on Home and Medications; main row still navigates to script detail

Still pending: Dashboard nav badge count for script alerts (REQ-SCRIP-NOTIF §12).

UI refresh (2026-06-02, hardened 2026-06-03)

Section titled “UI refresh (2026-06-02, hardened 2026-06-03)”

Fills and stock edits must update Home/Medications banners without relying on route remount:

MechanismRole
lib/scriptsEvents.tsnotifyScriptsChanged() + SCRIPTS_CHANGED_EVENT + sessionStorage touch (mirrors dispensingsEvents.ts). takeScriptsTouchForInitialState() peeks only (Strict Mode safe).
lib/scriptAlerts.tsBanner copy + navigation (stock_tracking_incomplete, stock_count_needed → /scripts/{id}?setup=stock).
FillModalOn hand after collection preview; notifyScriptsChanged() after successful POST …/fills.
Dashboard.tsxListens for event / touch; refetches scripts.alerts with cancelled in-flight requests; pageshow (bfcache) bumps scriptsDataGen.
Scripts.tsxSilent load() on event; touch when returning to /scripts*.
ScriptDetail.tsx?setup=stock opens Edit for admins; “Set up stock tracking” on amber panel.
ScriptAlertBanner.tsxIgnore pill + dismiss API (Home + Medications).

dispensingsEvents calls notifyScriptsChanged() after a dose log so Medications card stock and dose-log lines refresh without a full reload.

FileRole
backend/migrations/V112__patient_scripts_physical_count_baseline.sqllast_physical_count, last_physical_count_at; dispensings index
backend/migrations/V113__dispensings_clock_timestamp_defaults.sqlclock_timestamp() defaults on dispensings timestamps
backend/migrations/V114__script_alert_stock_count_needed.sqlstock_count_needed on dismiss CHECK
backend/migrations/V105__script_alert_dismissals.sqlDismiss snooze table
backend/services/script_stock.pyCanonical stock + lifetime / since-baseline aggregates
backend/services/alert_script_sync.pyUpsert / auto-resolve prescription_stock_count in care_alerts
backend/services/alert_script_hooks.pyawait_sync_prescription_stock_count_alert — inline after stock/dispense commit
backend/services/alert_script_hooks.pySchedule stock-count care-alert sync after dispense / PATCH
backend/services/patient_scripts_service.pyget_script_alerts(), dismiss_script_alert(), record_fill(), pills_available baseline PATCH
backend/repositories/patient_scripts.pyderive_stock(), enrich_script(), dismiss helpers
backend/routers/scripts.pyGET …/scripts/alerts, POST …/alerts/dismiss, PATCH …/scripts/{id} (pills_available)
frontend/src/pages/Dashboard.tsxHome alert banners
frontend/src/pages/Scripts.tsxMedications alert banners
frontend/src/components/scripts/ScriptAlertBanner.tsxBanner + Ignore
frontend/src/components/scripts/MedicationCard.tsxDoses available + countdown bar + dose log line; EXHAUSTED_REPEATS_LABEL when exhausted
frontend/src/components/scripts/EditScriptModal.tsxDoses on hand (pills_available PATCH); amber highlight + scroll-to-field when on-hand is 0 / stock mismatch (emphasizeStockField from ?setup=stock)
frontend/src/lib/scriptStock.tsLabels (DOSES_AVAILABLE_LABEL, EXHAUSTED_REPEATS_LABEL, …), needsStockCountGuidance, resolveTotalDispensed, stockCountdownBar
frontend/src/lib/numericField.tsInteger text fields (no type="number" leading zeros)
frontend/src/pages/ScriptDetail.tsxFill + stock setup UX
frontend/src/components/scripts/FillModal.tsxRecord fill modal
frontend/src/components/scripts/StockCountGuidancePanel.tsxZero on-hand guidance (Log Dose, schedule dispense)
frontend/src/pages/LogDose.tsxManual dose entry; stock guidance on form + post-save success when needsStockCountGuidance
backend/tests/test_prescriptions.pyTestScriptAlerts, TestStockAdjustment, fill + stock tests

Spec: 08-PRESCRIPTIONS-MODULE.md §11–12.


Medication schedule — dose circles [Current]

Section titled “Medication schedule — dose circles [Current]”

Route: /medication-schedule (MedicationSchedule.tsx). Per medicine in an expanded time slot, the round action control shows:

StateCircle content
PendingScheduled dose_amount via ScheduleDoseCircleLabel (components/medication-schedule/ScheduleDoseCircleLabel.tsx)
OverdueSame numeric label; coral ring
DispensedSage checkmark

CellSheet saves dose via medicationGroups.addItem / updateItem; handleCellSaved merges into groups[].items so the circle updates without a full page reload.

Tests: frontend/src/test/components/ScheduleDoseCircleLabel.test.tsx, MedicationSchedule.test.tsx (dose visible in circle after expand).

Spec: 05-DEVELOPER-GUIDE § Medication Schedule.

Migration numbering: Post-v1 Care Start reconciliation shipped as V006–V009 (2026-06-04 on dev). Palliative §7.0.5 planned V106–V111 content is equivalent — see 11-DATABASE-SAFETY §2j.


LynCareOS ships as a Progressive Web App — installable on iOS and Android, usable in standalone display mode with a native-like experience. The PWA is the current primary delivery mechanism. The Capacitor native app is the planned successor for App Store distribution.

PropertyValueNotes
displaystandaloneHides browser chrome; full-screen native feel
display_override["window-controls-overlay", "standalone"]Allows WCO where supported (Sprint 2.7)
orientationportrait-primaryIntentionally portrait-locked for clinical use
theme_color / background_color#0f172a (slate-900)Matches dark mode app shell
Icons192 × 192, 512 × 512 (any + maskable)Used for home screen and splash screens
categorieshealth, medicalApp store metadata

Service Worker strategy (frontend/public/sw.js)

Section titled “Service Worker strategy (frontend/public/sw.js)”
Resource typeCache strategyRationale
App shell (HTML, JS, CSS, icons)Cache-first, update on installFast load; cache busted by SW CACHE_NAME
/api/* callsNetwork-onlyClinical data must always be fresh
API-served imagesNetwork-first, short cachePrescription / patient images may change
Navigation fallbackoffline.htmlBranded offline page when network is unavailable

Background Sync: frontend/src/lib/syncQueue.ts queues failed POST /api/dispensings mutations; the SW sync handler replays them when connectivity is restored.

Dev mode: SW self-destructs on localhost (unregisters + reloads) to prevent Vite HMR conflicts with stale cached /@vite/client.

Stale-bundle resilience after deploy: the SW CACHE_NAME is no longer a hand-edited string. frontend/public/sw.js declares const CACHE_NAME = 'lyncareos-__BUILD_ID__'; frontend/scripts/inject-sw-version.mjs runs as part of npm run build and substitutes the placeholder with the Vite main-bundle content hash. Every deploy ships a byte-different sw.js, which forces every open browser tab to install + activate the new SW and fire the existing SW_UPDATED → reload chain in index.html. Lazy-loaded React routes are wrapped in frontend/src/lib/lazyWithReload.ts so a ChunkLoadError (stale chunk filename after deploy) triggers a single guarded window.location.reload() instead of an error-boundary card. backend/main.py serves both index.html and sw.js with Cache-Control: no-cache, no-store, must-revalidate; a Cloudflare Cache Rule (lyncareos-sw-bypass) bypasses edge cache on /sw.js so the no-cache header reaches browsers. Strategy + remaining layers: docs/plans/2026-05-29-spa-deploy-resilience.md.

Web Push (VAPID) and sw.js push handlers were removed. Awareness is the shared care_alerts queue — see Care alerts (in-app). Legacy V063 tables and optional VAPID_* env vars remain for a future native-push path only.

PWA install prompt architecture [Target — REQ-ONBOARD-04]

Section titled “PWA install prompt architecture [Target — REQ-ONBOARD-04]”

Not yet implemented in the frontend. When built, install detection and snooze will live in dedicated components (not AlertContext). The iOS copy should reference in-app alerts and the home-screen icon badge, not browser push.

Yes

No

Yes under 14 days

No

Android

iOS

accepted

dismissed

Dismissed

Installed later

App boots

Already installed?

No prompt - app is installed

Dismissed recently?

Platform?

Listen for beforeinstallprompt

Show iOS bottom sheet

User taps Add to home screen?

appinstalled - dismiss permanently

Write pwa_prompt_dismissed - 14 day snooze

User taps Install or Dismiss?

Key implementation points:

ConcernImplementation
Android prompt interceptionbeforeinstallprompt captured in main.tsx before React mounts; stored as a module-level ref for the install prompt component
iOS detectionisIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) + !(window as Window & { MSStream?: unknown }).MSStream
Install state detectionwindow.navigator.standalone === true || window.matchMedia('(display-mode: standalone)').matches
Dismissal persistencelocalStorage.setItem('pwa_prompt_dismissed', Date.now()) — prompt hidden for 14 days
Install value hookThe iOS bottom sheet explains home-screen install for faster access and the app icon badge (open alert count)
Shift guardPrompt is suppressed while a care shift is active to avoid interrupting workflows
Type declarationfrontend/src/types/pwa.d.ts — declares BeforeInstallPromptEvent extending Event

frontend/src/types/pwa.d.ts (new file required):

interface BeforeInstallPromptEvent extends Event {
readonly platforms: string[];
readonly userChoice: Promise<{ outcome: 'accepted' | 'dismissed'; platform: string }>;
prompt(): Promise<void>;
}
declare global {
interface WindowEventMap {
beforeinstallprompt: BeforeInstallPromptEvent;
}
}

Authoritative DDL is backend/schema.sql. The diagram below reflects core tables. Additional tables (shopping catalog, sleep entries, pain/vitals/mind, Stripe, notifications, key contacts, etc.) are added by migrations/ — see schema_migrations and migration files for the full picture.

owns

member of

has

subscribes

manages

owns

PRN labels

records

logged for

issues

grants

has

includes

schedules

contains (optional since V026)

owns by date

dispensed in

reason for

has

has

linked to

scheduled in

filled by

stock deducted by

linked to

contains

auto-dispensed as

users

serial

id

PK

text

email

UK

text

username

UK

text

password_hash

text

role

text

status

text

google_id

UK

text

avatar_url

text

profile_colour

smallint

is_super_admin

smallint

must_change_password

timestamptz

created_at

timestamptz

last_login

tenants

serial

id

PK

text

name

text

slug

UK

integer

owner_user_id

FK

text

status

text

timezone

integer[]

manual_dose_quick_medicine_ids

timestamptz

created_at

tenant_memberships

integer

tenant_id

PK,FK

integer

user_id

PK,FK

text

role

text

status

integer

invited_by

FK

timestamptz

joined_at

subscriptions

serial

id

PK

integer

tenant_id

FK

text

module

text

status

timestamptz

valid_until

integer

activated_by

FK

timestamptz

activated_at

timestamptz

created_at

patients

serial

id

PK

integer

tenant_id

FK

text

name

text

photo_url

text

dob

text

address

text

medical_summary

text

gender

integer

created_by

FK

timestamptz

created_at

patient_access

integer

patient_id

PK,FK

integer

user_id

PK,FK

text

role

integer

granted_by

FK

timestamptz

granted_at

care_groups

serial

id

PK

text

name

integer

patient_id

FK

integer

created_by

FK

text

timezone

timestamptz

created_at

care_group_members

integer

group_id

PK,FK

integer

user_id

PK,FK

text

display_colour

text

display_name

timestamptz

joined_at

care_shifts

serial

id

PK

integer

group_id

FK

integer

patient_id

FK

integer

carer_id

FK

text

date

text

time_slot

text

start_time

text

end_time

text

location

text

priority

text

recurrence_rule

text

handover_notes

text

wellbeing_note

text

status

timestamptz

created_at

timestamptz

updated_at

care_tasks

serial

id

PK

integer

shift_id

FK

nullable since V026

integer

patient_id

FK

text

date

text

title

integer

sort_order

boolean

completed

timestamptz

completed_at

integer

completed_by

FK

text

source_care_profile_slug

text

source_action_id

text

source_task_id

text

task_prompt

text

response_kind

text

response_code

timestamptz

response_recorded_at

integer

response_recorded_by

FK

timestamptz

created_at

medicines

serial

id

PK

integer

tenant_id

FK

text

name

text

unit

text

color_hex

boolean

active

boolean

as_needed

timestamptz

created_at

reason_types

serial

id

PK

integer

tenant_id

FK

integer

patient_id

FK

V014 — per person in care

text

name

text

description

text

color_hex

integer

display_order

boolean

active

timestamptz

created_at

dispensings

serial

id

PK

integer

tenant_id

FK

text

date

text

time

integer

medicine_id

FK

double_precision

volume

integer

reason_type_id

FK

text

notes

integer

patient_id

FK

integer

script_id

FK

nullable

integer

scheduled_item_id

FK

nullable

integer

dispense_batch_id

nullable

text

proof_image_url

nullable

text

dose_kind

manual | auto | scheduled

timestamptz

created_at

timestamptz

updated_at

patient_scripts

serial

id

PK

integer

tenant_id

FK

integer

patient_id

FK

integer

medicine_id

FK

nullable

text

medicine_name_raw

text

strength

text

form

text

dose_instructions

text

unit

integer

quantity_per_fill

nullable

integer

total_fills_authorised

nullable

integer

fills_completed

integer

low_stock_threshold

text

prescriber_name

text

prescriber_practice

text

issued_date

text

expiry_date

text

image_url

timestamptz

image_stored_at

text

scan_status

text

scan_raw_text

real

scan_confidence

text

status

includes archived

integer

stock_adjustment

text

notes

integer

created_by

FK

timestamptz

created_at

timestamptz

updated_at

script_fills

serial

id

PK

integer

script_id

FK

integer

fill_number

integer

quantity_added

integer

collected_by

FK

timestamptz

collected_at

text

notes

medication_groups

serial

id

PK

integer

tenant_id

FK

integer

patient_id

FK

text

name

text

scheduled_time

text

color_hex

integer

sort_order

boolean

active

integer

created_by

FK

timestamptz

created_at

timestamptz

updated_at

medication_schedule_items

serial

id

PK

integer

group_id

FK

integer

tenant_id

FK

integer

patient_id

FK

integer

medicine_id

FK

integer

script_id

FK

nullable

double_precision

dose_amount

text

unit

text

instructions

integer

sort_order

boolean

active

integer

created_by

FK

timestamptz

created_at

timestamptz

updated_at

audit_log

serial

id

PK

integer

tenant_id

FK

integer

patient_id

FK

nullable; V099 - REQ-MED-15

text

action

text

entity_type

integer

entity_id

integer

performed_by

FK

text

snapshot_before

text

snapshot_after

text

changed_fields

text

deletion_reason

timestamptz

created_at

invitations

serial

id

PK

text

token

UK

integer

tenant_id

FK

integer

created_by

FK

text

message

integer

patient_id

FK

text

invite_role

text

invitee_email

text

invitee_contact

text

delivery_channel

timestamptz

shared_at

timestamptz

expires_at

timestamptz

used_at

integer

used_by

FK

timestamptz

created_at

Notable migration-added tables (not in schema.sql)

Section titled “Notable migration-added tables (not in schema.sql)”
Added byTables / columns
V011__sleep_trackingsleep_entries
V012__shopping_moduleshopping_lists, shopping_items, shopping_catalog_*
V028__patient_appointmentspatient_appointments
V033__audit_log_hardeningAudit triggers on PHI tables
V034__row_level_securityRLS policies using app_current_tenant_id()
V035__mfa_usersuser_mfa
V041__stripe_billingstripe_customers, stripe_subscriptions, stripe_events
V042__stripe_tiersstripe_tiers, stripe_prices
V043__signup_and_onboardingpending_signups, onboarding_steps
V047__tier_limits_and_pending_downgradeTier limit columns
V050–V058pain_entries, patient_vitals, mind_entries, tenant_pain_settings (see 26-PAIN-STATS-MODULE.md)
V060__key_contactspatient_key_contacts
V061__data_deletion_on_cancellationDeletion policy columns
V062key_contacts subscription module row
V063__notificationsuser_notifications, push_subscriptions, tenant_notification_settings
V064–V066Schedule item deactivation tracking (deactivated_at); medication dose change timestamp (dose_changed_at)
V067–V072Soft-delete (deleted_at) across patients, care tasks, contact records, sleep entries, appointments, script fills
V073care_alerts, care_alert_events — in-app care alert system; Web Push (VAPID) removed
V074analytics_dispensing_summary materialised view — pre-computed tenant-partitioned dispensing summary; REFRESH MATERIALIZED VIEW CONCURRENTLY every 5 min via APScheduler
V075scan_jobs — PostgreSQL-native scan job queue replacing Redis LPUSH/BRPOP; pg_notify replaces Redis PUBLISH for SSE result delivery
V076Encrypted shadow columns (_enc, email_idx, enc_version) for PHI fields on patients, users, care_groups; field_crypto.py encrypts Fernet (phi:v1:) on write, decrypts on read
V077condition_archetypes — seven palliative care archetypes grouping patients by dominant coordination challenge (C1a)
V078condition_packs, pack_reason_type_links, pack_shift_task_templates — template bundles tied to archetypes; 2 free starter packs per tenant (C1b)
V079observation_types, pack_observation_type_links, patient_observations — flexible observation type registry replacing hard-coded vitals columns; 7 universal seed types (C1c)
V080help_requests, help_offers — family help-circle coordination (D1a)
V081claimed_by ownership on patient_appointments and shift_tasks — calendar ownership (D1b)
V082body_layer column on patient_pain_entries — pain selector layers: front, back, skeleton, mind, surface (C8)
V083–V088Stream 5 clinical module schema — care observations, goals of care, frailty, behaviour, cognitive assessments, PAINAD pain, swallowing, falls, respiratory, therapy, equipment, journal, patient voice, preventive care, care intelligence (routers pending)
V089PHI field-level encryption extended to tenants: name_enc + enc_version shadow columns added
V090PHI constraints: UNIQUE index on users.email_idx; NOT NULL constraints on email_enc, email_idx, full_name_enc, date_of_birth_enc, name_enc across users, patients, care_groups, tenants
V091PHI plaintext drop: patients.name, patients.dob, users.email, care_groups.name, tenants.name removed — DB stores no readable identity fields; field_crypto.py decrypts all reads
V092patient_pain_entries.body_layer CHECK extended for bone overlay: front-skeleton, back-skeleton (fixes V082 constraint vs PainBodyMapTab)
V093tenant_notification_settings.family_help — care-alert channel for family help board
V094subscriptions_module_check extended to allow family_help module slug
V100care_alerts.metadata JSONB — consolidated overdue-dose miss_count
V101users.phone, profile fields; key-contacts extensions
V102tenant_module_purchase_alerts
V103Merge medicines into patient_scripts; drop medicines router/table (D23)
V104tenants.dek_ciphertext, dek_nonce — per-tenant DEK envelope (REQ-ENC-04 storage; B4)

Post-v1 active migrations (backend/migrations/, run by migrations.runner on app start):

MigrationAdds
V025tenant_account_numbers
V026care_tasks becomes date-scoped: patient_id, date, source_care_profile_slug, source_action_id; shift_id nullable with FK ON DELETE SET NULL; RLS tenant_isolation policy via patients; uq_care_tasks_module_action for idempotent care-module actions
V027Module calendar task structured responses: source_task_id, task_prompt, response_kind, response_code, response_recorded_at, response_recorded_by; partial index on module tasks by patient/date
V028users.login_count — completed sign-in counter (mobile nav onboarding hint; not incremented on refresh bootstrap)

Identity PII is encrypted at the column level before it reaches PostgreSQL using the platform Fernet key (PHI_ENCRYPTION_KEY). Tenant isolation remains tenant_id in SQL, require_tenant_member, and RLS (V034). V104 (2026-06-02) adds per-tenant data encryption keys (DEKs) stored as dek_ciphertext / dek_nonce on tenants, generated by generate_tenant_dek() and provisioned via ensure_tenant_dek() on Stripe checkout, auth tenant create, and schedule backfill — not in routers/tenants.py. Identity columns still use phi:v1: platform encryption today; REQ-ENC-05 (encrypt additional clinical columns with the tenant DEK) is future work. Clinical free-text (e.g. medical_summary) is outside this pass unless noted elsewhere.

Two crypto modules (do not conflate):

ModulePrefixKey envPurpose
services/crypto.pymfa:v1:MFA_ENCRYPTION_KEY or HKDF lyncareos:mfa:v1TOTP secret and backup codes
services/field_crypto.pyphi:v1:PHI_ENCRYPTION_KEY (comma-separated MultiFernet chain) or HKDF lyncareos:phi:v1User email, patient name/DOB, care group name, tenant display name
Blind index (email only)—PHI_BLIND_INDEX_KEY or HKDF lyncareos:phi:idx:v1users.email_idx — HMAC-SHA256 of normalised email (26-char urlsafe base64) for equality lookup without plaintext

Columns (post-V091):

TableStored ciphertext / indexAPI field after decrypt
usersemail_enc, email_idx, enc_versionemail
patientsfull_name_enc, date_of_birth_enc, enc_versionname, dob (legacy names in app layer)
care_groupsname_enc, enc_versionname
tenantsname_enc, enc_versionname

Read path: Routers and auth.get_current_user load encrypted columns only, then call decrypt_user, decrypt_patient, decrypt_tenant, or decrypt_care_group before building Pydantic/JSON responses. auth.USER_COLUMNS lists email_enc, email_idx, enc_version — not plaintext email.

Write path: INSERT/UPDATE use encrypt_field() and email_blind_index(); enc_version = 1. Pre-V091 backfill: python -m migrations.scripts.encrypt_phi_fields (idempotent; requires V076 + V089 columns).

Lookup by email: Login, registration, invites, pending signup, and Stripe provisioning resolve users via email_idx, never plaintext users.email (column dropped in V091).

Primary call sites:

AreaFilePattern
Session userauth.pydecrypt_user in get_current_user, get_mfa_pending_user, SSE ticket path
Login / registerrouters/auth.pyemail_idx lookup; email_enc on INSERT; decrypt_tenant for tenant name in response
Patientsservices/patients_service.py (via routers/patients.py)*_enc columns only; member invite uses email_blind_index
Tenant DEKservices/field_crypto.pyensure_tenant_dek on provision; get_tenant_dek for future REQ-ENC-05
Google OAuthservices/google_auth_service.pyemail_idx lookup; encrypt on new user
Signup guardservices/signup_service.pyduplicate check on email_idx
Stripe checkoutservices/stripe_provisioning.pyemail_enc / email_idx on user; name_enc on tenant
Tenants / users / invitationsrespective routersencrypt on write, decrypt before response
field_cryptoPostgreSQLRouterClientfield_cryptoPostgreSQLRouterClientPOST auth loginSELECT by email blind index HMACrow with email_enc onlydecrypt_user rowuser email plaintext in memory onlyJSON email for UI, never logged

Operational notes:

  • Production should set dedicated PHI_ENCRYPTION_KEY and PHI_BLIND_INDEX_KEY in backend/.env (see config.py comments). Rotating keys: add new key first in comma-separated PHI_ENCRYPTION_KEY; re-encrypt with backfill script.
  • V091 is irreversible — apply only after backfill and code paths verified (backend/scripts/validate_migration.py checks duplicates and decrypt round-trip). V091 carries an in-DB DO $guard$ pre-flight block (added 2026-05-27) that counts enc_version = 0 rows and NULL ciphertext across all four PHI tables, then RAISE EXCEPTIONs and rolls back if any count is non-zero. The guard was added after an incident on lyncareos_dev where V091 ran without the backfill having executed first, dropping the plaintext source columns and permanently losing PHI on 7 of 8 legacy users, 1 of 2 patients, 1 of 2 care groups, and all 4 tenants. Production was not affected (audit 2026-05-27 confirmed all rows encrypted, decrypt round-trip succeeds). See [04 - OPERATIONS/11-DATABASE-SAFETY-AND-MIGRATIONS.md §5](../04 - OPERATIONS/11-DATABASE-SAFETY-AND-MIGRATIONS.md).
  • PHI key pinning is mandatory on production. If only SECRET_KEY is set, services/field_crypto.py derives the Fernet/HMAC keys via HKDF on every boot — that works until SECRET_KEY is rotated, at which point all existing ciphertext becomes permanently undecryptable. .\scripts\production-phi-pin.ps1 writes the derived values to /opt/lyncareos/.env.production and recreates the app + scan_worker containers so the pinned values are loaded. The script is idempotent and was last verified 2026-05-27 20:30.
  • Known limitation: GET /api/patients orders by full_name_enc (lexicographic on ciphertext), not display-name sort order.
PatternType
Primary keysSERIAL
BooleansBOOLEAN
Admin / state flagsSMALLINT (users.is_super_admin, users.must_change_password)
TimestampsTIMESTAMPTZ for audit and created_at / updated_at fields
Calendar / dispensing dates as enteredTEXT (e.g. dispensing date/time, shift date)
VolumesDOUBLE PRECISION (dispensings.volume)

Condition archetypes and the flexible observation system (V077–V079)

Section titled “Condition archetypes and the flexible observation system (V077–V079)”

Migrations V077–V079 introduce a three-layer system that replaces hard-coded vitals columns with a configurable, archetype-driven observation framework. Canonical product spec: Palliative Care Archetypes.md v2.1.

Reconciliation charter: V077–V079 seeds were draft data. Post-v1 reconciliation V006–V010 (2026-06-04) aligns DB to Palliative §2–§3.6 on dev and VPS. Full mapping: Palliative §7.0 · 11-DATABASE-SAFETY §2j–§2k.

Product model:

LayerTable / conceptRole
Archetypecondition_archetypesSeven coordination patterns — onboarding classifier
Care Profile (pack)condition_packsUnlockable template; content in pack_* tables
Care Start applyapply_care_start_pack() in care_start_service.pyIdempotent merge: patient-scoped reason types (reason_types.patient_id, V014), shift templates, care_profile_slug; bootstrap_patient_care_surfaces() in care_start_bootstrap.py — four med slots (medication_groups), sample pain script on paid packs, profile shopping lists (SHOPPING_LISTS_BY_PACK_SLUG in seed_catalog.py); same slots on new patient create; first patient may auto-apply from tenants.pending_care_start_pack_slug (checkout bundle)

condition_archetypes (V077) — seven palliative care archetypes grouped by dominant coordination challenge (not diagnosis). Each archetype recommends Care Profiles from §3.2.1 of the archetypes doc.

condition_packs (V078 + V007) — Care Profile catalogue. Twelve canonical slugs after V007__reconcile_condition_packs (legacy V078 slugs remapped). Tables: condition_packs, pack_reason_types, pack_shift_tasks, pack_observation_type_links, tenant_pack_purchases. Pack content seeded in V008__seed_care_start_pack_content.

observation_types / patient_observations (V079 + V008) — configurable observation registry. Seven universal types ship in V079; archetype-specific and self-care types seeded in V008 per Palliative Care Archetypes §3.4–§3.6. Value types: number, boolean, text, scale_1_5, scale_1_10, choice. Capture widgets: pill_tap, number_input, slider, text_input, visual.

Tenant isolation: patient_observations.tenant_id enforced in all queries. Patient columns (V009): archetype_id, care_profile_slug, care_start_applied_at; apply tracking via patient_applied_care_profiles.


Multi-tenancy, accounts, and patient access (authoritative)

Section titled “Multi-tenancy, accounts, and patient access (authoritative)”

This section is the contract for how subscriber data is isolated and how carers see patients. Implementation lives primarily in backend/auth.py and backend/routers/patients.py.

TermMeaning
Account / tenantOne subscriber organisation. Created when a user registers (or accepts an invite). Billing and subscriptions rows are per tenant.
Tenant administratortenant_memberships.role = 'admin'. Seeded for the account purchaser; can invite users and manage patients for that tenant only.
Tenant membertenant_memberships.role = 'member' (or admin). Must be invited and approved into the tenant.
PatientA person receiving care. patients.tenant_id ties them to exactly one account.
Allocationpatient_access rows: which tenant users may see/act on which patients (role: carer or observer).
  1. No cross-account visibility for tenant admins, carers, or observers. Every tenant-scoped query must use ctx["tenant_id"] from require_tenant_member (or stricter). JWT carries tid; PostgreSQL RLS uses app.current_tenant_id (see migration V034__row_level_security.sql) as defense in depth.

  2. Carers and observers see only patients they have been allocated via patient_access. GET /api/patients for non-admins returns only those rows; patient-scoped routes use require_patient_access / ensure_patient_access.

  3. Tenant administrators (tenant_role admin in context) may see all patients in their tenant without a per-patient patient_access row. This supports account management (register patients, assign carers, oversee care). They still cannot see other tenants’ data.

  4. Platform owner (users.is_super_admin = 1): may use X-Tenant-ID or ?as_tenant= to operate as a tenant (auth.resolve_tenant_id). Cross-tenant listing (e.g. GET /api/users/all) uses require_super_admin. This is the only cross-account operational path for normal product features.

  5. Super admin in tenant context is treated like a tenant admin for patient visibility within the selected tenant (after X-Tenant-ID is set).

  6. Email identity lookups (login, invite-by-email, signup duplicate check) use users.email_idx (blind index), not a plaintext email column — see Field-level PHI encryption (B4).

  7. Multi-tenant user model (REQ-AUTH-12) [Target — Phase E]. A users row is a person; a tenants row is a care account. One person may hold many tenant_memberships. Roles (admin, member) are per-tenant — being a member of one tenant places no constraint on being admin of another. Removing a user from one tenant never affects their other memberships. New-tenant creation by an existing user reuses the users row and creates a new tenants row plus an admin tenant_memberships row. The provisioning engine (services/stripe_provisioning._provision_from_pending_signup) already reuses existing users by email_idx; the gap is the marketing signup gate (services/signup_service.email_available()) and the missing in-app entry point — both are scheduled in 04-ROADMAP.md Phase E.

  8. Active tenant in session (REQ-AUTH-13) [Target — Phase E]. The JWT carries tid (already true today). When a user has multiple memberships, the active tenant is selected at login (default: most recently joined active membership) and may be changed via POST /api/auth/switch-tenant, which re-issues the JWT pair with the new tid. All require_tenant_member / require_module checks apply against that active tid only; exactly one tid is in flight at any time. The tenant switcher in the SPA must invalidate all per-tenant caches (TanStack Query, AuthContext) before swapping in the new tokens to prevent stale-state leakage.

HelperPurpose
require_tenant_memberActive membership on write pool (get_db); sets RLS app.current_tenant_id.
require_tenant_member_readSame membership check on read pool (get_ro_db) — use with analytics/audit/onboarding GET.
require_tenant_adminAdmin or super_admin in context (write path).
require_tenant_admin_readAdmin check on read path (e.g. audit list with get_ro_db_with_rls_admin).
get_ro_db_with_rlsSingle RO connection with RLS GUC; depends on require_tenant_member_read only.
resolve_tenant_idActive tenant from JWT; super-admin override validates tenant row via a short pool borrow (not held for the whole request).
require_patient_access / ensure_patient_accessCarer/observer must have patient_access; admin/super_admin must have patient in tenant.
is_tenant_wide_operatorAdmin or super_admin — may use tenant-wide patient visibility for certain operations.
append_dispensing_patient_scope_for_memberRestricts dispensing/analytics SQL to patients the user may see (non-admins only).
ensure_dispensing_row_access_for_memberSingle dispensing row: member must have access to that row’s patient_id.

  • In scope: FastAPI routers under backend/routers/, core dependencies in backend/auth.py, alignment with the rules in Multi-tenancy, accounts, and patient access above.
  • Out of scope: Exhaustive review of every SQL fragment in large routers; non-HTTP jobs. Frontend was reviewed in the same period (see Frontend access control).
  1. Listed every router mounted in backend/main.py and checked each file for: correct tenant context (require_tenant_member or stricter), patient allocation where the resource is patient-specific (require_patient_access, ensure_patient_access, or inline patient_access SQL), and role expectations (require_tenant_admin, require_carer_role, etc.).
  2. Searched for tenant-scoped routes that aggregate per-patient data without patient_access filtering for non-admin members (the main failure mode for carers/observers).

Authoritative list: include_router calls in backend/main.py and OpenAPI /api/docs. The table below is indicative; new routers must be reviewed the same way.

RouterPrimary dependenciesPatient allocation
authget_current_user, require_approved, public login/register/refreshN/A — identity and tokens only
usersrequire_tenant_admin; GET /all → require_super_adminTenant membership / module overrides — no patient rows without admin
invitationsrequire_tenant_admin; GET /verify/{token} publicAdmin-only CRUD; verify is token-scoped
tenantsrequire_tenant_member, require_tenant_admin, require_super_adminTenant metadata — no clinical rows
subscriptionsrequire_tenant_admin (writes), require_tenant_member (read active)Billing — tenant-scoped
medicinesrequire_tenant_member / admin; REQ-MED-14 GET /api/patients/{id}/medicinesPatient-scoped read for carer pickers
reason_typesGET /api/reason-types?patient_id= + ensure_patient_access; admin writes scoped to that patientPatient-scoped PRN catalogue (V014) — not shared across people in care
dispensingsrequire_tenant_member + helpersRemediated — see below
analyticsrequire_tenant_member_read + get_ro_db_with_rls + SQL scopeRemediated — see below; one pool slot per request (2026-05-30)
auditrequire_tenant_admin_read + get_ro_db_with_rls_adminAdmin-only — no member leak
medication_groupsrequire_patient_access, require_tenant_admin, require_carer_rolerequire_carer_role depends on require_patient_access
patientsrequire_tenant_member / admin vs member queriesAligned — member list joins patient_access; GET /{id}/members uses ensure_patient_access
care_shiftsrequire_tenant_member + ensure_patient_accessRemediated — see below
patient_appointmentsLocal _require_patient_access on each handlerAligned
scriptsrequire_patient_access / require_tenant_admin where appropriateAligned
sleeprequire_patient_accessAligned
vitalsrequire_module("vitals_tracking") + require_patient_accessAligned
pain, mindrequire_module("pain_tracking") + require_patient_access / carer where applicableAligned
pain_settingsAuth + tenant; not module-gated in main.pyTenant settings
shoppingrequire_patient_access on patient routes; ensure_patient_access on selected flowsAligned
key_contactsrequire_module("key_contacts") + require_patient_accessAligned — Family and Complete
admin_shoppingrequire_super_admin / require_tenant_adminCatalog admin — not member clinical data
pwa_authUnauthenticated + rate limitsPWA OAuth handoff — opaque session_id as credential
stripeMix of public (/webhook) and authed (signup, upgrade)Provisioning / billing — see router
billingPublic + authed (get_ro_db for some reads)Tiers/FX for marketing; tenant billing context when logged in
onboardingrequire_tenant_member_read (GET progress), require_tenant_member + get_db (POST steps)Onboarding — tenant-scoped
alertsrequire_tenant_member; admin settings require tenant adminShared open alerts — team-visible per patient
dev_toolsNon-production onlyTest helpers
AreaFindingResolution
Analytics (/api/analytics/*)Dispensing aggregates used tenant_id only. A member could see chart data for patients they were not allocated to.All analytics queries apply append_dispensing_patient_scope_for_member (or mv.patient_id / patient_access in MV-backed CTEs) unless is_tenant_wide_operator.
Active-patient isolation (REQ-MED-15)Member-scope still merged all allocated patients, and admins saw the whole tenant, so selecting one person (e.g. Peter) still showed another’s (Mum’s) trends, analytics, alert badge/inbox, export, and audit.Every dispensing-analytics endpoint, /api/alerts + /api/alerts/open-count, /api/billing/export/download, and /api/audit accept an optional patient_id validated by ensure_patient_access and applied via _scope_dispensings; carer-facing pages always send the active patient and refetch on switch. Export is per-selected-person; audit gains audit_log.patient_id (V099) and defaults to the selected person with an admin “All people” toggle. Tests: tests/test_patient_analytics_isolation.py.
Dispensings (/api/dispensings)List without patient_id returned all tenant rows; GET/PATCH/DELETE by id did not check allocation; POST allowed members to create rows without patient_id.List applies member scope when patient_id is omitted; GET/PATCH/DELETE call ensure_dispensing_row_access_for_member; POST requires patient_id + ensure_patient_access for members, or rejects null patient_id for members.
Care calendar (/api/care-shifts, /api/care-tasks, /api/care-groups/.../members, and related)Generic shift/task routes enforced tenant only; members could target shifts or tasks for patients they were not allocated to.ensure_patient_access (or equivalent) on create/read/update/delete paths that imply a patient_id.
Patients routerGET /{patient_id}/members listed care-team rows with tenant filter only.ensure_patient_access before the query.
RLSV034 policies enforce tenant isolation at the database layer.Keep application checks as primary for patient allocation; RLS as defense in depth.
AreaAssessment
RoutingProtectedRoute requires approved user; ModuleGate enforces subscription modules; AdminGate protects admin URLs; Settings self-redirects non-admins.
Patient listPatientProvider uses GET /api/patients only — members receive allocated patients; empty list shows “No patients assigned yet” (Layout).
API usagelib/api.ts patient-scoped helpers take patientId explicitly; pages use usePatient().activePatient / activePatientId (Log Dose, Calendar, Schedule, Scripts, etc.). No client-side “all patients” merge for members.
Patient-scoped PRN reasonsGET /api/reason-types?patient_id= returns labels for active patient only (Log Dose, History, More → Reason codes). Care Start apply seeds reasons on that person. Switching patient in header refetches — no cross-patient bleed (V014).
History → AuditAudit API is admin-only. Audit tab is shown only to admins (History.tsx) and, per REQ-MED-15, defaults to the selected person (patient_id filter on /api/audit) with an admin “All people” toggle.
Super-adminTreated as having all modules (ModuleContext) and full nav; impersonation uses X-Tenant-ID from server session when using the tenant switcher.
  • tests/test_dispensings.py: member with patient_access to one patient only sees those dispensings; cannot GET another patient’s dispensing (403); cannot POST without patient_id (403).
  • tests/test_care.py: care groups, shifts, tasks, patient-prefixed calendar routes, and test_list_patient_members_requires_allocation (GET /patients/{id}/members).
  • dispensings.patient_id is NOT NULL since V039, so analytics/export/audit patient filters are lossless. audit_log.patient_id (V099) is backfilled from owning tables; hard-deleted-dispensing audit rows keep a NULL patient_id (cannot be rejoined) and only surface under “All people”.
  • New-write audit_log.patient_id population now covers all clinical entity types — dispensing, prescription, script_fill, medication_group, patient, sleep, and (since 2026-05-29) care_shift, patient_appointment, key_contact, and contact_note. Only hard-deleted-dispensing rows that predate V099 keep a NULL patient_id.
  • Shared-device hardening: the active-patient selection is keyed per user in localStorage (lyncareos_active_patient:<userId>) and the patient list reloads when the authenticated user changes, so a selection cannot carry across carers on a shared browser (the backend always enforces access regardless).
  • Export scope: POST /api/billing/export/download is require_tenant_admin. Per-patient export sends patient_id (validated by ensure_patient_access); omitting it (account-cancellation portability) exports the whole account. Non-admins cannot export.
  • Clinical trends (pain, vitals, observations, sleep, mind) are /patients/{patient_id}/... routes guarded by require_patient_access / require_carer_role, so they are inherently single-patient and need no extra scoping.
  • Regression coverage: backend tests/test_patient_analytics_isolation.py; frontend frontend/src/test/components/PatientIsolation.test.tsx; tenant RLS tests/test_rls.py (now exercises encrypted full_name_enc).
  • Periodic re-audit when new routers or major SPA routes are added.

Configured via DB_POOL_MIN / DB_POOL_MAX (defaults 2 and 10 in .env.example; dev backend/.env may override). get_db uses manual transaction boundaries (autocommit=False); rollback on unhandled exceptions. get_ro_db uses autocommit=True on the replica pool (falls back to primary when no DATABASE_READ_URL).

FastAPI caches the same Depends(get_db) or Depends(get_ro_db) generator per request — multiple dependencies that list the same callable share one connection. Different callables (get_db + get_ro_db, or require_tenant_member nested inside get_ro_db_with_rls while the handler also declares require_tenant_member) use separate slots.

SymptomTypical cause
Page hangs ~30 s then 500psycopg_pool.PoolTimeout — pool exhausted; check backend-err.log
Dashboard worst caseMany parallel /api/* calls (medicines, analytics ×2, alerts, dispense view, …) × React StrictMode double-fetch in dev
Fixed 2026-05-30Read routes no longer hold get_db + get_ro_db for the same handler; resolve_tenant_id no longer acquires get_db when tid is only in the JWT

Authoring rule: Read-only handlers that need ctx + get_ro_db_with_rls must use require_tenant_member_read for ctx, not require_tenant_member.


This section summarises the architectural deltas introduced by the “Hardening and Scale-to-100k” plan. Detailed day-2 procedures live in 17-HARDENING-SCALE-RUNBOOK.md.

ConcernBeforeAfter
SSE ticketsIn-memory dict per workerRedis keys with TTL + GETDEL (services/sse_tickets.py)
PWA ↔ Safari OAuth handoffIn-memory dictRedis keyed sessions (services/pwa_auth_service.py)
Shopping pub/subasyncio.Queue fan-outRedis pub/sub (services/shopping_service.py + hooks/useShoppingSync.ts)
Rate limit bucketsIn-memory SlowAPIRedis-backed SlowAPI (middleware/rate_limit.py)
Hot cachesNoneRedis TTL caches for modules / patients / medicines / catalogs (services/cache.py)
Care alertsPer-user inbox + VAPIDPostgreSQL care_alerts + alert_service / routers/alerts.py

All per-worker in-memory state has been removed, so FastAPI can now run with --workers N safely behind any number of container replicas.

  • PgBouncer (transaction pool mode) sits in front of PostgreSQL in Docker Compose (pgbouncer service). The app targets PgBouncer, which funnels DB_POOL_MAX * replicas client connections down to a small fixed backend pool.
  • Optional read replica via DATABASE_READ_URL + get_ro_db. List, analytics, and audit endpoints use the replica when available and fall back to the primary transparently. Default Compose does not ship a second Postgres container — the URL is for an external replica or a custom stack.
  • Per-connection statement_timeout (migration V037) prevents slow queries from holding pool slots under load.
  • Advisory lock around the migration runner (migrations/runner.py) so concurrent app replicas cannot clash during rolling deploys.
  • Refresh token lives in an HttpOnly, SameSite=Lax, Secure-in-production cookie (lyncare_refresh). Access tokens remain in memory on the client. POST /api/auth/logout clears the cookie.
  • MFA TOTP secrets are encrypted at rest with Fernet (mfa:v1: prefix); key from MFA_ENCRYPTION_KEY or HKDF from SECRET_KEY (services/crypto.py).
  • PHI identity fields are encrypted at rest with Fernet (phi:v1: prefix) and email equality via HMAC blind index (services/field_crypto.py). See Field-level PHI encryption (B4). API handlers decrypt only in memory before responding; PHI must not appear in application logs.
  • Constant-time login — bcrypt always runs against a dummy hash for missing or Google-only accounts to close a timing oracle.
  • Rate limits on POST /api/auth/register, POST /api/auth/login, and GET /api/invitations/verify/{token}.
  • SlowAPI key function hashes the JWT signature so bucket keys are bound to the credential, not user-supplied claims.
  • Migration V041 adds Stripe columns on tenants and new stripe_events, stripe_prices, and mapping tables.
  • routers/stripe.py exposes signup (/start-signup, /start-signup-google, /complete-signup, GET /checkout-outcome) with optional Palliative Care Start fields (care_start_pack_slug, care_start_bundle, archetype_slug → Stripe metadata); POST /api/stripe/upgrade-tier, POST /api/stripe/webhook, and related billing helpers. Provisioning: care_start_checkout.provision_care_start_bundle_from_session().
  • routers/care_start.py — POST|GET …/patients/{id}/care-start, PATCH …/care-pattern (module gate condition_templates). Bootstrap: services/care_start_bootstrap.py (med schedule slots, sample medicine, shopping lists); backfill scripts/backfill_care_bootstrap.py for patients applied before bootstrap shipped; catalogue care_start/seed_catalog.py (SHOPPING_LISTS_BY_PACK_SLUG, REASON_MEDICAL_DESCRIPTION_BY_PACK). UI: PatientCareStartWizard (Add Person — demographics only, 2026-06-26); CareProfileQaPanel (dev, user id 1); CarePatternPanel + ArchetypeOnboarding deleted. Care boards: Layout.tsx injects sidebar Cancer board / Breathing board when active patient slug matches and preview flags on; plus CareBoardDashboardChip on Home. Dev QA: scripts/seed_dev_peter_care_qa.py on tenant peter (activates shopping module for list QA).
  • services/stripe_provisioning.py handles first-time tenant / user / subscription creation from a completed Checkout session. Signup sets users.last_active_tenant_id to the provisioned tenant; all provision paths pass Checkout payment_status into module sync when the Stripe subscription is still incomplete.
  • services/stripe_service.sync_subscription_items mirrors Stripe subscription items into subscriptions rows. Price → modules: stripe_tiers / stripe_tier_local_prices, then Stripe Price metadata lyncareos_tier for grandfathered Price ids (2026-05-30), then legacy stripe_price_modules. Repair: scripts/resync_tenant_subscriptions.py.
  • Product delivery manifest (billing/module_delivery.json, loader in billing/module_delivery.py) records live / partial / planned per slug — separate from commercial entitlement in tiers.json. Exposed on GET /api/modules/available as delivery; the Subscriptions page (ModuleAccessRow) must not label partial modules (e.g. condition_templates) as fully subscribed. See 24 §1.2 and 31.
  • services/payment_outcome.py maps Checkout sessions to user-facing outcomes (charged, user_message, stable code) and logs structured payment_outcome lines for operator review.
  • services/tier_resolution.py and services/tier_upgrade_service.py resolve active tier rows and upgrade options. Primary path: join subscriptions.stripe_price_id to stripe_tiers or stripe_tier_local_prices. Fallback (2026-05-27): when price IDs are missing or stale (e.g. test-era IDs after live switchover), infer essential / professional / complete from active module slugs (shopping/pain_tracking → Complete; Family markers → professional; else Essential). GET /api/billing/my-tier and Subscriptions UI depend on this.
  • services/condition_pack_billing.py enforces tier-included packs, purchase guards, and subscription-currency display for pack checkout.
  • POST /api/stripe/complete-signup provisions inline when Stripe reports paid but the webhook has not yet consumed pending_signups, sets last_active_tenant_id, and resyncs from Stripe — reduces stuck signups on /billing/success.
  • require_module(slug) checks subscriptions.status and returns HTTP 402 when the tenant does not hold an active entitlement.

Prescription image scans are enqueued in PostgreSQL (scan_jobs, V075) via services/scan_queue.py (facade over scan_queue_pg.py), claimed with SELECT … FOR UPDATE SKIP LOCKED by workers/scan_worker.py (stale processing rows reclaimed after 30 minutes), and results are delivered via pg_notify / LISTEN to SSE subscribers. Redis is not used for scan durability or result delivery (B6). The API connection is never held during the LM Studio vision-model call.

APScheduler uses an AsyncIOScheduler backed by SQLAlchemyJobStore with per-tenant timezone-aware triggers (services/scheduler.py). Jobs survive restarts and are safe under multi-replica deployments because the store is the single source of truth.

  • Prometheus request metrics, pg_stat_statements, SSE gauges, and scan-queue depth (Sprint 3 observability) — deferred.
  • Multi-region / active-active deployment (Sprint 4+) — deferred until required.
  • Extracting the Shopping module into its own repo — Shopping stays as a bundled family-care module.

Best-practice gap analysis (mobile-first, international standards)

Section titled “Best-practice gap analysis (mobile-first, international standards)”

This section documents the delta between the current implementation and recognised international best practices for a mobile-first, installable healthcare web app. Items are categorised by severity.

GapCurrent stateRecommended approach
Safe-area insets✅ Implemented — Layout.tsx, MobileBottomNav.tsx, MobileTopBar.tsx, Shopping.tsx, and sheet components use env(safe-area-inset-*). index.html has viewport-fit=cover.No action required.
Input font size (iOS zoom prevention)✅ Implemented — frontend/src/index.css @layer base sets input, textarea { font-size: 16px !important; }No action required.
Touch target minimum size✅ Implemented — .btn class sets min-h-[44px]; .input class sets min-h-[48px].No action required.
Offline error pageNone → ✅ Implemented — frontend/public/offline.html (branded page); sw.js caches and serves it as navigation fallback.Done in Sprint 1.4.
GapCurrent stateRecommended approach
WCAG 2.1 AA accessibility@axe-core/playwright added to CI; e2e/a11y.spec.ts created. :focus-visible global ring added.Ongoing — fix violations as they surface in CI.
Manifest display_override✅ Implemented — frontend/public/manifest.json now includes "display_override": ["window-controls-overlay", "standalone"].Done in Sprint 2.7.
Background Sync for deferred mutations✅ Implemented — frontend/src/lib/syncQueue.ts + SW sync handler for /api/dispensings POST failures.Done in Sprint 3.3.
API versioning✅ Implemented — /api/v1/ prefix mounted alongside existing routes in main.py. API_V1 constant in lib/api.ts. 2026-05-21: router prefix doubling fixed for auth, patients, dispensings. Remaining routers may still use prefix="/api" — tracked as D15 / TODO(C3) in main.py (separate from D6 layering, resolved 2026-06-02 for hot paths).Done in Sprint 3.1; bug-fixed 2026-05-21.
Structured logging with correlation IDs✅ Implemented — backend/middleware/request_id.py injects X-Request-ID. JSON logging gated by LOG_FORMAT=json.Done in Sprints 1.5 + 1.6.
React Error Boundaries✅ Implemented — frontend/src/components/ErrorBoundary.tsx wraps every route in App.tsx and NotificationBell in Layout.tsx.Done in Sprint 1.1.
Core Web Vitals targetsBaseline not yet measured.Measure with Lighthouse after Sprint 1 code-splitting lands; target LCP < 2.5 s.
Code splitting / lazy loading✅ Implemented — 22 heavy pages lazy-loaded in App.tsx; all wrapped in lazyWithReload() from lib/lazyWithReload.ts (2026-05-29) so a stale-deploy ChunkLoadError triggers a guarded window.location.reload() rather than surfacing an error-boundary card.Sprint 1.2; resilience 2026-05-29.
GapCurrent stateRecommended approach
Router → Service → Repository layeringComplete — 0 router SQL execute sites (2026-07-17); all routers delegate to services/repositories.D6 Resolved in 32-KNOWN-DEBTS-REGISTER.md; Layer boundaries.
Image optimisation pipeline✅ Implemented — services/images.py now converts all uploads to WebP (quality 85) at save time.Done in Sprint 2.4. Static-asset pipeline (Vite plugin) is a future enhancement.
Placeholder / skeleton screens✅ Implemented — components/ui/Skeleton.tsx added; used on Dashboard, Calendar, Shopping, patient selector.Done in Sprint 2.5.
prefers-reduced-motion✅ Implemented — Global @media (prefers-reduced-motion: reduce) rule in index.css.Done in Sprint 2.2.
Scroll restoration✅ Implemented — <ScrollRestoration /> added to App.tsx.Done in Sprint 2.1.
OpenAPI /api/docs exposure✅ Implemented — docs_url / redoc_url gated to None in production.Done in Sprint 2.8.
Observability (Sentry)✅ Implemented — sentry-sdk[fastapi] (backend) and @sentry/react (frontend) initialised. PHI-safe (no session replays).Done in Sprint 1.3.
Biometric / WebAuthnNot presentFuture: navigator.credentials (Passkeys / FIDO2) as a supplement to TOTP MFA. No immediate requirement.
ItemStatus
Design tokens as CSS custom properties✅ Added to index.css :root — --color-brand-*, --color-slate-* key tokens. chartTheme.ts updated to use getComputedStyle lookups.
Focus-visible styles✅ Global :focus-visible ring rule added to index.css @layer base.
Typography scale✅ Documented in docs/03-DESIGN-SYSTEM.md; named fontSize extensions added to tailwind.config.js.
Motion designStandard easing tokens deferred to Sprint 3 follow-up. prefers-reduced-motion global rule is the primary mitigation.

Internationalisation architecture [Target — §7.35]

Section titled “Internationalisation architecture [Target — §7.35]”

LynCareOS is designed for global deployment. The i18n architecture distinguishes between frame (UI strings translated by the app) and content (user-entered data, stored and displayed as-is in the original language). See 02-REQUIREMENTS.md §7.35 for the full requirements.

The UI default locale is en-AU; fr-FR is enabled for engineering QA (locales.config.json). Full locale rollout (marketing, Wave 1b) remains roadmap work — see doc 03 and §Internationalisation target.

Backend i18n

Translation Key Convention

Frontend i18n Stack

react-i18next

+ i18next

Namespace files

/locales/{lang}/{ns}.json

common , clinical , modules

locales.config.json

date format , time format

number format , emergency numbers

terminology overrides , locale inheritance

Intl.DateTimeFormat

Intl.NumberFormat

Intl.RelativeTimeFormat

Clinical View Toggle

clinical_view = true/false

per user preference in localStorage

key → plain language

e.g. t('pain.score_label')

= 'How much pain?'

key_clinical → clinical terminology

e.g. t('pain.score_label_clinical')

= 'NRS Pain Score 0-10'

Backend locale

notification templates

API error messages

email bodies

per-request Accept-Language header

Canonical path: frontend/src/locales/ (Vite imports / lazy chunks at build). Do not use frontend/public/locales/ for app UI strings.

Implementation order: 03-REQUIREMENTS-INTERNATIONAL-LANGUAGE.md §2.1 — I18N-P0 en-AU framework → I18N-P1 fr-FR + switcher → I18N-P2a/P2b plug-in Wave 1b locales.

frontend/src/locales/
├── locales.config.json
├── en-AU/
│ ├── common.json
│ ├── clinical.json
│ ├── errors.json
│ ├── notifications.json
│ └── modules/ optional — large domains only
│ ├── medication.json
│ └── care_calendar.json
├── fr-FR/ I18N-P1 — first plug-in proof
│ └── ... (same structure)
├── es-ES/, de-DE/, ... I18N-P2a/P2b — plug-in only
├── ar/, hi/ Wave 2 (RTL / script gates)
└── ja/, ko/, zh-TW/ Wave 3

Plain language vs clinical terminology toggle

Section titled “Plain language vs clinical terminology toggle”

The dual-key convention supports a per-user Clinical View Toggle (REQ-I18N-18). All clinical translation keys exist in two variants:

KeyRendered for carers/familiesRendered when clinical toggle is on
pain.score_label“How much pain?”(toggle off — default)
pain.score_label_clinical—“NRS Pain Score 0–10”
vitals.spo2“Oxygen level”“SpO₂ (%)”
medication.prn“When needed”“PRN”

The toggle state is stored in localStorage as clinical_view and read by a custom useClinicalView() hook that selects the appropriate key suffix.

Locale configuration (locales.config.json)

Section titled “Locale configuration (locales.config.json)”
{
"en": {
"dateFormat": "DD/MM/YYYY",
"timeFormat": "HH:mm",
"firstDayOfWeek": 1,
"emergencyNumber": "000",
"currency": "AUD",
"terminology": {}
},
"en-US": {
"inherits": "en",
"dateFormat": "MM/DD/YYYY",
"emergencyNumber": "911",
"currency": "USD",
"terminology": {
"carer": "caregiver",
"disability_support_coordination": "care coordination services"
}
},
"ar": {
"inherits": "en",
"dir": "rtl",
"dateFormat": "DD/MM/YYYY"
}
}
  • CSS logical properties (margin-inline-start, padding-inline-end, etc.) must be used for all directional spacing in new components.
  • <html dir="..."> is set from locales.config.json on locale change.
  • User-entered text input fields use dir="auto" so Arabic or Hebrew input renders correctly even in an LTR-default locale (REQ-I18N-20).
  • Existing components use physical CSS properties — these will be migrated progressively as RTL languages are introduced.
  • Notification templates and email bodies are stored per-locale in backend/locales/{lang}/notifications.json.
  • The backend reads the tenant’s preferred locale (from tenants.locale column) for outbound messages.
  • API validation error messages are translated via a locale parameter on the HTTPException detail dict — the frontend resolves them through i18next.
TableColumnPurpose
tenantslocale TEXT DEFAULT 'en-AU'Tenant default UI locale and backend notification locale; does not imply PHI storage region
userslocale_override TEXTPer-user locale override (null = use tenant default)
TierScopeQuality requirement
1UI chrome (nav, buttons, labels, generic error messages)Professional human translation required
2Plain-language clinical content (symptom labels, care notes prompts, module names)Human translation with lay-carer review
3Standardised validated scales (MMSE, NRS, Abbey Pain Scale)Use only officially published and validated translations; do not translate independently

Native app strategy: Capacitor [Target — §7.36]

Section titled “Native app strategy: Capacitor [Target — §7.36]”

The native app strategy is a Capacitor-first approach. The existing React/Vite SPA is wrapped in a Capacitor WebView and distributed through Google Play first, then the Apple App Store. No framework rewrite is required.

Design authority: 2026-08-06-native-store-clients-design.md (commerce posture, client matrix, store UX rules, auth notes).

Commerce posture (REQ-NATIVE-08…10) — authoritative

Section titled “Commerce posture (REQ-NATIVE-08…10) — authoritative”
RuleDetail
System of recordWebsite Stripe (Checkout, Customer Portal, Care Profile purchase) + existing webhooks → tenant tier / module entitlements
Store binariesFree, consumption-only — login / free signup / use entitled modules; no Stripe Checkout, payment WebViews, or payment portal deep links
Upgrade messagingInformational copy only in store builds (e.g. “Go to lyncareos.com to upgrade”) — must not lead to an alternate payment method
Tenant unlockAdmin purchase on website unlocks modules for the whole care circle (unchanged)
Optional laterPlay Billing / StoreKit / Billing Choice only with PO sign-off (REQ-NATIVE-12)

Store clients free

PostgreSQL

Website

Stripe

Tenant entitlements

Android Play

iOS App Store

The native build is initiated when any of the following conditions are met:

  • In-app alert engagement or home-screen install rate on iOS PWA materially impacts retention (measured via analytics).
  • HealthKit / Health Connect integration is formally prioritised on the product roadmap.
  • App Store / Play Store distribution is chosen as a primary growth channel (product owner may start Play-first earlier than other triggers).

Backend unchanged

Capacitor Plugins - Target

Build Pipeline - Target

Vite build

React SPA to dist/

npx cap sync

Copies dist to ios and android assets

Xcode build

to iOS .ipa App Store

Gradle build

to Android .aab Play Store

@capacitor/push-notifications

APNs + FCM mirror care_alerts

Target native only

@capacitor/camera

replaces file input for photo capture

@capacitor/preferences

secure native key-value / session material

@capacitor/haptics

feedback on critical clinical actions

@capacitor-community/health-kit

Apple HealthKit read SpO2 HR steps

@capacitor-community/health-connect

Google Health Connect read SpO2 HR steps

FastAPI

identical API relative URLs

/api with credentials include

HttpOnly refresh cookies are origin-scoped to the web app. Capacitor implementation must either live-load the production origin or provide a native-safe session path via tokenStore + secure native storage. OAuth must use a system browser / Capacitor Browser pattern — not in-WebView-only Google sign-in. See design §7.2.

Architecture preservation rules (REQ-NATIVE-06)

Section titled “Architecture preservation rules (REQ-NATIVE-06)”

These rules must be maintained in the SPA codebase to ensure the native build works without modification:

RuleRationale
All API calls use relative URLs (/api/...) or VITE_API_URL env varCapacitor’s WebView resolves relative URLs against the configured server.url; absolute URLs break in-app routing
Auth tokens stored via tokenStore abstraction (in-memory access + HttpOnly cookie)Native builds need a single swap point for secure storage when cookies are unavailable
No direct window.location for authenticated downloadsUse useAuthenticatedImage hook (fetches with auth headers, returns blob URL); direct href downloads bypass the auth token in native
Browser globals (window, navigator, localStorage) wrapped or feature-detected@capacitor/device and @capacitor/preferences are drop-in replacements; direct browser globals may not be available in the WebView
CSS env(safe-area-inset-*) in LayoutAlready implemented — required for iPhone notch and Dynamic Island clearance
Billing / upgrade CTAs feature-gated for store buildsREQ-NATIVE-08/10 — website keeps full Stripe UX

When the native app is released:

  1. PWA users continue with in-app alerts + icon badge only.
  2. Native installs register APNs/FCM tokens; open care_alerts optionally mirror to lock screen.
  3. PostgreSQL care_alerts remains authoritative — native push is a nudge, not a second inbox.
RequirementApproach
Google Play first, then AppleFree listings; Health & Fitness / family-support framing
Listing policyPosition as family support / care coordination, not a medical app. Description must not claim to diagnose, treat, or cure.
Privacy policyMust explicitly describe all data collected, stored, and processed, including family data and care records.
No medical device claimAll care data entry is presented as family care record-keeping, not medical advice — enforced in listing copy and in-app disclaimers
PaymentsConsumption-only store clients (REQ-NATIVE-08); do not lead users to Stripe from the binary
Privacy / security controls (not regime readiness)Single-region Postgres, deletion-on-cancellation, audit log, and PHI-safe logging are implemented as engineering controls. LynCareOS does not claim GDPR-ready or HIPAA-ready status — see 26 — Regulatory applicability.

React Native evaluation gate (REQ-NATIVE-07)

Section titled “React Native evaluation gate (REQ-NATIVE-07)”

If Capacitor has specific limitations that block a required user experience (e.g., complex camera pipeline, biometric authentication, Bluetooth peripheral access), a React Native (Expo) evaluation should be triggered. The evaluation criteria are:

  • Does the required native capability have a stable Capacitor plugin?
  • Is the Capacitor plugin actively maintained with iOS 18+ / Android 15+ support?
  • If no — evaluate React Native with shared business logic extracted into a packages/core workspace.

A React Native rewrite is not the default path and should only be chosen if Capacitor cannot deliver two or more required native capabilities.


Type system and API contracts [REQ-PLAT-10]

Section titled “Type system and API contracts [REQ-PLAT-10]”

Status (repo audit, 2026-07-31): Phase B1 shipped the contract pipeline; adoption across routes and the React app is partial and growing. Do not treat “OpenAPI exists” as “types are generated end-to-end.”

All figures below are counted from the repository, not estimated. Re-measure before citing them.

LayerWhat the code does
Backend wire modelsPydantic models in backend/models.py plus additional models on routes and in services/* (e.g. PatientCreate in patients_service.py). Request bodies on routes are usually typed; most responses are not — handlers return dicts/rows without response_model or a -> Model return annotation.
OpenAPI artefactbackend/scripts/export_openapi.py imports main.app and writes committed openapi/openapi.json — 399 /api paths, 517 operations, 132 component schemas.
Response typing in OpenAPI36 @router.* decorators set response_model=, across 10 router files. 73 of 517 /api operations (14%) expose a named 2xx response schema; the rest document empty or generic responses even when JSON is returned.
Generated TypeScriptnpm run generate:types → frontend/src/lib/api.types.ts (~30k lines, committed). CI job openapi-contracts fails if openapi.json or api.types.ts drift after export/regenerate.
Stable aliasesfrontend/src/lib/api.contracts.ts — 66 export type X = Schema<'X'> aliases. Still mostly create/update bodies, but now including response shapes (DatedCareTask, CalendarAction, CalendarActionsDay).
What the UI imports169 frontend/src/** files import from lib/api.ts. Only two files import api.contracts.ts directly — lib/api.ts and lib/types/care.ts — so api.ts remains the de facto import surface for feature code.
Manual response typesapi.ts still defines 72 export interface types (e.g. Patient, User, CareAlert, analytics aggregates) that are not tied to OpenAPI response schemas. Comment in source: “manual until response_model covers the endpoint.”

Fully response_model-backed routers (every endpoint): alerts.py (6/6), routers/care_tasks.py (2/2), care_modules/routers/calendar_actions.py (4/4).

Partially covered: scripts.py (5/13), medication_groups.py (5/18), patients.py (4/12), dispensings.py (4/5), reason_types.py (3/4), auth.py (2/16), dev_tools.py (1/2).

No response coverage: 30 of 40 router files.

Request-only coverage: Many modules expose Pydantic request models in OpenAPI (shopping, care calendar creates, etc.) while responses stay manual on the frontend.

Why partial adoption is a correctness risk, not just tidiness

Section titled “Why partial adoption is a correctness risk, not just tidiness”

Where a response has no response_model, the frontend type is hand-written and nothing verifies it against the database. In July 2026 DatedCareTask was hand-declared with completed: 0 | 1 against a Postgres BOOLEAN; task.completed === 1 was therefore never true and the care calendar rendered every completed task as outstanding. Writes succeeded, so the data was correct and only the UI lied.

Neither gate caught it: check:types-drift only compares generated output against openapi.json, and an endpoint absent from OpenAPI cannot drift. tsc was satisfied because === 1 is valid against a 0 | 1 declaration. The fix was to give those endpoints response_model= and generate the type. Treat a hand-written response interface as unverified until it is.

Target architecture (same section, desired end state)

Section titled “Target architecture (same section, desired end state)”

Pydantic wire models

models.py + services

FastAPI routes

response_model on public APIs

export_openapi.py

openapi/openapi.json

openapi-typescript

npm run generate:types

api.types.ts

auto-generated

api.contracts.ts

Schema aliases

api.ts

transport only

Pages / components

CI openapi-contracts

  1. Export (from backend/): python scripts/export_openapi.py → openapi/openapi.json.
  2. Generate (from frontend/): npm run generate:types → src/lib/api.types.ts.
  3. Alias: add export type Foo = Schema<'Foo'> in api.contracts.ts when the schema exists in OpenAPI.
  4. Adopt: import from api.contracts.ts in helpers and feature code; re-export from api.ts only for backward-compatible import paths.
  5. Verify: npm run check:types-drift locally; CI openapi-contracts (see .github/workflows/ci.yml).

Live schema (dev): GET /openapi.json (FastAPI default; app on port 8021 in local dev).

  • api.types.ts — generated only; never hand-edit.
  • openapi/openapi.json — committed; CI diffs after export.
  • api.ts — must not redefine types that already exist as Schema<'…'> in api.contracts.ts.
  • New or changed response shapes — add/extend Pydantic response models and response_model= on the route (or typed return annotation FastAPI can emit), then regenerate; delete the matching manual interface in api.ts.
  • UI-only types (form state, chart buckets) — lib/types/<domain>.ts; must not duplicate wire fields.

Adoption backlog (architecture — not sprint ledger)

Section titled “Adoption backlog (architecture — not sprint ledger)”

Finish the partially covered routers first — scripts.py, medication_groups.py, patients.py and auth.py carry the most traffic and the widest gap between typed and untyped endpoints — so OpenAPI 2xx schemas and api.ts manual interfaces converge. Prefer completing a router over scattering single decorators: a router at 100% lets its manual interfaces be deleted outright. Tracker: 04-ROADMAP B1; requirement text: 02-REQUIREMENTS REQ-PLAT-10.


  • Optional SQLite import tooling: backend/scripts/ when migrating from a legacy SQLite file