Skip to content

27 — LynCareOS Solution Design Document

Version: 1.3
Last Updated: 2026-08-06 13:33:14
Status: Authoritative synthesis — current state (as implemented in this repository) and target state (as defined in product and architecture objectives)

Audience: Product leadership, engineers, operators, investors, and security reviewers.

Related documents:

DocumentRole
02-REQUIREMENTS.mdBusiness requirements, FR/NFR status, use cases
01-ARCHITECTURE.mdTechnical architecture, stack, evolution model
04-ROADMAP.mdPosture, topology, launch checklist, resolution queue
13-MARKETING-AND-SUBDOMAIN-DEPLOYMENT.mdMarketing site deployment
24-SUBSCRIPTION-BILLING-AND-TIER-LIMITS.mdBilling implementation detail
23-SUBSCRIPTION-TIER-ENTITLEMENTS-MATRIX.mdTier × feature matrix
04-ROADMAP.mdPhased delivery plan

This Solution Design Document (SDD) describes what LynCareOS is, how it is built today, and how it is intended to evolve. It is written to industry practice for solution architecture: problem → context → logical design → physical deployment → gaps → roadmap.

Conventions used in this document:

LabelMeaning
[Current]Implemented and verifiable in this repository
[Partial]Started but incomplete against requirements or target layering
[Target]Required by 02-REQUIREMENTS.md or 01-ARCHITECTURE.md but not yet built
[Operational]Live or deployable outside application code (Cloudflare, Stripe dashboard, operations host)

Source of truth for behaviour: running API + PostgreSQL schema + frontend routes. Module specs may describe polish not yet shipped; this SDD defers to code when they diverge.


LynCareOS is a multi-tenant family care SaaS platform: one deployment serves many isolated subscriber families (tenants), each coordinating medication, schedules, clinical observations, and team communication around one or more people in care (patients). The product is subscription-gated (Essential · Family · Complete), privacy-first (single-region PostgreSQL, no third-party analytics), and compliance-oriented (audit trail, RLS backstop, OWASP-aligned controls).

[Current] The platform is in private beta:

  • Product: https://app.lyncareos.com — React 19 PWA + FastAPI on an operations host (Docker Compose production profile, Cloudflare Tunnel).
  • Marketing: https://lyncareos.com — static site on Cloudflare Pages with a private-beta worker gate; full marketing experience requires a preview cookie.
  • Billing: Stripe end-to-end in test mode — credentials-first signup, Checkout, webhooks, tier provisioning, upgrade-only-pay-difference, Customer Portal.
  • Modules shipped: eight clinical/coordination modules (see §6); fifteen+ future module slugs specified in requirements only.

[Target] Evolution adds: fifteen Future clinical modules, internationalisation (11 Wave-1 languages), Capacitor native apps (APNs/FCM), OpenAPI-generated TypeScript contracts, and horizontal scale patterns already scaffolded (PgBouncer, Redis, read replica, scan worker).


Families caring for loved ones at home rely on fragmented tools (paper charts, messaging apps, spreadsheets). Institutional clinical software is unsuitable: expensive, clinician-centric, and not designed for informal care circles. LynCareOS is a family support care solution — not a medical app — addressing coordination, medication safety, and longitudinal wellbeing tracking for home-based care without positioning as a regulated health-provider or clinical product. See 26-REGULATORY-APPLICABILITY-AND-CONTROL-MAP.md.

DimensionDesign choice
CustomerEnglish-speaking families (AU, NZ, UK, US, CA, IE first)
DeliveryWeb PWA today; native app store presence [Target]
Commercial modelAnnual subscription only; three tiers; Stripe Adaptive Pricing at checkout
Data residencySingle PostgreSQL per deployment; tenant isolation in app + RLS
GrowthTier limits + contextual UpgradeGate prompts at capacity boundaries

3.3 Primary use cases (requirements traceability)

Section titled “3.3 Primary use cases (requirements traceability)”

Requirements were prioritised against eight documented use cases (UC-01–UC-08) in 02-REQUIREMENTS.md §1.7. The table below maps each use case to built versus future capability at a solution level.

