LynCareOS — Architecture
Version: 3.62
Last Updated: 2026-08-06 13:33:14
Purpose
Section titled “Purpose”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.tsare in the quality gate (REQ-PLAT-10 / B1). High-traffic clinical routes useresponse_model=; remaining hand-written interfaces inlib/api.tsare documented as pending migration (see Type system and API contracts). Layering: every router is SQL-free; services are HTTP-free exceptservices/http_errors.py(ADR 0001AuditContext). - 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.
Architecture evolution: current to target
Section titled “Architecture evolution: current to target”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.
Current state (live)
Section titled “Current state (live)”| Layer | Posture |
|---|---|
| Delivery | One FastAPI application serves a React PWA (browser install). No App Store native shell yet. |
| Domain coverage | Eleven 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. |
| Awareness | Care 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. |
| Contracts | Pipeline 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. |
| Locale | en-AU default; fr-FR enabled for app QA (react-i18next). |
| Persistence | PostgreSQL is system of record; Redis supports cache, rate limits, and pub/sub — not prescription-scan durability. |
| Security | Tenant 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. |
| Analytics | Dashboard aggregates prefer a refreshed materialized view; some timelines still read live transactional rows. |
| Async work | Prescription scanning is a database-queued pipeline (claim, worker, notify/stream) rather than holding API connections during vision inference. |
| Code structure | Router → 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. |
Target state (roadmap)
Section titled “Target state (roadmap)”The target architecture adds four major capability layers on top of the current foundation without replacing it. Each layer is independently deliverable.
Progression summary
Section titled “Progression summary”| Dimension | Current | Target |
|---|---|---|
| Client delivery | PWA (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 awareness | In-app alerts + icon badge (Badging API) | In-app alerts + optional native push (APNs/FCM) when Capacitor ships |
| Module coverage | 8 built modules | 8 built + 15 Future modules |
| UI language | English only | 11 Wave-1 languages + RTL readiness (react-i18next) |
| Frontend type contracts | B1 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-backed | Every 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 data | Not available | HealthKit / Health Connect read via Capacitor plugin |
| App Store presence | None (direct web install only) | Free Google Play + Apple App Store listings (Capacitor); paid features unlocked via website entitlements |
| Commerce | Stripe on web | Unchanged Stripe SoT on web; store builds hide payment CTAs (REQ-NATIVE-08/10) |
| Distribution model | Direct (single region, AU operations host) | Direct + country operator tier (operator_tenants) |
Production topology at a glance
Section titled “Production topology at a glance”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.
Key points:
- One Dockerfile (
backend/Dockerfile) builds theappimage; production hostsdocker compose … build appon the VPS (or a future CI push). - Postgres data lives on a 50 GB block volume at
/data/pgon 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 theappservice on the VPS. Private-beta gate:marketing/palliative/_worker.jsreads Cloudflare Pages envPREVIEW_SECRET(workstationMARKETING_PREVIEW_SECRETin.env.production, synced byscripts/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.
Software development stack
Section titled “Software development stack”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:
| Area | Technology | Notes |
|---|---|---|
| Language (backend) | Python 3.11+ | Match production: Docker image uses Python 3.12 (backend/Dockerfile). |
| API framework | FastAPI 0.115.6 | App entry: backend/main.py. Async throughout; OpenAPI at /api/docs and /api/redoc. |
| ASGI server (local dev) | Uvicorn with reload | Started via backend/run_server.py — binds 127.0.0.1:8021 on Windows with reload=True. |
| Database | PostgreSQL 16 | Started with Docker Compose (postgres service only for typical dev). Host port 5432. |
| DB driver | psycopg v3 | psycopg[binary,pool] — AsyncConnectionPool in backend/database.py. |
| Language (frontend) | TypeScript ~5.9 | frontend/tsconfig + tsc -b in production build. |
| UI | React 19, Vite 8 | Dev server default port 5173 (VITE_PORT overrides). |
| Styling | Tailwind CSS 3.4, PostCSS, Autoprefixer | frontend/tailwind.config.js, frontend/src/index.css. Dark-mode via class strategy. |
| Design tokens | Custom brand.* + lyn.* palette | tailwind.config.js — sky-blue brand, slate-based panels. See 03-DESIGN-SYSTEM.md. |
| Routing | React Router 7 | frontend/src/App.tsx. |
| Charts | Apache ECharts 6 | echarts, echarts-for-react; theme helpers in frontend/src/lib/chartTheme.ts. |
| Date utilities | date-fns 4.x | Date formatting, arithmetic, and locale helpers throughout the app. |
| Vision AI (prescription scanning) | LM Studio — Qwen2.5-VL 7B | Local 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]), bcrypt | Access + refresh tokens; optional Google sign-in (google-auth on the server; client uses OAuth2 implicit redirect to /login + hash, or PWA handoff on iOS). |
| MFA | pyotp (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 rest | cryptography Fernet + HMAC blind index | Identity fields in DB via services/field_crypto.py (phi:v1:); see Field-level PHI encryption (B4). |
| HTTP client (backend) | httpx 0.27 | Used for LM Studio inference and external HTTP calls. |
| HTTP client (frontend) | fetch | Centralised in frontend/src/lib/api.ts (no React Query / TanStack Query in this repo). |
| Modal / list UX | Headless UI 2 | Dialog, Listbox in frontend/src/components/ui/Modal.tsx, Select.tsx. |
| Icons | Lucide React 1.x (primary), @heroicons/react 2.x (secondary) | Navigation and UI icons. |
| UI motion | motion 12.x | Discrete 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 UI | body-muscles, react-muscle-highlighter | Muscle highlighter SVG for pain body-map page (PainTracking.tsx). |
| Image crop | react-advanced-cropper 0.20.x | Profile photo and prescription image upload cropping. |
| Drag-and-drop | @dnd-kit/core, @dnd-kit/sortable, @dnd-kit/utilities | Medication schedule management (MedicationSchedule.tsx). |
| Background jobs | APScheduler 3.10 (AsyncIOScheduler) backed by SQLAlchemyJobStore | services/scheduler.py — per-tenant 06:00 local timezone-aware jobs (shopping list reset, etc.). Jobs survive restarts; safe under multi-replica deploy. |
| Caching | Redis (via redis==5.2.0 and services/redis_client.py) | SSE tickets, rate limits, shopping pub/sub, hot-caches (modules, patients, medicines, catalog). |
| Rate limiting | slowapi — Redis in production, memory:// in dev | middleware/rate_limit.py. Avoids ~2s Redis connect penalty per request when Redis is stopped locally. JWT signature hashed for bucket keys. |
| Care alerts | PostgreSQL care_alerts + APScheduler | alert_service, alert_scheduler, routers/alerts.py |
| Billing | stripe==11.4.1 | Checkout sessions, webhooks, upgrade flows. |
| Crypto | cryptography==44.0.0 | Fernet for MFA (crypto.py) and PHI (field_crypto.py); HKDF key derivation for both. |
| PWA / Service Worker | Custom sw.js (cache-first app shell, network-only API) | frontend/public/sw.js; installable via manifest.json. See PWA and Mobile section. |
| Dark / light mode | ThemeContext | Three states: light, dark, system. localStorage persistence; CSS class toggling on <html>. |
| Local orchestration | PowerShell | dev-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-asyncio | backend/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, Playwright | frontend/ — 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:
- UAT / rehearsal on a non-production machine —
docker-compose.yml, profileproduction, volumes on that PC. - Production — the same
docker-compose.ymland profile on the operations host that serveshttps://app.lyncareos.com, with livelyncare_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.
Services
Section titled “Services”| Service | Image / build | Role |
|---|---|---|
postgres | postgres:16-alpine | Primary 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. |
pgbouncer | edoburu/pgbouncer:latest | Connection pooler; app and scan_worker use DATABASE_URL → pgbouncer:5432. |
redis | redis:7-alpine | SSE tickets, rate limits, cache, shopping pub/sub (scan queue is Postgres-native). |
app | Build: backend/Dockerfile (context: repository root) | FastAPI + built React SPA (single origin). Profile: production only — see below. |
scan_worker | Same image as app; python -m workers.scan_worker | Prescription image scan pipeline (Postgres scan_jobs queue + uploads volume). Profile: production. |
Volumes and persistence
Section titled “Volumes and persistence”| Volume | Used by | Purpose |
|---|---|---|
lyncare_pg_data | postgres | All 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_uploads | app, scan_worker | Mounted 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). |
Configuration wiring
Section titled “Configuration wiring”appusesenv_file: backend/.envso local and containerised runs can share the same keys (secrets,LMSTUDIO_*, pool sizes, etc.).- Compose overrides
ENVIRONMENT=production,DATABASE_URL=postgresql://…@postgres:5432/…, andUPLOADS_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.
Application image (backend/Dockerfile)
Section titled “Application image (backend/Dockerfile)”Multi-stage build:
- Stage
build-frontend:node:22-alpine,npm ci,npm run build→ static assets in/app/frontend/distinside the build stage. - Stage
app:python:3.12-slim, installslibpq5,pip install -r requirements.txt, copiesbackend/to/app, copies frontend build to../frontend/distrelative to backend (i.e./frontend/distfrom 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.pymounts/assets(and/iconsif present) fromfrontend/distand uses an SPA fallback so client routes resolve toindex.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:
docker compose --profile production up -d --buildThe 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).
Edge, TLS, and public access
Section titled “Edge, TLS, and public access”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)”| Dependency | Role |
|---|---|
| PostgreSQL | Required — same Compose service or external DSN via DATABASE_URL. |
| Redis | Required — rate limits, SSE tickets, pub/sub, caches. |
| Stripe | Required 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. |
Runtime topology
Section titled “Runtime topology”⚠️ 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 │└────────────────────────────────────────────────────────────────────────────┘LM Studio (prescription scanning)
Section titled “LM Studio (prescription scanning)”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_workeronly (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_workerclaims rows, calls LM Studio, and publishes results viapg_notifyto SSE subscribers (services/scan_queue_pg.py/scan_queue.pyfacade) so the browser never holds an open HTTP connection during model inference.
Local development detail
Section titled “Local development detail”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.pyanddev-start.ps1. cookieDomainRewriteon the proxy ensures thelyncare_refreshHttpOnly 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, notificationsBackend application
Section titled “Backend application”Lifespan and database
Section titled “Lifespan and database”On startup (main.py lifespan):
open_pool()— opens the primary psycopg AsyncConnectionPool and, ifDATABASE_READ_URLis set, the read-replica pool.init_db()— on a greenfield database (nopublic.tenants), appliesbackend/schema/lyncareos_v1_baseline.sqlonce, then runs the migration runner (migrations/runner.py), then ensuresUPLOADS_DIRexists and appliesbackend/schema.sql(idempotentCREATE TABLE IF NOT EXISTS/ indexes). On brownfield hosts (existing dev/VPS), baseline is skipped; only pending active migrations run, thenschema.sql. Migrations-before-schema prevents startup failure whenschema.sqlreferences columns added only in a pending migration (e.g.audit_log.patient_idfrom V099). The runner holds an advisory lock so concurrent replicas cannot clash on rolling deploys.- Stripe price-map seed — reads
STRIPE_PRICE_MAPenv and populates thestripe_pricesmapping (non-fatal). - APScheduler start —
services/scheduler.py,AsyncIOSchedulerbacked bySQLAlchemyJobStore(PostgreSQL). Per-tenant 06:00 local-timezone triggers (e.g. recurring shopping list reset viaservices/shopping_service.py). Jobs survive restarts. - SSE ticket cleanup task (no-op — Redis TTL + GETDEL handles eviction). Task kept for compatibility.
- Yield → serve requests.
- 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)”- SlowAPIMiddleware — Redis-backed rate limiter (JWT-signature-keyed buckets).
- 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-Policyon all API/SPA responses (default-src 'self';frame-ancestors 'none'; Stripeconnect-srcwhere needed). - CORSMiddleware —
ALLOWED_ORIGINSfrom config;allow_credentials=True; allowed headerX-Tenant-ID; exposed headerX-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.
HTTP surface
Section titled “HTTP surface”- API prefixes (all JSON unless noted): routers use paths under
/api/...:
| Router file | Path 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), CRUD | medication_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 endpoints | medication_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}/sleep | sleep_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 routes | shopping |
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-settings | require_tenant_member / admin |
dev_tools.py | /api/dev/* | Non-production only |
care_modules/routers/status.py | /api/care-modules/status | CARE_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.
Module gating
Section titled “Module gating”require_module(slug) checks subscriptions for active or trial status and returns HTTP 402 when the tenant lacks an active entitlement.
Care Module plugins (feature-flagged)
Section titled “Care Module plugins (feature-flagged)”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.
| Gate | Config | Default (production) |
|---|---|---|
| Server | CARE_MODULE_BOARDS_ENABLED in backend/config.py | false |
| Preview users | CARE_MODULE_PREVIEW_USER_IDS (comma-separated) | 1 |
| Frontend build | VITE_CARE_MODULE_BOARDS=true in frontend/.env | omitted / false |
| Runtime (per user) | GET /api/subscriptions/active → feature_flags.care_module_boards | deploy 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:
| Path | Role |
|---|---|
backend/care_modules/flags.py | Deploy + preview user gate |
backend/care_modules/routers/status.py | GET /api/care-modules/status |
backend/care_modules/routers/board.py | Board state, capture events, settings patch, visit prep, dashboard chips, dashboard-panel, comfort-checkin date/average/snapshot |
backend/care_modules/services/cancer_hub_service.py | Hub 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.py | Home Care board panel — status chips + actions_for_today + treatment_modes icon rows |
backend/care_modules/services/comfort_checkin_service.py | Date-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.py | Abbreviated story.lines builder for oncology visit prep (CANC-H01) |
backend/care_modules/services/board_service.py | Manifest + zone + hub payload for cancer_at_home |
backend/care_modules/services/calendar_actions_service.py | Manifest calendar_actions: apply/undo date-scoped tasks, range read, audit on apply/undo |
backend/care_modules/calendar_task_manifest.py | Normalizes manifest tasks[] (object or legacy string) → id, title, prompt, response_kind |
backend/care_modules/calendar_task_responses.py | Allowed response_kind → option codes; validates PATCH response_code |
backend/care_modules/routers/calendar_actions.py | Gated calendar action endpoints (require_care_module_access) |
backend/repositories/care_tasks.py | Date-scoped care_tasks SQL (V026 apply; V027 response columns on read/write) |
backend/care_modules/manifest_loader.py | Loads manifests/{slug}.json; mtime-keyed lru_cache so manifest edits apply without API restart |
backend/care_modules/cancer_board_visual.py | Tile/mode/day icon keys, enrich_tiles(), telemetry + breakthrough sparkline on hub tiles |
backend/care_modules/cancer_defaults.py | Day types, treatment modes, checklist defs, PRIMARY_SITE_TIPS, ONCOLOGY_APPOINTMENT_TYPES |
backend/repositories/care_module_settings.py | care_module_patient_settings CRUD |
backend/care_modules/manifests/*.json | Pack UI manifest + capture_sessions per slug |
backend/migrations/V011__care_module_events.sql | Event log table |
backend/migrations/V012__cancer_at_home_marketing_copy.sql | condition_packs.description + feature_bullets for cancer_at_home |
backend/migrations/V015__care_module_patient_settings.sql | Per-patient hub JSONB (today_day_type, checklists, visit prep questions, visit_prep_discussed) |
backend/migrations/V016__patient_appointments_oncology_type.sql | Optional appointment_type on patient_appointments (IV infusion, labs, clinic review, …) |
backend/migrations/V026__care_tasks_date_scoped.sql | Date-scoped module tasks; RLS on care_tasks; idempotent apply index |
backend/migrations/V027__care_task_module_responses.sql | Structured 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:
| Path | Role |
|---|---|
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.ts | Shared red→green health gradient for comfort radar web and dots |
frontend/src/components/dashboard/CareBoardDashboardPanel.tsx | Home Care board card — dashboard-panel API; CareProfileIconStrip (540px layout) |
frontend/src/pages/calendar/CalendarFocusDayPanel.tsx | Focus-date calendar_actions + module task response buttons (CAL_LIST_ROW styling) |
frontend/src/lib/calendarModuleTaskResponses.ts | Frontend mirror of calendar_task_responses.py option sets |
frontend/src/components/calendar/ModuleTaskResponseButtons.tsx | Tappable answers per module task row |
frontend/src/components/dashboard/CareActionsForTodayBlock.tsx | Deleted 2026-07-31 — replaced by calendar focus-day panel |
frontend/src/components/dashboard/CancerTodayStrip.tsx | Legacy 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.tsx | GET /api/subscriptions/active — modules + feature_flags.care_module_boards |
frontend/src/context/CareModuleFlagsContext.tsx | useCareModuleFlags() 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 slug | Status | Gated features |
|---|---|---|
medication_dispensing | Built | Medicines, reason types, dispensings, analytics, audit, medication schedule (auto-dispense) |
care_calendar | Built | Patients, care shifts (groups, shifts, tasks), patient appointments |
prescription_management | Built | Patient scripts, fills, scan, images, alerts — routers/scripts.py |
sleep_tracking | Built | Sleep pattern API — routers/sleep.py |
vitals_tracking | Built | Vitals (BP, SpO2, weight, temp, etc.) — routers/vitals.py |
pain_tracking | Built | Body-map pain, mind tracking — routers/pain.py, routers/mind.py |
shopping | Built | Patient shopping lists + catalog consumer API — routers/shopping.py |
key_contacts | Built | Patient key contacts — routers/key_contacts.py (Family and Complete) |
care_observations | Future | Structured shift observation records and body-map skin integrity — routers/care_observations.py |
therapy_records | Future | Physiotherapy, occupational therapy, and speech therapy sessions — routers/therapy_records.py |
equipment_management | Future | Equipment register, servicing schedule, loan tracking — routers/equipment.py |
goals_of_care | Future | Goals of care, advance care planning, escalation directives — routers/goals_of_care.py |
clinical_episodes | Future | Hospital admissions, crisis episodes, infections — routers/clinical_episodes.py |
caregiver_wellbeing | Future | Carer stress, fatigue, burnout logs — routers/caregiver_wellbeing.py |
patient_voice | Future | Patient self-report: mood, comfort, preferences — routers/patient_voice.py |
care_intelligence | Future | AI-generated care summaries and longitudinal trend insights — routers/care_intelligence.py |
respiratory_oxygen | Future | SpO₂ trends, oxygen therapy orders, exacerbation events — routers/respiratory.py |
behaviour_tracking | Future | Behavioural events with triggers, severity, and intervention outcomes — routers/behaviour.py |
care_protocols | Future | Crisis plans, breathlessness plans, exacerbation protocols — routers/care_protocols.py |
observational_pain | Future | Non-verbal pain assessment scales (Abbey, PAINAD) — routers/observational_pain.py |
swallowing_safety | Future | Swallowing assessments, texture/fluid grades, aspiration risk — routers/swallowing.py |
falls_tracking | Future | Falls events with context, injury grading, intervention records — routers/falls.py |
cognitive_tracking | Future | Cognitive assessments (MMSE/MoCA), orientation, delirium screening — routers/cognitive.py |
family_journal | Future | Family-authored journal entries, milestones, memory capture — routers/family_journal.py |
preventive_care | Future | Vaccination records, screening schedules, preventive appointments — routers/preventive_care.py |
frailty_tracking | Future | Frailty 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.
Module router convention (Future modules)
Section titled “Module router convention (Future modules)”When a Future module router is built, it must:
- Be added to
database.pyMODULEStuple alongside the slug. - Use
require_module(slug)as a Depends on every endpoint. - Have a dedicated migration file
VNNN__<slug>_tables.sqlfor its schema. - Be added to the router inventory table in the HTTP surface section.
- 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 transactionRead 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 onlyRule (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).
| Layer | Location | Responsibility | Must not |
|---|---|---|---|
| Router | backend/routers/ | HTTP: Pydantic validation, Depends auth, call service/repo, return response models | await db.execute / conn.execute (new calls blocked by CI); business rules; cross-router imports |
| Service | backend/services/ | Business logic, orchestration, audit side-effects, external I/O orchestration | HTTP types (Request/Response); acquire its own DB connection |
| Repository | backend/repositories/ | Parameterised SQL only; tenant_id in WHERE for tenant-scoped tables | HTTP; branching business rules beyond query parameters |
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.
Repository layout (backend)
Section titled “Repository layout (backend)”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.jsonis{}). CI gate:python scripts/check_router_sql.pyfrombackend/— fails on any new router SQL. Git-free security review:scripts/security-review-static.ps1at 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 application
Section titled “Frontend application”Entry and providers
Section titled “Entry and providers”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.
Contexts
Section titled “Contexts”| Context | File | Purpose |
|---|---|---|
AuthContext | context/AuthContext.tsx | JWT access token (in-memory), refresh (HttpOnly cookie), user object, login/logout, _tryRefresh() on bootstrap. |
PatientContext | context/PatientContext.tsx | Loads GET /api/patients once on login; keeps activePatientId in localStorage; list is already filtered server-side for non-admins. |
ModuleContext | context/ModuleContext.tsx | Loads 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. |
AlertContext | context/AlertContext.tsx | Open alert count, Badging API (navigator.setAppBadge), 60s polling while session active. |
ThemeContext | context/ThemeContext.tsx | light / dark / system preference stored in localStorage; system listens to prefers-color-scheme. Toggles dark class on <html>. |
Routing
Section titled “Routing”All routes under the ProtectedRoute wrapper require an approved authenticated session. ModuleGate wraps routes that require a subscription module. AdminGate wraps admin-only routes.
| Route | Component | Gate |
|---|---|---|
/login | Login | Public |
/register | Register | Public |
/pending | PendingApproval | Public |
/billing/success | BillingSuccess | Public (post-Stripe redirect) |
/billing/cancel | BillingCancel | Public |
/billing/upgrade-success | BillingUpgradeSuccess | Public |
/ | Dashboard | Protected |
/calendar | Calendar | Protected + care_calendar |
/schedule | Schedule | Protected + care_calendar |
/log | LogDose | Protected + medication_dispensing |
/history | History | Protected + medication_dispensing — Dispensing and Adverse Reactions History Log: dose records plus coral-highlighted adverse reaction events; deep link ?adverseReaction={check_id} |
/analytics | Analytics | Protected + medication_dispensing |
/auto-dispense | AutoDispense | Protected + medication_dispensing |
/medication-schedule | MedicationSchedule | Protected + medication_dispensing |
/scripts | Scripts (nav: Medications) | Protected + prescription_management |
/scripts/:scriptId | ScriptDetail | Protected + prescription_management |
/admin/medicines | Redirect → /scripts | Protected + prescription_management |
/sleep | SleepPattern | Protected + sleep_tracking |
/vitals | VitalsTracking | Protected + vitals_tracking |
/pain | PainTracking | Protected + pain_tracking |
/shopping | Shopping | Protected + shopping |
/contacts | KeyContacts | Protected + key_contacts |
/care-archetypes | Redirect → /subscriptions | Legacy URL (exploratory page removed 2026-06-26) |
/observations | Observations | Protected + custom_observations (requires active patient) |
/help-requests | HelpRequests | Protected + family_help (discover via More) |
/planning-ahead | PlanningAhead (planned D31) | Protected + care_pathways — Future; spec 33 |
/account | Account | Protected |
/settings | Settings | Protected (admin-only — non-admins redirect to /) |
/people | PeopleReadOnly | Protected |
/more | More | Protected |
/getting-started | GettingStarted | Protected |
/module-upgrade | ModuleUpgrade | Protected |
/subscriptions | Subscriptions | Protected (require_tenant_member; all roles — purchase via admin, members may request modules) |
/admin/subscriptions | Redirect → /subscriptions | Protected |
/admin/patients | PatientsAdmin | Protected + AdminGate |
/admin/shopping-catalog | ShoppingCatalogAdmin | Protected + AdminGate |
/admin/alerts | AlertSettings | Protected + AdminGate |
* | Redirect to / | — |
Frontend structure
Section titled “Frontend structure”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 constantsAuth flow
Section titled “Auth flow”- Bootstrap:
AuthContextcalls_tryRefresh()on mount — exchanges thelyncare_refreshHttpOnly 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_refreshHttpOnly, SameSite=Lax, Secure-in-production cookie. - Refresh-on-401:
lib/api.tsintercepts any 401 response, attempts one refresh, retries the original request. - Logout:
POST /api/auth/logoutclears the cookie server-side. - Google sign-in: Full-page OAuth redirect from
/login; PWA handoff on iOS viapwa_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.
| Flow | Encrypt on write | Lookup / decrypt on read |
|---|---|---|
| Email/password login | — | email_blind_index → users.email_idx; decrypt_user before JWT payload |
| Register / invite accept | encrypt_field on email; patient/care-group names as applicable | decrypt_user, decrypt_patient, decrypt_tenant in responses |
Google OAuth (google_auth_service) | Encrypt new user email; blind index on create | process_google_user resolves by email_idx |
Stripe signup (signup_service, stripe_provisioning) | Tenant and user identity fields encrypted in provisioning transaction | Admin/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).
Care alerts (in-app) [Current]
Section titled “Care alerts (in-app) [Current]”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 type | Severity | Behaviour |
|---|---|---|
first_dose_reaction | normal | Answer via POST /api/first-dose-reactions/{check_id}/respond |
adverse_reaction_reported | urgent | Tap card → detail modal; Mark done when handled |
| Endpoint | Purpose |
|---|---|
POST /api/first-dose-reactions/{check_id}/respond | Structured 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-log | Observed 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.
Architecture
Section titled “Architecture”Key files
Section titled “Key files”| File | Role |
|---|---|
backend/services/first_dose_reaction_service.py | First-dose prompt detection; structured respond; adverse-reaction follow-up |
backend/routers/first_dose_reactions.py | POST …/respond, GET …/{check_id}, GET …/adverse-reaction-log |
backend/repositories/first_dose_reactions.py | patient_medicine_first_dose_checks SQL |
backend/migrations/V004__first_dose_reaction_checks.sql | First-dose checks table + notification channel |
frontend/src/components/medication/FirstDoseReactionModal.tsx | Post-dispense prompt; post-Yes → detail modal |
frontend/src/components/medication/AdverseReactionDetailModal.tsx | Reaction note, seek advice, clinical contacts |
frontend/src/lib/contactRoles.ts | Shared role labels; pickAdverseReactionContacts() |
backend/migrations/V005__key_contacts_palliative_specialist.sql | palliative_specialist on key_contacts.role_tag |
backend/routers/alerts.py | List open alerts, open-count, resolve, events, admin channel settings |
backend/services/alert_service.py | Policy check → upsert open alert (nine tenant channels + master toggle) |
backend/services/alert_scheduler.py | Shift reminders (24h), overdue-dose hourly sweep (per patient, consolidated) |
backend/services/alert_dose_sync.py | Upsert/resolve consolidated overdue-dose alert from live group counts |
backend/services/alert_dose_helpers.py | Consolidated dedup keys, overdue-window checks, “dose recorded today” |
backend/services/alert_dose_hooks.py | schedule_refresh_overdue_dose_alert() after dispense commits |
backend/services/alert_shopping_sync.py | Upsert/resolve consolidated shopping alert from active item counts |
backend/services/alert_shopping_helpers.py | Shopping dedup key, active-item count query, alert body text |
backend/services/alert_fire.py | schedule_alert(fn) — background tasks with dedicated pool connection |
backend/repositories/alerts.py | SQL for care_alerts, care_alert_events, settings (incl. family_help) |
frontend/src/context/AlertContext.tsx | Open-count polling, Badging API |
frontend/src/components/alerts/ | AlertBell, AlertInbox, AlertRow |
frontend/src/pages/admin/AlertSettings.tsx | Tenant channel toggles (/admin/alerts) |
backend/migrations/V073__care_alerts.sql | care_alerts, care_alert_events |
backend/migrations/V100__care_alerts_metadata.sql | care_alerts.metadata JSONB (miss_count for overdue dose; item_count for shopping) |
backend/migrations/V093__alert_settings_family_help.sql | tenant_notification_settings.family_help channel toggle |
backend/migrations/V094__subscriptions_add_family_help_module.sql | subscriptions.module CHECK includes family_help |
backend/migrations/V063__notifications.sql | Legacy 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.
Backend changes required:
- New or extended
push_subscriptionswithdelivery_type(apns|fcm) anddevice_token— no VAPID path. native_push_service(or hook inalert_fire) reads open alerts and fans out to registered tokens.APNS_*andFCM_*env vars in.env.example.
Frontend / Capacitor:
@capacitor/push-notificationsregisters token with the API; tap opens the app to/alerts(or deep link).- PWA build unchanged —
AlertContextpolling + 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.
Alert types and gates
Section titled “Alert types and gates”type | Severity | When |
|---|---|---|
stock_tracking_incomplete | Amber | status = 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_low | Amber | Stock 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_needed | Amber | Admin / 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_fill | Amber | fills_completed = total_fills_authorised − 1. |
exhausted / expired | Red | Script 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.
| Concept | Source | UI label |
|---|---|---|
| Pharmacy supply | fills_completed × quantity_per_fill (legacy path) or SUM(script_fills.quantity_added) since baseline | Implied by fills / pack size (not a separate card line today) |
| Dose log total (API only) | SUM(dispensings.volume) lifetime | total_dispensed — alert logic only; not shown on family UI |
| On hand now | Baseline 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 audit | last_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.
| Item | Detail |
|---|---|
| API | ScriptUpdate.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. |
| Service | services/script_stock.py — load_lifetime_dispensed_totals, load_since_baseline_aggregates, enrich_scripts_stock; used by list, detail, medicine-summary, alerts |
| Repository | enrich_script() delegates to script_stock; legacy adjustment_for_pills_available() retained for tests only |
| Frontend | lib/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(). |
| Tests | TestStockAdjustment; 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):
| Issue | Impact |
|---|---|
quantity_added on script_fills only in since-baseline SUM; legacy path still uses fills×quantity_per_fill | Partial pharmacy pick semantics — document in spec before changing legacy scripts |
Denormalized total_dispensed_volume on patient_scripts | Deferred 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”| Item | Detail |
|---|---|
| Table | script_alert_dismissals — (user_id, patient_id, script_id, alert_type) unique; dismissed_at timestamp |
| Snooze | Banner hidden for 3 days after Ignore; returns if the condition still applies |
| Resolved condition | When 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 |
| API | POST /api/patients/{id}/scripts/alerts/dismiss — body { script_id, alert_type } → 204 |
| UI | ScriptAlertBanner — 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:
| Mechanism | Role |
|---|---|
lib/scriptsEvents.ts | notifyScriptsChanged() + SCRIPTS_CHANGED_EVENT + sessionStorage touch (mirrors dispensingsEvents.ts). takeScriptsTouchForInitialState() peeks only (Strict Mode safe). |
lib/scriptAlerts.ts | Banner copy + navigation (stock_tracking_incomplete, stock_count_needed → /scripts/{id}?setup=stock). |
FillModal | On hand after collection preview; notifyScriptsChanged() after successful POST …/fills. |
Dashboard.tsx | Listens for event / touch; refetches scripts.alerts with cancelled in-flight requests; pageshow (bfcache) bumps scriptsDataGen. |
Scripts.tsx | Silent load() on event; touch when returning to /scripts*. |
ScriptDetail.tsx | ?setup=stock opens Edit for admins; “Set up stock tracking” on amber panel. |
ScriptAlertBanner.tsx | Ignore 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.
Key files
Section titled “Key files”| File | Role |
|---|---|
backend/migrations/V112__patient_scripts_physical_count_baseline.sql | last_physical_count, last_physical_count_at; dispensings index |
backend/migrations/V113__dispensings_clock_timestamp_defaults.sql | clock_timestamp() defaults on dispensings timestamps |
backend/migrations/V114__script_alert_stock_count_needed.sql | stock_count_needed on dismiss CHECK |
backend/migrations/V105__script_alert_dismissals.sql | Dismiss snooze table |
backend/services/script_stock.py | Canonical stock + lifetime / since-baseline aggregates |
backend/services/alert_script_sync.py | Upsert / auto-resolve prescription_stock_count in care_alerts |
backend/services/alert_script_hooks.py | await_sync_prescription_stock_count_alert — inline after stock/dispense commit |
backend/services/alert_script_hooks.py | Schedule stock-count care-alert sync after dispense / PATCH |
backend/services/patient_scripts_service.py | get_script_alerts(), dismiss_script_alert(), record_fill(), pills_available baseline PATCH |
backend/repositories/patient_scripts.py | derive_stock(), enrich_script(), dismiss helpers |
backend/routers/scripts.py | GET …/scripts/alerts, POST …/alerts/dismiss, PATCH …/scripts/{id} (pills_available) |
frontend/src/pages/Dashboard.tsx | Home alert banners |
frontend/src/pages/Scripts.tsx | Medications alert banners |
frontend/src/components/scripts/ScriptAlertBanner.tsx | Banner + Ignore |
frontend/src/components/scripts/MedicationCard.tsx | Doses available + countdown bar + dose log line; EXHAUSTED_REPEATS_LABEL when exhausted |
frontend/src/components/scripts/EditScriptModal.tsx | Doses 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.ts | Labels (DOSES_AVAILABLE_LABEL, EXHAUSTED_REPEATS_LABEL, …), needsStockCountGuidance, resolveTotalDispensed, stockCountdownBar |
frontend/src/lib/numericField.ts | Integer text fields (no type="number" leading zeros) |
frontend/src/pages/ScriptDetail.tsx | Fill + stock setup UX |
frontend/src/components/scripts/FillModal.tsx | Record fill modal |
frontend/src/components/scripts/StockCountGuidancePanel.tsx | Zero on-hand guidance (Log Dose, schedule dispense) |
frontend/src/pages/LogDose.tsx | Manual dose entry; stock guidance on form + post-save success when needsStockCountGuidance |
backend/tests/test_prescriptions.py | TestScriptAlerts, 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:
| State | Circle content |
|---|---|
| Pending | Scheduled dose_amount via ScheduleDoseCircleLabel (components/medication-schedule/ScheduleDoseCircleLabel.tsx) |
| Overdue | Same numeric label; coral ring |
| Dispensed | Sage 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.
PWA and installable app
Section titled “PWA and installable app”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.
Manifest (frontend/public/manifest.json)
Section titled “Manifest (frontend/public/manifest.json)”| Property | Value | Notes |
|---|---|---|
display | standalone | Hides browser chrome; full-screen native feel |
display_override | ["window-controls-overlay", "standalone"] | Allows WCO where supported (Sprint 2.7) |
orientation | portrait-primary | Intentionally portrait-locked for clinical use |
theme_color / background_color | #0f172a (slate-900) | Matches dark mode app shell |
| Icons | 192 × 192, 512 × 512 (any + maskable) | Used for home screen and splash screens |
categories | health, medical | App store metadata |
Service Worker strategy (frontend/public/sw.js)
Section titled “Service Worker strategy (frontend/public/sw.js)”| Resource type | Cache strategy | Rationale |
|---|---|---|
| App shell (HTML, JS, CSS, icons) | Cache-first, update on install | Fast load; cache busted by SW CACHE_NAME |
/api/* calls | Network-only | Clinical data must always be fresh |
| API-served images | Network-first, short cache | Prescription / patient images may change |
| Navigation fallback | offline.html | Branded 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.
Care awareness (current)
Section titled “Care awareness (current)”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.
Key implementation points:
| Concern | Implementation |
|---|---|
| Android prompt interception | beforeinstallprompt captured in main.tsx before React mounts; stored as a module-level ref for the install prompt component |
| iOS detection | isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) + !(window as Window & { MSStream?: unknown }).MSStream |
| Install state detection | window.navigator.standalone === true || window.matchMedia('(display-mode: standalone)').matches |
| Dismissal persistence | localStorage.setItem('pwa_prompt_dismissed', Date.now()) — prompt hidden for 14 days |
| Install value hook | The iOS bottom sheet explains home-screen install for faster access and the app icon badge (open alert count) |
| Shift guard | Prompt is suppressed while a care shift is active to avoid interrupting workflows |
| Type declaration | frontend/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; }}Database model
Section titled “Database model”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.
Entity–relationship diagram
Section titled “Entity–relationship diagram”Notable migration-added tables (not in schema.sql)
Section titled “Notable migration-added tables (not in schema.sql)”| Added by | Tables / columns |
|---|---|
| V011__sleep_tracking | sleep_entries |
| V012__shopping_module | shopping_lists, shopping_items, shopping_catalog_* |
| V028__patient_appointments | patient_appointments |
| V033__audit_log_hardening | Audit triggers on PHI tables |
| V034__row_level_security | RLS policies using app_current_tenant_id() |
| V035__mfa_users | user_mfa |
| V041__stripe_billing | stripe_customers, stripe_subscriptions, stripe_events |
| V042__stripe_tiers | stripe_tiers, stripe_prices |
| V043__signup_and_onboarding | pending_signups, onboarding_steps |
| V047__tier_limits_and_pending_downgrade | Tier limit columns |
| V050–V058 | pain_entries, patient_vitals, mind_entries, tenant_pain_settings (see 26-PAIN-STATS-MODULE.md) |
| V060__key_contacts | patient_key_contacts |
| V061__data_deletion_on_cancellation | Deletion policy columns |
| V062 | key_contacts subscription module row |
| V063__notifications | user_notifications, push_subscriptions, tenant_notification_settings |
| V064–V066 | Schedule item deactivation tracking (deactivated_at); medication dose change timestamp (dose_changed_at) |
| V067–V072 | Soft-delete (deleted_at) across patients, care tasks, contact records, sleep entries, appointments, script fills |
| V073 | care_alerts, care_alert_events — in-app care alert system; Web Push (VAPID) removed |
| V074 | analytics_dispensing_summary materialised view — pre-computed tenant-partitioned dispensing summary; REFRESH MATERIALIZED VIEW CONCURRENTLY every 5 min via APScheduler |
| V075 | scan_jobs — PostgreSQL-native scan job queue replacing Redis LPUSH/BRPOP; pg_notify replaces Redis PUBLISH for SSE result delivery |
| V076 | Encrypted 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 |
| V077 | condition_archetypes — seven palliative care archetypes grouping patients by dominant coordination challenge (C1a) |
| V078 | condition_packs, pack_reason_type_links, pack_shift_task_templates — template bundles tied to archetypes; 2 free starter packs per tenant (C1b) |
| V079 | observation_types, pack_observation_type_links, patient_observations — flexible observation type registry replacing hard-coded vitals columns; 7 universal seed types (C1c) |
| V080 | help_requests, help_offers — family help-circle coordination (D1a) |
| V081 | claimed_by ownership on patient_appointments and shift_tasks — calendar ownership (D1b) |
| V082 | body_layer column on patient_pain_entries — pain selector layers: front, back, skeleton, mind, surface (C8) |
| V083–V088 | Stream 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) |
| V089 | PHI field-level encryption extended to tenants: name_enc + enc_version shadow columns added |
| V090 | PHI 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 |
| V091 | PHI 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 |
| V092 | patient_pain_entries.body_layer CHECK extended for bone overlay: front-skeleton, back-skeleton (fixes V082 constraint vs PainBodyMapTab) |
| V093 | tenant_notification_settings.family_help — care-alert channel for family help board |
| V094 | subscriptions_module_check extended to allow family_help module slug |
| V100 | care_alerts.metadata JSONB — consolidated overdue-dose miss_count |
| V101 | users.phone, profile fields; key-contacts extensions |
| V102 | tenant_module_purchase_alerts |
| V103 | Merge medicines into patient_scripts; drop medicines router/table (D23) |
| V104 | tenants.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):
| Migration | Adds |
|---|---|
| V025 | tenant_account_numbers |
| V026 | care_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 |
| V027 | Module 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 |
| V028 | users.login_count — completed sign-in counter (mobile nav onboarding hint; not incremented on refresh bootstrap) |
Field-level PHI encryption (B4)
Section titled “Field-level PHI encryption (B4)”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):
| Module | Prefix | Key env | Purpose |
|---|---|---|---|
services/crypto.py | mfa:v1: | MFA_ENCRYPTION_KEY or HKDF lyncareos:mfa:v1 | TOTP secret and backup codes |
services/field_crypto.py | phi:v1: | PHI_ENCRYPTION_KEY (comma-separated MultiFernet chain) or HKDF lyncareos:phi:v1 | User email, patient name/DOB, care group name, tenant display name |
| Blind index (email only) | — | PHI_BLIND_INDEX_KEY or HKDF lyncareos:phi:idx:v1 | users.email_idx — HMAC-SHA256 of normalised email (26-char urlsafe base64) for equality lookup without plaintext |
Columns (post-V091):
| Table | Stored ciphertext / index | API field after decrypt |
|---|---|---|
users | email_enc, email_idx, enc_version | email |
patients | full_name_enc, date_of_birth_enc, enc_version | name, dob (legacy names in app layer) |
care_groups | name_enc, enc_version | name |
tenants | name_enc, enc_version | name |
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:
| Area | File | Pattern |
|---|---|---|
| Session user | auth.py | decrypt_user in get_current_user, get_mfa_pending_user, SSE ticket path |
| Login / register | routers/auth.py | email_idx lookup; email_enc on INSERT; decrypt_tenant for tenant name in response |
| Patients | services/patients_service.py (via routers/patients.py) | *_enc columns only; member invite uses email_blind_index |
| Tenant DEK | services/field_crypto.py | ensure_tenant_dek on provision; get_tenant_dek for future REQ-ENC-05 |
| Google OAuth | services/google_auth_service.py | email_idx lookup; encrypt on new user |
| Signup guard | services/signup_service.py | duplicate check on email_idx |
| Stripe checkout | services/stripe_provisioning.py | email_enc / email_idx on user; name_enc on tenant |
| Tenants / users / invitations | respective routers | encrypt on write, decrypt before response |
Operational notes:
- Production should set dedicated
PHI_ENCRYPTION_KEYandPHI_BLIND_INDEX_KEYinbackend/.env(seeconfig.pycomments). Rotating keys: add new key first in comma-separatedPHI_ENCRYPTION_KEY; re-encrypt with backfill script. - V091 is irreversible — apply only after backfill and code paths verified (
backend/scripts/validate_migration.pychecks duplicates and decrypt round-trip). V091 carries an in-DBDO $guard$pre-flight block (added 2026-05-27) that countsenc_version = 0rows and NULL ciphertext across all four PHI tables, thenRAISE EXCEPTIONs and rolls back if any count is non-zero. The guard was added after an incident onlyncareos_devwhere 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_KEYis set,services/field_crypto.pyderives the Fernet/HMAC keys via HKDF on every boot — that works untilSECRET_KEYis rotated, at which point all existing ciphertext becomes permanently undecryptable..\scripts\production-phi-pin.ps1writes the derived values to/opt/lyncareos/.env.productionand 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/patientsorders byfull_name_enc(lexicographic on ciphertext), not display-name sort order.
PostgreSQL type conventions in use
Section titled “PostgreSQL type conventions in use”| Pattern | Type |
|---|---|
| Primary keys | SERIAL |
| Booleans | BOOLEAN |
| Admin / state flags | SMALLINT (users.is_super_admin, users.must_change_password) |
| Timestamps | TIMESTAMPTZ for audit and created_at / updated_at fields |
| Calendar / dispensing dates as entered | TEXT (e.g. dispensing date/time, shift date) |
| Volumes | DOUBLE 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:
| Layer | Table / concept | Role |
|---|---|---|
| Archetype | condition_archetypes | Seven coordination patterns — onboarding classifier |
| Care Profile (pack) | condition_packs | Unlockable template; content in pack_* tables |
| Care Start apply | apply_care_start_pack() in care_start_service.py | Idempotent 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.
| Term | Meaning |
|---|---|
| Account / tenant | One subscriber organisation. Created when a user registers (or accepts an invite). Billing and subscriptions rows are per tenant. |
| Tenant administrator | tenant_memberships.role = 'admin'. Seeded for the account purchaser; can invite users and manage patients for that tenant only. |
| Tenant member | tenant_memberships.role = 'member' (or admin). Must be invited and approved into the tenant. |
| Patient | A person receiving care. patients.tenant_id ties them to exactly one account. |
| Allocation | patient_access rows: which tenant users may see/act on which patients (role: carer or observer). |
-
No cross-account visibility for tenant admins, carers, or observers. Every tenant-scoped query must use
ctx["tenant_id"]fromrequire_tenant_member(or stricter). JWT carriestid; PostgreSQL RLS usesapp.current_tenant_id(see migrationV034__row_level_security.sql) as defense in depth. -
Carers and observers see only patients they have been allocated via
patient_access.GET /api/patientsfor non-admins returns only those rows; patient-scoped routes userequire_patient_access/ensure_patient_access. -
Tenant administrators (
tenant_roleadmin in context) may see all patients in their tenant without a per-patientpatient_accessrow. This supports account management (register patients, assign carers, oversee care). They still cannot see other tenants’ data. -
Platform owner (
users.is_super_admin = 1): may useX-Tenant-IDor?as_tenant=to operate as a tenant (auth.resolve_tenant_id). Cross-tenant listing (e.g.GET /api/users/all) usesrequire_super_admin. This is the only cross-account operational path for normal product features. -
Super admin in tenant context is treated like a tenant admin for patient visibility within the selected tenant (after
X-Tenant-IDis set). -
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). -
Multi-tenant user model (REQ-AUTH-12) [Target — Phase E]. A
usersrow is a person; atenantsrow is a care account. One person may hold manytenant_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 theusersrow and creates a newtenantsrow plus anadmintenant_membershipsrow. The provisioning engine (services/stripe_provisioning._provision_from_pending_signup) already reuses existing users byemail_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. -
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 viaPOST /api/auth/switch-tenant, which re-issues the JWT pair with the newtid. Allrequire_tenant_member/require_modulechecks apply against that activetidonly; exactly onetidis 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.
Helpers (reference)
Section titled “Helpers (reference)”| Helper | Purpose |
|---|---|
require_tenant_member | Active membership on write pool (get_db); sets RLS app.current_tenant_id. |
require_tenant_member_read | Same membership check on read pool (get_ro_db) — use with analytics/audit/onboarding GET. |
require_tenant_admin | Admin or super_admin in context (write path). |
require_tenant_admin_read | Admin check on read path (e.g. audit list with get_ro_db_with_rls_admin). |
get_ro_db_with_rls | Single RO connection with RLS GUC; depends on require_tenant_member_read only. |
resolve_tenant_id | Active 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_access | Carer/observer must have patient_access; admin/super_admin must have patient in tenant. |
is_tenant_wide_operator | Admin or super_admin — may use tenant-wide patient visibility for certain operations. |
append_dispensing_patient_scope_for_member | Restricts dispensing/analytics SQL to patients the user may see (non-admins only). |
ensure_dispensing_row_access_for_member | Single dispensing row: member must have access to that row’s patient_id. |
Access control audit (April 2026)
Section titled “Access control audit (April 2026)”- In scope: FastAPI routers under
backend/routers/, core dependencies inbackend/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).
Method
Section titled “Method”- Listed every router mounted in
backend/main.pyand checked each file for: correct tenant context (require_tenant_memberor stricter), patient allocation where the resource is patient-specific (require_patient_access,ensure_patient_access, or inlinepatient_accessSQL), and role expectations (require_tenant_admin,require_carer_role, etc.). - Searched for tenant-scoped routes that aggregate per-patient data without
patient_accessfiltering for non-admin members (the main failure mode for carers/observers).
Router inventory (maintain from code)
Section titled “Router inventory (maintain from code)”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.
| Router | Primary dependencies | Patient allocation |
|---|---|---|
| auth | get_current_user, require_approved, public login/register/refresh | N/A — identity and tokens only |
| users | require_tenant_admin; GET /all → require_super_admin | Tenant membership / module overrides — no patient rows without admin |
| invitations | require_tenant_admin; GET /verify/{token} public | Admin-only CRUD; verify is token-scoped |
| tenants | require_tenant_member, require_tenant_admin, require_super_admin | Tenant metadata — no clinical rows |
| subscriptions | require_tenant_admin (writes), require_tenant_member (read active) | Billing — tenant-scoped |
| medicines | require_tenant_member / admin; REQ-MED-14 GET /api/patients/{id}/medicines | Patient-scoped read for carer pickers |
| reason_types | GET /api/reason-types?patient_id= + ensure_patient_access; admin writes scoped to that patient | Patient-scoped PRN catalogue (V014) — not shared across people in care |
| dispensings | require_tenant_member + helpers | Remediated — see below |
| analytics | require_tenant_member_read + get_ro_db_with_rls + SQL scope | Remediated — see below; one pool slot per request (2026-05-30) |
| audit | require_tenant_admin_read + get_ro_db_with_rls_admin | Admin-only — no member leak |
| medication_groups | require_patient_access, require_tenant_admin, require_carer_role | require_carer_role depends on require_patient_access |
| patients | require_tenant_member / admin vs member queries | Aligned — member list joins patient_access; GET /{id}/members uses ensure_patient_access |
| care_shifts | require_tenant_member + ensure_patient_access | Remediated — see below |
| patient_appointments | Local _require_patient_access on each handler | Aligned |
| scripts | require_patient_access / require_tenant_admin where appropriate | Aligned |
| sleep | require_patient_access | Aligned |
| vitals | require_module("vitals_tracking") + require_patient_access | Aligned |
| pain, mind | require_module("pain_tracking") + require_patient_access / carer where applicable | Aligned |
| pain_settings | Auth + tenant; not module-gated in main.py | Tenant settings |
| shopping | require_patient_access on patient routes; ensure_patient_access on selected flows | Aligned |
| key_contacts | require_module("key_contacts") + require_patient_access | Aligned — Family and Complete |
| admin_shopping | require_super_admin / require_tenant_admin | Catalog admin — not member clinical data |
| pwa_auth | Unauthenticated + rate limits | PWA OAuth handoff — opaque session_id as credential |
| stripe | Mix of public (/webhook) and authed (signup, upgrade) | Provisioning / billing — see router |
| billing | Public + authed (get_ro_db for some reads) | Tiers/FX for marketing; tenant billing context when logged in |
| onboarding | require_tenant_member_read (GET progress), require_tenant_member + get_db (POST steps) | Onboarding — tenant-scoped |
| alerts | require_tenant_member; admin settings require tenant admin | Shared open alerts — team-visible per patient |
| dev_tools | Non-production only | Test helpers |
Findings and remediation
Section titled “Findings and remediation”| Area | Finding | Resolution |
|---|---|---|
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 router | GET /{patient_id}/members listed care-team rows with tenant filter only. | ensure_patient_access before the query. |
| RLS | V034 policies enforce tenant isolation at the database layer. | Keep application checks as primary for patient allocation; RLS as defense in depth. |
Frontend access control (April 2026)
Section titled “Frontend access control (April 2026)”| Area | Assessment |
|---|---|
| Routing | ProtectedRoute requires approved user; ModuleGate enforces subscription modules; AdminGate protects admin URLs; Settings self-redirects non-admins. |
| Patient list | PatientProvider uses GET /api/patients only — members receive allocated patients; empty list shows “No patients assigned yet” (Layout). |
| API usage | lib/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 reasons | GET /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 → Audit | Audit 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-admin | Treated 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 withpatient_accessto one patient only sees those dispensings; cannot GET another patient’s dispensing (403); cannot POST withoutpatient_id(403).tests/test_care.py: care groups, shifts, tasks, patient-prefixed calendar routes, andtest_list_patient_members_requires_allocation(GET /patients/{id}/members).
Follow-up (recommended)
Section titled “Follow-up (recommended)”dispensings.patient_idisNOT NULLsince 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 NULLpatient_id(cannot be rejoined) and only surface under “All people”.- New-write
audit_log.patient_idpopulation 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 NULLpatient_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/downloadisrequire_tenant_admin. Per-patient export sendspatient_id(validated byensure_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 byrequire_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; frontendfrontend/src/test/components/PatientIsolation.test.tsx; tenant RLStests/test_rls.py(now exercises encryptedfull_name_enc). - Periodic re-audit when new routers or major SPA routes are added.
Connection pool
Section titled “Connection pool”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.
| Symptom | Typical cause |
|---|---|
| Page hangs ~30 s then 500 | psycopg_pool.PoolTimeout — pool exhausted; check backend-err.log |
| Dashboard worst case | Many parallel /api/* calls (medicines, analytics ×2, alerts, dispense view, …) × React StrictMode double-fetch in dev |
| Fixed 2026-05-30 | Read 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.
Hardening and Scale-to-100k (April 2026)
Section titled “Hardening and Scale-to-100k (April 2026)”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.
Shared state and horizontal scaling
Section titled “Shared state and horizontal scaling”| Concern | Before | After |
|---|---|---|
| SSE tickets | In-memory dict per worker | Redis keys with TTL + GETDEL (services/sse_tickets.py) |
| PWA ↔ Safari OAuth handoff | In-memory dict | Redis keyed sessions (services/pwa_auth_service.py) |
| Shopping pub/sub | asyncio.Queue fan-out | Redis pub/sub (services/shopping_service.py + hooks/useShoppingSync.ts) |
| Rate limit buckets | In-memory SlowAPI | Redis-backed SlowAPI (middleware/rate_limit.py) |
| Hot caches | None | Redis TTL caches for modules / patients / medicines / catalogs (services/cache.py) |
| Care alerts | Per-user inbox + VAPID | PostgreSQL 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.
Database tier
Section titled “Database tier”- PgBouncer (transaction pool mode) sits in front of PostgreSQL in Docker Compose (
pgbouncerservice). The app targets PgBouncer, which funnelsDB_POOL_MAX * replicasclient 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.
Auth and security
Section titled “Auth and security”- 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/logoutclears the cookie. - MFA TOTP secrets are encrypted at rest with Fernet (
mfa:v1:prefix); key fromMFA_ENCRYPTION_KEYor HKDF fromSECRET_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 —
bcryptalways 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, andGET /api/invitations/verify/{token}. - SlowAPI key function hashes the JWT signature so bucket keys are bound to the credential, not user-supplied claims.
Billing (Stripe MVP)
Section titled “Billing (Stripe MVP)”- Migration V041 adds Stripe columns on
tenantsand newstripe_events,stripe_prices, and mapping tables. routers/stripe.pyexposes 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 gatecondition_templates). Bootstrap:services/care_start_bootstrap.py(med schedule slots, sample medicine, shopping lists); backfillscripts/backfill_care_bootstrap.pyfor patients applied before bootstrap shipped; cataloguecare_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+ArchetypeOnboardingdeleted. Care boards:Layout.tsxinjects sidebar Cancer board / Breathing board when active patient slug matches and preview flags on; plusCareBoardDashboardChipon Home. Dev QA:scripts/seed_dev_peter_care_qa.pyon tenantpeter(activatesshoppingmodule for list QA).services/stripe_provisioning.pyhandles first-time tenant / user / subscription creation from a completed Checkout session. Signup setsusers.last_active_tenant_idto the provisioned tenant; all provision paths pass Checkoutpayment_statusinto module sync when the Stripe subscription is stillincomplete.services/stripe_service.sync_subscription_itemsmirrors Stripe subscription items intosubscriptionsrows. Price → modules:stripe_tiers/stripe_tier_local_prices, then Stripe Price metadatalyncareos_tierfor grandfathered Price ids (2026-05-30), then legacystripe_price_modules. Repair:scripts/resync_tenant_subscriptions.py.- Product delivery manifest (
billing/module_delivery.json, loader inbilling/module_delivery.py) records live / partial / planned per slug — separate from commercial entitlement intiers.json. Exposed onGET /api/modules/availableasdelivery; 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.pymaps Checkout sessions to user-facing outcomes (charged,user_message, stablecode) and logs structuredpayment_outcomelines for operator review.services/tier_resolution.pyandservices/tier_upgrade_service.pyresolve active tier rows and upgrade options. Primary path: joinsubscriptions.stripe_price_idtostripe_tiersorstripe_tier_local_prices. Fallback (2026-05-27): when price IDs are missing or stale (e.g. test-era IDs after live switchover), inferessential/professional/completefrom active module slugs (shopping/pain_tracking→ Complete; Family markers →professional; else Essential).GET /api/billing/my-tierand Subscriptions UI depend on this.services/condition_pack_billing.pyenforces tier-included packs, purchase guards, and subscription-currency display for pack checkout.POST /api/stripe/complete-signupprovisions inline when Stripe reportspaidbut the webhook has not yet consumedpending_signups, setslast_active_tenant_id, and resyncs from Stripe — reduces stuck signups on/billing/success.require_module(slug)checkssubscriptions.statusand returns HTTP 402 when the tenant does not hold an active entitlement.
Long-running work
Section titled “Long-running work”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.
Scheduling
Section titled “Scheduling”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.
What was deliberately not done
Section titled “What was deliberately not done”- 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.
Critical — address before public launch
Section titled “Critical — address before public launch”| Gap | Current state | Recommended approach |
|---|---|---|
✅ 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. | |
✅ Implemented — frontend/src/index.css @layer base sets input, textarea { font-size: 16px !important; } | No action required. | |
✅ Implemented — .btn class sets min-h-[44px]; .input class sets min-h-[48px]. | No action required. | |
| Offline error page | frontend/public/offline.html (branded page); sw.js caches and serves it as navigation fallback. | Done in Sprint 1.4. |
High — address in next sprint
Section titled “High — address in next sprint”| Gap | Current state | Recommended 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 targets | Baseline 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. |
Medium — planned technical debt
Section titled “Medium — planned technical debt”| Gap | Current state | Recommended approach |
|---|---|---|
| Router → Service → Repository layering | Complete — 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 / WebAuthn | Not present | Future: navigator.credentials (Passkeys / FIDO2) as a supplement to TOTP MFA. No immediate requirement. |
Design system best practices
Section titled “Design system best practices”| Item | Status |
|---|---|
| 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 design | Standard 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.
Current state
Section titled “Current state”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.
Target architecture
Section titled “Target architecture”Translation namespace structure
Section titled “Translation namespace structure”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 3Plain 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:
| Key | Rendered for carers/families | Rendered 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" }}RTL layout readiness
Section titled “RTL layout readiness”- CSS logical properties (
margin-inline-start,padding-inline-end, etc.) must be used for all directional spacing in new components. <html dir="...">is set fromlocales.config.jsonon 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.
Backend localisation
Section titled “Backend localisation”- 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.localecolumn) for outbound messages. - API validation error messages are translated via a locale parameter on the
HTTPExceptiondetail dict — the frontend resolves them throughi18next.
New database columns required
Section titled “New database columns required”| Table | Column | Purpose |
|---|---|---|
tenants | locale TEXT DEFAULT 'en-AU' | Tenant default UI locale and backend notification locale; does not imply PHI storage region |
users | locale_override TEXT | Per-user locale override (null = use tenant default) |
Translation quality tiers
Section titled “Translation quality tiers”| Tier | Scope | Quality requirement |
|---|---|---|
| 1 | UI chrome (nav, buttons, labels, generic error messages) | Professional human translation required |
| 2 | Plain-language clinical content (symptom labels, care notes prompts, module names) | Human translation with lay-carer review |
| 3 | Standardised 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”| Rule | Detail |
|---|---|
| System of record | Website Stripe (Checkout, Customer Portal, Care Profile purchase) + existing webhooks → tenant tier / module entitlements |
| Store binaries | Free, consumption-only — login / free signup / use entitled modules; no Stripe Checkout, payment WebViews, or payment portal deep links |
| Upgrade messaging | Informational copy only in store builds (e.g. “Go to lyncareos.com to upgrade”) — must not lead to an alternate payment method |
| Tenant unlock | Admin purchase on website unlocks modules for the whole care circle (unchanged) |
| Optional later | Play Billing / StoreKit / Billing Choice only with PO sign-off (REQ-NATIVE-12) |
Trigger criteria (REQ-NATIVE-01)
Section titled “Trigger criteria (REQ-NATIVE-01)”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).
Capacitor architecture
Section titled “Capacitor architecture”Auth note [Target]
Section titled “Auth note [Target]”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:
| Rule | Rationale |
|---|---|
All API calls use relative URLs (/api/...) or VITE_API_URL env var | Capacitor’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 downloads | Use 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 Layout | Already implemented — required for iPhone notch and Dynamic Island clearance |
| Billing / upgrade CTAs feature-gated for store builds | REQ-NATIVE-08/10 — website keeps full Stripe UX |
Native push migration
Section titled “Native push migration”When the native app is released:
- PWA users continue with in-app alerts + icon badge only.
- Native installs register APNs/FCM tokens; open
care_alertsoptionally mirror to lock screen. - PostgreSQL
care_alertsremains authoritative — native push is a nudge, not a second inbox.
App Store compliance (REQ-NATIVE-04)
Section titled “App Store compliance (REQ-NATIVE-04)”| Requirement | Approach |
|---|---|
| Google Play first, then Apple | Free listings; Health & Fitness / family-support framing |
| Listing policy | Position as family support / care coordination, not a medical app. Description must not claim to diagnose, treat, or cure. |
| Privacy policy | Must explicitly describe all data collected, stored, and processed, including family data and care records. |
| No medical device claim | All care data entry is presented as family care record-keeping, not medical advice — enforced in listing copy and in-app disclaimers |
| Payments | Consumption-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/coreworkspace.
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.”
As implemented today
Section titled “As implemented today”All figures below are counted from the repository, not estimated. Re-measure before citing them.
| Layer | What the code does |
|---|---|
| Backend wire models | Pydantic 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 artefact | backend/scripts/export_openapi.py imports main.app and writes committed openapi/openapi.json — 399 /api paths, 517 operations, 132 component schemas. |
| Response typing in OpenAPI | 36 @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 TypeScript | npm 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 aliases | frontend/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 imports | 169 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 types | api.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)”Workflow (B1 — use on every API change)
Section titled “Workflow (B1 — use on every API change)”- Export (from
backend/):python scripts/export_openapi.py→openapi/openapi.json. - Generate (from
frontend/):npm run generate:types→src/lib/api.types.ts. - Alias: add
export type Foo = Schema<'Foo'>inapi.contracts.tswhen the schema exists in OpenAPI. - Adopt: import from
api.contracts.tsin helpers and feature code; re-export fromapi.tsonly for backward-compatible import paths. - Verify:
npm run check:types-driftlocally; CIopenapi-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 asSchema<'…'>inapi.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 manualinterfaceinapi.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.
Further reading
Section titled “Further reading”Core architecture and operations
Section titled “Core architecture and operations”- Day-to-day setup: 05-DEVELOPER-GUIDE.md
- Product scope, requirements and roadmap: 02-REQUIREMENTS.md, 04-ROADMAP.md
- Operations (tunnel, backup): [../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md](../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md)
- Hardening & scale operations (2026-04): 17-HARDENING-SCALE-RUNBOOK.md
- Posture and launch plan: 04-ROADMAP.md
- Production deployment and hosting: 03%20-%20DEPLOYMENT%20AND%20PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md
Module documentation
Section titled “Module documentation”- Shopping module: 06-SHOPPING-MODULE.md
- Prescriptions module: 08-PRESCRIPTIONS-MODULE.md
- Auto-dispense module: 09-AUTO-DISPENSE-MODULE.md
- Pain & Stats module: 26-PAIN-STATS-MODULE.md
Billing and pricing
Section titled “Billing and pricing”- Stripe live switchover playbook: 21-STRIPE-LIVE-SWITCHOVER.md
- Global pricing model and Adaptive Pricing: 18-STRIPE-GLOBAL-PRICING.md
Design
Section titled “Design”- Design system (colour palette, typography, component conventions): 03-DESIGN-SYSTEM.md
In-document sections (this file)
Section titled “In-document sections (this file)”- Architecture evolution overview: Architecture evolution: current to target
- All 23 module slugs and status: Module gating
- Care alert architecture (in-app; future native push): Care alerts (in-app)
- PWA install prompt architecture (iOS + Android): PWA and installable app
- Internationalisation architecture (react-i18next, locales, RTL): Internationalisation architecture
- Native app strategy (Capacitor, Play-first, website Stripe SoT, HealthKit): Native app strategy: Capacitor · design spec
- OpenAPI-driven type generation: Type system and API contracts
- Multi-tenant isolation contract: Multi-tenancy, accounts, and patient access
Tooling
Section titled “Tooling”- Optional SQLite import tooling:
backend/scripts/when migrating from a legacy SQLite file