IDUse caseBuilt modules (solution building blocks)Major future gaps
UC-01Family medication coordinatorMedication dispensing, care calendar, prescriptionsHandover, observations
UC-02Child with chronic conditionMedication, calendar, pain, vitals, key contactsObservations, clinical episodes
UC-03Adult palliative home careCalendar, medication, vitals, pain, prescriptions, contacts, shoppingHandover, goals of care, episodes, caregiver wellbeing
UC-04Complex paediatric palliativeAbove + sleepObservations, therapy, equipment, goals of care, care intelligence, patient voice
UC-05Aged care networkCalendar, medication, vitals, sleep, shopping, contactsObservations, handover, caregiver wellbeing
UC-06Disability support coordinationCalendar, medication, contacts, shoppingTherapy, equipment, goals of care, patient voice
UC-07Respiratory palliative (e.g. IPF)Calendar, medication, vitals, pain, sleep, contacts, prescriptionsrespiratory_oxygen, goals of care, episodes, equipment
UC-08Advanced dementia palliativeCalendar, medication, sleep, pain, contacts, shoppingbehaviour_tracking, care protocols, cognitive tracking, swallowing safety, observational pain

LayerScope
Web applicationReact 19 SPA/PWA, 31 page components, module-gated routes
APIFastAPI, 29 router modules, dual mount /api and partial /api/v1
DataPostgreSQL 16, 68 numbered migrations (V001–V066), schema.sql baseline
Marketingmarketing/palliative/ static site + Cloudflare Worker gate
BillingStripe Checkout, webhooks, tier catalog, limits enforcement
OperationsDocker Compose production profile, Cloudflare Tunnel, backup runbooks
AI (optional)LM Studio / Qwen2.5-VL prescription scan (server-side only)
  • Native iOS/Android binaries ([Target] — Capacitor per REQ-NATIVE-02)
  • Country-operator console and operator_tenants ([Target] — REQ-I18N-14)
  • Offline write queue ([Future] — NFR-2)
  • Separate shopping product database (shopping stays bundled; see known debt D4)
  • Clinical registration or provider billing to insurers/governments

5. Solution overview — logical architecture

Section titled “5. Solution overview — logical architecture”

External services

Data & cache

Application layer

Edge & identity

Experience layer

GET api billing *

POST api stripe start-signup

HTTPS api

Bearer JWT

webhook

Marketing site

lyncareos.com

Cloudflare Pages + Worker

Care app PWA

app.lyncareos.com

React 19 + Service Worker

Cloudflare

TLS , Tunnel , optional Access

FastAPI

Module gates , JWT , Webhooks

scan_worker

Redis queue , LM Studio

PostgreSQL 16

Tenant-scoped PHI + audit

Redis 7

SSE , rate limits , cache , pub/sub

Stripe

Checkout , Portal , Webhooks

Google OAuth

ID token verify

LM Studio

Prescription vision

Frankfurter API

FX rates for marketing

The solution is organised as platform services plus eight product modules. Each module is a bounded capability set enforced by require_module(slug) on the API and ModuleGate in the UI.

Product modules - built

medication_dispensing

care_calendar

prescription_management

sleep_tracking

vitals_tracking

pain_tracking

shopping

key_contacts

Platform services

Auth & MFA

Tenants & invitations

Billing & Stripe

Notifications , Web Push

Onboarding checklist

Audit log viewer

[Target] Fifteen additional module slugs (e.g. care_observations, goals_of_care, respiratory_oxygen) extend this diagram without replacing the platform layer — see §14.

5.3 Request lifecycle (authenticated API call) [Current]

Section titled “5.3 Request lifecycle (authenticated API call) [Current]”
PostgreSQLRedis rate limitFastAPICloudflare TunnelBrowser PWAPostgreSQLRedis rate limitFastAPICloudflare TunnelBrowser PWAHTTPS request with Authorization headerForward to port 8020Check JWT signature bucketDecode JWT and resolve tenantCheck tenant member and module accessParameterised SQL with tenant context for RLSRows as dictJSON response

6. Current-state component inventory (code review)

Section titled “6. Current-state component inventory (code review)”

Review performed 2026-05-18 against repository structure, router registration in backend/main.py, and layering scan.

PathResponsibilityMaturity
frontend/React 19, Vite 8, Tailwind 3, lib/api.ts contract[Current] — production UI
backend/FastAPI, routers, services, repositories, migrations[Current] — primary business logic
marketing/palliative/Public marketing HTML, assets, _worker.js gate[Current]
backend/billing/tiers.jsonTier catalog, limits, module slugs[Current] — SSOT for commercial rules
docker-compose.ymlPostgres, PgBouncer, Redis, app, scan_worker[Current]
cloudflared/Tunnel config for app.lyncareos.com[Operational]
MetricCountNotes
Router modules29Registered in main.py
Service modules25Business logic concentration varies
Repository modules5dispensings, analytics, notifications, pain, shopping
Migration files68Latest: V066__add_dose_changed_at.sql
pytest modules45Auth, billing, RLS, modules, Stripe flows
Inline SQL in routers~270 execute call sitesLayering debt — see §13
Inline SQL in services~60 execute call sitesBilling, signup, Stripe provisioning

API versioning: Most routes mount at /api/.... A subset also mounts under /api/v1/... (auth, users, billing, clinical routers) — clients today use /api from lib/api.ts; full /api/v1 cutover remains [Target] per roadmap.

OpenAPI: Interactive docs gated in production via EXPOSE_API_DOCS / ENVIRONMENT=production in main.py (contrasts with older doc 19 note — code now hides docs by default in production).

MetricCountNotes
Page components31Including 4 admin pages
Data fetchinguseState + useEffectNo TanStack Query [Target]
API clientfrontend/src/lib/api.tsCentralised; ESLint blocks raw fetch in pages
Module gatingModuleGate + ModuleContextMirrors server require_module
Code splittingReact.lazy on heavy routesDashboard/login eager

Primary routes (product): /, /calendar, /schedule, /log, /history, /analytics, /medication-schedule, /scripts, /sleep, /vitals, /pain, /shopping, /contacts, /more, /getting-started, admin paths under /admin/*.

6.4 Module implementation matrix [Current]

Section titled “6.4 Module implementation matrix [Current]”

Aligned with backend/billing/tiers.json and router registration.

Module slugTier(s)API routersUI pagesRepository layer
medication_dispensingAllmedicines, reason_types, dispensings, analytics, audit, medication_groupsLog, History, Analytics, Medication Scheduledispensings, analytics
care_calendarEssential+patients, care_shifts, patient_appointmentsCalendar, Schedule, Patients— (SQL in routers)
prescription_managementFamily+scriptsScripts, ScriptDetail—
sleep_trackingFamily+sleepSleepPattern—
vitals_trackingFamily+vitalsVitalsTrackingvitals_service
key_contactsFamily, Completekey_contactsKeyContacts—
pain_trackingCompletepain, mind, pain_settingsPainTrackingpain
shoppingCompleteshopping, admin_shoppingShopping, ShoppingCatalogAdminshopping

Placeholder: care_services appears in older roadmap text as a subscription slug without a dedicated router — not in current tiers.json.

6.5 Cross-cutting platform components [Current]

Section titled “6.5 Cross-cutting platform components [Current]”
ConcernImplementationLocation
AuthenticationJWT HS256 access + HttpOnly refresh cookiebackend/auth.py, routers/auth.py
MFATOTP, AES-GCM at restservices/mfa_service.py, services/crypto.py
Google sign-inServer ID token verify + marketing GISservices/google_auth_service.py
PWA iOS OAuth handoffSession create / poll / callbackrouters/pwa_auth.py
Rate limitingslowapi + Redis; JWT signature as keymiddleware/rate_limit.py
Tenant isolationtenant_id in queries + RLS V034All clinical routers
Patient scopepatient_access role checksPatient-scoped endpoints
Audit trailaudit_log on clinical mutationsRouters + triggers V033
Background jobsAPScheduler, per-tenant 06:00 localservices/scheduler.py
Real-time shoppingSSE + Redis pub/sub + one-time ticketsservices/sse_tickets.py, shopping router
Prescription scanRedis queue + worker + SSE resultworkers/scan_worker.py, services/scan_queue.py
Care alerts (in-app)PostgreSQL + APSchedulerservices/alert_service.py, routers/alerts.py
Tier limitsHTTP 402 at capacityservices/tier_limits.py
File uploadsUPLOADS_DIR volumePrescriptions, contacts, shopping, proof-of-dose

The marketing site is the acquisition channel: explain value, display tier pricing with local currency preview, and initiate credentials-first Stripe Checkout without exposing the full product UI to anonymous users.

DomainTechnologyRole
lyncareos.com, www.lyncareos.comCloudflare Pages project lyncareos-marketingStatic hosting
Root contentmarketing/palliative/index.htmlHero, pricing, signup modal
Edge logicmarketing/palliative/_worker.jsPrivate-beta gate [Current]
Product loginLink to https://app.lyncareos.comExisting subscribers

app.lyncareos.com is not gated by the marketing worker — it is served by the operations host tunnel independently.

7.2 Private-beta gate architecture [Current]

Section titled “7.2 Private-beta gate architecture [Current]”

false

true

yes

no

valid

invalid

GET lyncareos.com/

GATE_ENABLED?

env.ASSETS.fetch

Full marketing page

Valid _lco_preview cookie?

?preview=PREVIEW_SECRET

302 + Set-Cookie 90d

503 Private beta splash

X-Robots-Tag: noindex

Operational characteristics:

  • /robots.txt always returns Disallow: / while gated — SEO isolation.
  • Favicon and /icons/* pass through so splash branding works.
  • Launch path: set GATE_ENABLED = false or remove _worker.js and redeploy Pages (seconds, no DB change).

7.3 Marketing ↔ API integration [Current]

Section titled “7.3 Marketing ↔ API integration [Current]”

The marketing page is static but calls the live API for commercial accuracy:

IntegrationEndpointPurpose
Tier catalogGET /api/billing/tiersPrices, module lists, GOOGLE_CLIENT_ID for GIS
FX previewGET /api/billing/fx?to={code}Local currency approximation on cards
Password signupPOST /api/stripe/start-signupCreate pending_signups, redirect to Checkout
Google signupPOST /api/stripe/start-signup-googlePending row with google_sub
Stripe.jsHosted CheckoutAdaptive Pricing at payment

CORS: ALLOWED_ORIGINS on the app must include https://lyncareos.com and https://www.lyncareos.com for cross-origin API calls from Pages.

Content Security Policy: Marketing _headers and API SecurityHeadersMiddleware allow Stripe, Google, Tailwind CDN, and app subdomain origins only.

7.4 Signup UX flow (marketing origin) [Current]

Section titled “7.4 Signup UX flow (marketing origin) [Current]”
"Care app subdomain"Stripe CheckoutFastAPIMarketing pageProspect"Care app subdomain"Stripe CheckoutFastAPIMarketing pageProspectalt[Password path][Google path]Select tier and open modalEnter username, email, passwordPOST stripe start-signuppending_signups and encrypted password cookieGIS ID tokenPOST stripe start-signup-googleCreate Checkout sessionHosted payment"webhook checkout.session.completed"Provision user, tenant, subscriptionsRedirect to billing success URLWelcome modal and onboarding checklist

Key implementation files: marketing/palliative/index.html, backend/routers/stripe.py, backend/services/signup_service.py, backend/services/stripe_provisioning.py, frontend/src/pages/BillingSuccess.tsx, frontend/src/components/WelcomeModal.tsx.

7.5 Marketing future enhancements [Target]

Section titled “7.5 Marketing future enhancements [Target]”
ItemRequirement / debtPriority
FX resilienceD14 — stale cache, second upstream, startup warmHigh for launch UX
Public robots.txtReal sitemap when gate liftedLaunch
Invite-only registrationREQ-AUTH-11 INVITE_ONLY_REGISTRATIONPolicy
Localised marketing copyREQ-I18N / §7.35Wave 1 i18n
Zero Trust Access allowlistAlternative/complement to worker gateOptional

8. Billing and subscription solution design

Section titled “8. Billing and subscription solution design”
Tier slugDisplay nameUSD/yearCore modules
essentialEssential$39medication_dispensing, care_calendar
professionalFamily$69+ prescriptions, sleep, vitals, key contacts (read)
completeComplete$99+ shopping, pain_tracking, key contacts (write)
  • Billing period: annual only.
  • Checkout currency: Stripe Adaptive Pricing (customer location at Checkout).
  • Local price display: stripe_tier_local_prices + marketing FX preview (not authoritative — Checkout wins).
  • Add-on: extra_care_recipients on tenant (+$5/yr per person beyond tier cap).

Authoritative limits and module lists: backend/billing/tiers.json → seeder python -m scripts.stripe_seed_tiers.

8.2 Billing logical architecture [Current]

Section titled “8.2 Billing logical architecture [Current]”

Stripe

Runtime enforcement

Catalog layer

seed

tiers.json

limits , modules , USD

stripe_tiers

DB mirror

stripe_tier_local_prices

subscriptions

per-tenant module rows

tier_limits.py

HTTP 402

require_module()

HTTP 402

Checkout Sessions

signup , upgrade

Webhooks

Customer Portal

API handlers

stripe_provisioning.py

  1. Marketing or app initiates start-signup / start-signup-google.
  2. Row in pending_signups holds tier, auth material, opaque token.
  3. Stripe Checkout session created; user pays.
  4. Webhook checkout.session.completed → _provision_from_pending_signup:
    • users, tenants, tenant_memberships, subscriptions, Stripe customer linkage.
  5. Browser lands on /billing/success; client completes session and routes to onboarding.

8.3.2 Upgrade (pay difference only) [Current]

Section titled “8.3.2 Upgrade (pay difference only) [Current]”
  1. Admin POST /api/stripe/upgrade-tier with new_tier_slug.
  2. One-time Stripe Coupon = prior annual amount in billing currency (local row if applicable).
  3. Checkout for new tier price with coupon applied.
  4. Webhook → cancel old subscription billing cycle, sync modules, reset annual_anniversary_at.

Downgrades schedule for next renewal via POST /api/stripe/schedule-downgrade and APScheduler job — higher-tier access retained until effective date. (Schema evolved across V047/V049; behaviour documented in 24.)

SurfaceBehaviour
UpgradeGate componentShown when HTTP 402 or module disabled
ModuleUpgrade pagePer-module marketing copy + upgrade CTA
Settings → SubscriptionsAdmin view of active modules
Stripe Customer PortalInvoice and payment method management
TableRole
stripe_tiersTier slug, Stripe price IDs, limits JSONB
stripe_tier_local_pricesPer-currency price IDs and amounts
subscriptionsTenant module entitlements (active / trial)
stripe_customersMaps tenant → Stripe customer
pending_signupsPre-payment signup state (password or Google)

8.5 Billing pre-launch and live switchover [Operational]

Section titled “8.5 Billing pre-launch and live switchover [Operational]”

Documented in 21-STRIPE-LIVE-SWITCHOVER.md and 04-ROADMAP Current posture:

  • Swap sk_test / pk_test → live keys in .env.production.
  • Re-register webhook endpoint; run tier seeder.
  • End-to-end verification on marketing URL with live test card.

[Target] VPS migration before first live payment (debt D9) — workstation acceptable for private beta only.


  1. PostgreSQL is the single source of truth — no authoritative client caches for clinical figures.
  2. Every PHI query filters by tenant_id — RLS backstop on PHI tables (V034).
  3. Schema changes only via migrations — schema.sql + V###__*.sql applied at startup.
  4. Clinical mutations audit in the same transaction — audit_log append-only.
  5. Soft-delete where supported — no silent hard deletes on patient-linked records.

9.2 Entity relationship (core domains) [Current]

Section titled “9.2 Entity relationship (core domains) [Current]”

has

belongs

cares_for

grants

receives

entitles

receives

scheduled

prescribed

measured

reports

bills

tenants

tenant_memberships

users

patients

patient_access

subscriptions

dispensings

care_shifts

patient_scripts

patient_vitals

patient_pain_entries

stripe_customers

See 02-REQUIREMENTS.md §9 for the full built vs future table list. Built domains cover identity, patients, calendar, medications, prescriptions, sleep, vitals, pain/mind, contacts, shopping, notifications, billing, audit. Future domains add ~18 table groups (handover, observations, goals of care, respiratory, behaviour, etc.).

StoragePath patternContent
Docker volume lyncare_uploads/app/uploads/<tenant_id>/ (new); legacy flat root supportedPrescription images, proof-of-dose, shopping photos (services/images.py)
Docker volume lyncare_uploads/app/uploads/contact_attachments/<tenant_id>/Key contact note attachments
Docker volume lyncare_uploads/app/uploads/scan_stage/<tenant_id>/Ephemeral prescription scan staging (Redis worker)
DBURL columns on entitiesBare filename only; tenant enforced on serve via DB + image_path(filename, tenant_id)

ControlDesign
TransportTLS at Cloudflare; HSTS in production
SessionShort-lived access JWT in memory; refresh HttpOnly cookie
AuthZrequire_tenant_member, require_module, patient_access role checks
Defence in depthRLS app_current_tenant_id() on PHI tables
Rate limitingAuth, signup, invitation verify — signature-keyed buckets
HeadersCSP (API + marketing), X-Frame-Options: DENY, nosniff
Secrets.env.production on host; never in frontend VITE_* except public keys
PHI loggingNo patient names/DOB in application logs
MFAOptional TOTP; secrets encrypted with MFA_ENCRYPTION_KEY

10.2 Compliance-oriented behaviours [Current]

Section titled “10.2 Compliance-oriented behaviours [Current]”
  • Audit entries: tenant_id, performed_by, action, entity_type, entity_id, before, after, timestamp.
  • Tier limits and module gates prevent silent over-provisioning.
  • Data deletion on cancellation path implemented (V061, tested in test_data_deletion.py).
RiskMitigation / plan
SQL predominantly in routersRLS backstop; refactor to services/repositories (D6)
Some SELECT * in routersTier 2 lint script; explicit column lists (rules)
Single-region deploymentDocumented; multi-region deferred (D3)
LM Studio optional / off in prodGraceful scan errors (D10)
Marketing FX 503D14 work items

11. Deployment and operations architecture

Section titled “11. Deployment and operations architecture”
EnvironmentMeaningDatabase
Devdev-start.ps1, API :8021, Vite :5173lyncareos_dev
Optional Compose rehearsaldocker compose --profile production on non-prod machineDocker volume (non-authoritative)
ProductionOperations host, .env.production, tunnel to :8020lyncare_pg_data authoritative

See 00-INDEX.md — Terminology.

11.2 Production physical architecture [Current]

Section titled “11.2 Production physical architecture [Current]”

Operations host - Docker Compose production profile

Cloudflare

Internet

API calls

Browsers

Pages

lyncareos.com

Tunnel

app.lyncareos.com

app :8020

FastAPI + built SPA

pgbouncer

postgres

redis

scan_worker

cloudflared

host process

11.3 Scalability posture [Current + Target]

Section titled “11.3 Scalability posture [Current + Target]”
StagePosture
Day 1Single host, 2 Uvicorn workers, connection pool 10, Redis for shared state
GrowthEnable PgBouncer profile, tune DB_POOL_MAX, optional read replica URL
100k modelDocumented in 17-HARDENING-SCALE-RUNBOOK.md Part I — not day-1 target
ObservabilityPrometheus / pg_stat_statements deferred (D1, D2)

SystemDirectionProtocolPurpose
StripeOutbound + inbound webhookHTTPS RESTBilling
Google OAuthInbound ID tokenHTTPSSign-in and signup
Cloudflare TunnelOutbound from hostQUICExpose app without inbound ports
Cloudflare PagesDeploy staticWrangler CLIMarketing
FrankfurterOutboundHTTPSFX rates for marketing preview
LM StudioOutbound from workerOpenAI-compatible HTTPPrescription OCR/parse
Care alerts (in-app)Browser poll + Badging APIHTTPS /api/alertsShared team alert queue + icon badge

[Target] APNs, FCM, HealthKit, Health Connect — post-Capacitor.


  1. End-to-end commercial stack — marketing → pending signup → Stripe → webhook provisioning → onboarding is implemented and tested (test_signup_flow.py, test_stripe.py).
  2. Defence in depth for tenancy — application filters plus RLS migration V034; dedicated test_rls.py.
  3. Operational hardening scaffold — Redis SSE tickets, signature-based rate limits, scan worker decoupling, PgBouncer/read-replica compose profiles.
  4. Frontend architecture discipline — central API client, ESLint architectural rules, ErrorBoundary per route, lazy loading.
  5. Broad automated test coverage — 45 backend test modules spanning auth, clinical domains, billing, migrations.
  6. Module gating consistency — server require_module aligned with tiers.json and UI ModuleGate.

13.2 Architectural gaps (current vs target layering)

Section titled “13.2 Architectural gaps (current vs target layering)”

The project rules mandate Router → Service → Repository. Code review finds:

PatternCurrent stateTarget state
SQL in routersDominant (~270 execute sites)Routers delegate to services/repos
Repository coverage5 domains onlyAll clinical domains
Service coverageStrong in billing, notifications, shopping, pain/vitals/mindAll routers thin
SELECT *Present in several routers/reposExplicit column lists
Frontend typesManual in api.tsOpenAPI-generated api.types.ts (REQ-PLAT-10)
Data fetchinguseEffect per pageTanStack Query (roadmap Phase 0)

Risk treatment: RLS and audit triggers mitigate SQL-in-router risk; refactoring is maintainability and testability, not an emergency bypass of tenant checks.

Approximate distribution from 02-REQUIREMENTS.md §7 (varies by module):

StatusScope
DonePlatform auth, eight modules’ core FRs, PWA, Web Push, billing, marketing signup, audit, RLS
PartialCare shift recurrence (presets not full RRULE), analytics perf, some onboarding prompts
Future§7.15–§7.34 modules, i18n, native app, handover, care intelligence, invite-only mode

The target architecture extends the current platform — it does not replace it. Four capability layers stack on the existing FastAPI + PostgreSQL core:

Layer 4 - Engineering maturity

OpenAPI → TypeScript

TanStack Query

Prometheus metrics

Layer 3 - Client expansion

Capacitor iOS/Android

APNs + FCM push

HealthKit / Health Connect read

Layer 2 - Global reach

react-i18next

11 Wave-1 locales

CSS logical properties

operator_tenants

Layer 1 - Clinical depth modules

care_observations

goals_of_care

respiratory_oxygen

behaviour_tracking

+ 11 more slugs

Retained - current foundation

FastAPI + 8 modules

PostgreSQL + RLS + audit

Redis

14.2 Future module roadmap (solution view)

Section titled “14.2 Future module roadmap (solution view)”

Future modules follow a repeatable delivery pattern:

  1. Migration: tables + RLS policies + indexes.
  2. require_module(new_slug) router(s).
  3. Service layer (avoid repeating router-SQL antipattern for new code).
  4. Pydantic models in models.py.
  5. TypeScript types (generated once REQ-PLAT-10 lands).
  6. UI page(s) behind ModuleGate.
  7. Tier assignment in tiers.json + seeder.
  8. Audit triggers on mutations.

Tier policy [Target]: Most future clinical modules provision at Complete; family_journal and preventive_care at Family+ (REQ-MOD-23).

14.3 Internationalisation architecture [Target]

Section titled “14.3 Internationalisation architecture [Target]”
ComponentDesign
UI stringsreact-i18next namespaces per module
Locale configPer-country terminology overrides from §1.8 table
Tenant defaulttenants.locale
User overrideusers.locale_override
StripePer-locale currency already supported via local prices
LayoutLogical CSS properties (NFR-12) before first RTL locale

Capacitor wraps the existing SPA (REQ-NATIVE-02). Play first, then App Store. Design: native-store-clients.

  • Commerce: website Stripe SoT; free consumption-only store binaries (REQ-NATIVE-08…10) — no Stripe Checkout from store builds.
  • Optional native push plugins; dual-store device tokens (delivery_type column) (REQ-NATIVE-03).
  • Preserve tokenStore, relative /api URLs, no blob: persistence; resolve Capacitor cookie/session at implementation (design §7.2).
  • App Store compliance: no medical device claims (REQ-NATIVE-04).
  • Health platform import optional post-launch (REQ-NATIVE-05).
  • Store billing dual-rail only with PO sign-off (REQ-NATIVE-12).
ChangeRationale
/api/v1 as canonical prefixMobile client stability
OpenAPI-generated typesContract drift prevention
Versioned deprecation windowMaintain /api during transition

15. Transition roadmap (current → target)

Section titled “15. Transition roadmap (current → target)”

Aligned with 04-ROADMAP.md.

15.1 Phase A — Launch readiness (weeks, not months)

Section titled “15.1 Phase A — Launch readiness (weeks, not months)”
WorkstreamOutcomes
InfrastructureStable VPS migration (D9); tunnel and backups verified
BillingStripe live keys; webhook verification (21)
MarketingLift beta gate; fix FX resilience (D14); OAuth origins for www
SecurityOptional MFA_ENCRYPTION_KEY before SECRET_KEY rotation (D13)
OperationsCI build on main (D12 progress)

15.2 Phase B — Foundation hardening (parallel to feature work)

Section titled “15.2 Phase B — Foundation hardening (parallel to feature work)”
  • Extract SQL from highest-churn routers into services (care_shifts, scripts, patients first).
  • Introduce TanStack Query on new screens; migrate Dashboard and Calendar.
  • OpenAPI type generation in CI (REQ-PLAT-10).
  • Add Tier 2 architectural lint scripts from .cursor/rules.

15.3 Phase C — Clinical depth (module waves)

Section titled “15.3 Phase C — Clinical depth (module waves)”

Priority driven by UC-03, UC-04, UC-08:

  1. Handover + observations — shift continuity (REQ-CAL-10–14, REQ-OBS-*).
  2. Goals of care — safety-critical ACP (REQ-GOC-*).
  3. Behaviour + care protocols — dementia-centric (REQ-BEH-, REQ-PROT-).
  4. Respiratory module — IPF pathway (REQ-RO-*).
  5. Care intelligence — cross-domain analytics (REQ-CI-*).
  • Wave 1 i18n locales and operator model.
  • Capacitor Play-first when REQ-NATIVE-01 triggers (or PO override); consumption-only commerce (REQ-NATIVE-08); then iOS (REQ-NATIVE-11). See 04 §13.
  • Monorepo packages/core when mobile team starts (Phase 1 roadmap).
2026-05-012026-06-012026-07-012026-08-012026-09-012026-10-012026-11-012026-12-012027-01-012027-02-012027-03-012027-04-012027-05-012027-06-012027-07-012027-08-012027-09-012027-10-01Live Stripe + public marketing VPS production host Layering refactor + OpenAPI types TanStack Query adoption Handover + observations Goals of care Behaviour + protocols i18n Wave 1 Capacitor native apps LaunchHardeningClinical modulesGlobalLynCareOS solution evolution (indicative)

Dates are indicative planning anchors — see 04-ROADMAP.md for committed phase ordering.


IDRequirementCurrentTarget
NFR-1AvailabilitySingle-host SLA informalVPS + monitoring
NFR-2Offline / resilienceOnline-onlyWrite queue TBD
NFR-5PerformanceRedis cache, ECharts; no perf CIPerf budget in CI
NFR-6AccessibilityPartial Headless UIFull WCAG audit
NFR-7SecurityOWASP-aligned private betaContinuous dependency audit
NFR-11i18nEnglish onlyreact-i18next Wave 1
NFR-12RTLPhysical TailwindLogical properties

Consolidated from 32-KNOWN-DEBTS-REGISTER and code review.

IDItemImpactMitigation
D6SQL in routersMaintainability, test gapsIncremental service extraction; new modules use services
D9Workstation productionAvailability / backup riskVPS migration before live payments
D10LM Studio disconnectedPrescription scan disabledConfigure tunnel URL or accept graceful failure
D12Manual deploySlow, error-prone releasesCI build + gated deploy (02 - ARCHITECTURE_DESIGN/12-CI-REFERENCE.md)
D14FX single upstreamBlank local prices on marketingStale cache + warm on boot
D1–D3Observability / multi-regionLimited ops visibilityEnable when scale demands
Product15 Future modulesUse case gapsPhased module delivery §15.3
EngineeringNo OpenAPI typesContract driftREQ-PLAT-10

External dependencies: Stripe availability, Cloudflare Tunnel agent, Google OAuth client configuration, optional Frankfurter/LM Studio reachability.


AttributeVerification mechanism
Correctness45 pytest modules; Vitest frontend tests
Securitytest_rls.py, test_auth_*, rate limit tests, manual OWASP review
Tenant isolationRLS + code review checklist (rules.mdc Tier 3)
Billing integritytest_signup_flow.py, test_subscription_lifecycle.py, Stripe webhook tests
UX resilienceErrorBoundary on all protected routes
Architecture complianceruff check, npm run validate:architecture, planned Tier 2 scripts

Pre-merge commands (from project rules):

Terminal window
cd frontend; npm run validate:architecture; npm run lint:strict; npm run test
cd backend; ruff check .; python -m pytest tests/ -x

ConcernPath
API entrybackend/main.py
Tier catalogbackend/billing/tiers.json
Authbackend/auth.py, backend/routers/auth.py
Stripebackend/routers/stripe.py, backend/services/stripe_provisioning.py
Marketing gatemarketing/palliative/_worker.js
Marketing pagemarketing/palliative/index.html
Frontend routesfrontend/src/App.tsx
API clientfrontend/src/lib/api.ts
Compose productiondocker-compose.yml
Migrationsbackend/migrations/V*.sql
TermDefinition
TenantSubscriber family account; isolation boundary
PatientPerson in care
ModuleFeature package gated by subscription slug
Carer / ObserverRoles via tenant_memberships and patient_access
PHIProtected health information — names, clinical notes, etc.
DateVersionChange
2026-05-181.0Initial SDD — codebase review, marketing and billing design, current vs target architecture

Maintainers: Update this document when major architectural decisions land (new module family, billing model change, client platform shift). Bump Version and Last Updated using Get-Date -Format "yyyy-MM-dd HH:mm:ss" on each publish.