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:
| Document | Role |
|---|---|
| 02-REQUIREMENTS.md | Business requirements, FR/NFR status, use cases |
| 01-ARCHITECTURE.md | Technical architecture, stack, evolution model |
| 04-ROADMAP.md | Posture, topology, launch checklist, resolution queue |
| 13-MARKETING-AND-SUBDOMAIN-DEPLOYMENT.md | Marketing site deployment |
| 24-SUBSCRIPTION-BILLING-AND-TIER-LIMITS.md | Billing implementation detail |
| 23-SUBSCRIPTION-TIER-ENTITLEMENTS-MATRIX.md | Tier × feature matrix |
| 04-ROADMAP.md | Phased delivery plan |
1. Document purpose and conventions
Section titled “1. Document purpose and conventions”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:
| Label | Meaning |
|---|---|
| [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.
2. Executive summary
Section titled “2. Executive summary”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).
3. Business context
Section titled “3. Business context”3.1 Problem statement
Section titled “3.1 Problem statement”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.
3.2 Solution positioning
Section titled “3.2 Solution positioning”| Dimension | Design choice |
|---|---|
| Customer | English-speaking families (AU, NZ, UK, US, CA, IE first) |
| Delivery | Web PWA today; native app store presence [Target] |
| Commercial model | Annual subscription only; three tiers; Stripe Adaptive Pricing at checkout |
| Data residency | Single PostgreSQL per deployment; tenant isolation in app + RLS |
| Growth | Tier 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.
| ID | Use case | Built modules (solution building blocks) | Major future gaps |
|---|---|---|---|
| UC-01 | Family medication coordinator | Medication dispensing, care calendar, prescriptions | Handover, observations |
| UC-02 | Child with chronic condition | Medication, calendar, pain, vitals, key contacts | Observations, clinical episodes |
| UC-03 | Adult palliative home care | Calendar, medication, vitals, pain, prescriptions, contacts, shopping | Handover, goals of care, episodes, caregiver wellbeing |
| UC-04 | Complex paediatric palliative | Above + sleep | Observations, therapy, equipment, goals of care, care intelligence, patient voice |
| UC-05 | Aged care network | Calendar, medication, vitals, sleep, shopping, contacts | Observations, handover, caregiver wellbeing |
| UC-06 | Disability support coordination | Calendar, medication, contacts, shopping | Therapy, equipment, goals of care, patient voice |
| UC-07 | Respiratory palliative (e.g. IPF) | Calendar, medication, vitals, pain, sleep, contacts, prescriptions | respiratory_oxygen, goals of care, episodes, equipment |
| UC-08 | Advanced dementia palliative | Calendar, medication, sleep, pain, contacts, shopping | behaviour_tracking, care protocols, cognitive tracking, swallowing safety, observational pain |
4. Scope
Section titled “4. Scope”4.1 In scope (this repository)
Section titled “4.1 In scope (this repository)”| Layer | Scope |
|---|---|
| Web application | React 19 SPA/PWA, 31 page components, module-gated routes |
| API | FastAPI, 29 router modules, dual mount /api and partial /api/v1 |
| Data | PostgreSQL 16, 68 numbered migrations (V001–V066), schema.sql baseline |
| Marketing | marketing/palliative/ static site + Cloudflare Worker gate |
| Billing | Stripe Checkout, webhooks, tier catalog, limits enforcement |
| Operations | Docker Compose production profile, Cloudflare Tunnel, backup runbooks |
| AI (optional) | LM Studio / Qwen2.5-VL prescription scan (server-side only) |
4.2 Out of scope (explicit)
Section titled “4.2 Out of scope (explicit)”- 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”5.1 High-level logical view [Current]
Section titled “5.1 High-level logical view [Current]”5.2 Domain decomposition
Section titled “5.2 Domain decomposition”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.
[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]”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.
6.1 Repository layout
Section titled “6.1 Repository layout”| Path | Responsibility | Maturity |
|---|---|---|
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.json | Tier catalog, limits, module slugs | [Current] — SSOT for commercial rules |
docker-compose.yml | Postgres, PgBouncer, Redis, app, scan_worker | [Current] |
cloudflared/ | Tunnel config for app.lyncareos.com | [Operational] |
6.2 Backend surface area
Section titled “6.2 Backend surface area”| Metric | Count | Notes |
|---|---|---|
| Router modules | 29 | Registered in main.py |
| Service modules | 25 | Business logic concentration varies |
| Repository modules | 5 | dispensings, analytics, notifications, pain, shopping |
| Migration files | 68 | Latest: V066__add_dose_changed_at.sql |
| pytest modules | 45 | Auth, billing, RLS, modules, Stripe flows |
| Inline SQL in routers | ~270 execute call sites | Layering debt — see §13 |
| Inline SQL in services | ~60 execute call sites | Billing, 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).
6.3 Frontend surface area
Section titled “6.3 Frontend surface area”| Metric | Count | Notes |
|---|---|---|
| Page components | 31 | Including 4 admin pages |
| Data fetching | useState + useEffect | No TanStack Query [Target] |
| API client | frontend/src/lib/api.ts | Centralised; ESLint blocks raw fetch in pages |
| Module gating | ModuleGate + ModuleContext | Mirrors server require_module |
| Code splitting | React.lazy on heavy routes | Dashboard/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 slug | Tier(s) | API routers | UI pages | Repository layer |
|---|---|---|---|---|
medication_dispensing | All | medicines, reason_types, dispensings, analytics, audit, medication_groups | Log, History, Analytics, Medication Schedule | dispensings, analytics |
care_calendar | Essential+ | patients, care_shifts, patient_appointments | Calendar, Schedule, Patients | — (SQL in routers) |
prescription_management | Family+ | scripts | Scripts, ScriptDetail | — |
sleep_tracking | Family+ | sleep | SleepPattern | — |
vitals_tracking | Family+ | vitals | VitalsTracking | vitals_service |
key_contacts | Family, Complete | key_contacts | KeyContacts | — |
pain_tracking | Complete | pain, mind, pain_settings | PainTracking | pain |
shopping | Complete | shopping, admin_shopping | Shopping, ShoppingCatalogAdmin | shopping |
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]”| Concern | Implementation | Location |
|---|---|---|
| Authentication | JWT HS256 access + HttpOnly refresh cookie | backend/auth.py, routers/auth.py |
| MFA | TOTP, AES-GCM at rest | services/mfa_service.py, services/crypto.py |
| Google sign-in | Server ID token verify + marketing GIS | services/google_auth_service.py |
| PWA iOS OAuth handoff | Session create / poll / callback | routers/pwa_auth.py |
| Rate limiting | slowapi + Redis; JWT signature as key | middleware/rate_limit.py |
| Tenant isolation | tenant_id in queries + RLS V034 | All clinical routers |
| Patient scope | patient_access role checks | Patient-scoped endpoints |
| Audit trail | audit_log on clinical mutations | Routers + triggers V033 |
| Background jobs | APScheduler, per-tenant 06:00 local | services/scheduler.py |
| Real-time shopping | SSE + Redis pub/sub + one-time tickets | services/sse_tickets.py, shopping router |
| Prescription scan | Redis queue + worker + SSE result | workers/scan_worker.py, services/scan_queue.py |
| Care alerts (in-app) | PostgreSQL + APScheduler | services/alert_service.py, routers/alerts.py |
| Tier limits | HTTP 402 at capacity | services/tier_limits.py |
| File uploads | UPLOADS_DIR volume | Prescriptions, contacts, shopping, proof-of-dose |
7. Marketing solution design
Section titled “7. Marketing solution design”7.1 Purpose and placement
Section titled “7.1 Purpose and placement”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.
| Domain | Technology | Role |
|---|---|---|
lyncareos.com, www.lyncareos.com | Cloudflare Pages project lyncareos-marketing | Static hosting |
| Root content | marketing/palliative/index.html | Hero, pricing, signup modal |
| Edge logic | marketing/palliative/_worker.js | Private-beta gate [Current] |
| Product login | Link to https://app.lyncareos.com | Existing 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]”Operational characteristics:
/robots.txtalways returnsDisallow: /while gated — SEO isolation.- Favicon and
/icons/*pass through so splash branding works. - Launch path: set
GATE_ENABLED = falseor remove_worker.jsand 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:
| Integration | Endpoint | Purpose |
|---|---|---|
| Tier catalog | GET /api/billing/tiers | Prices, module lists, GOOGLE_CLIENT_ID for GIS |
| FX preview | GET /api/billing/fx?to={code} | Local currency approximation on cards |
| Password signup | POST /api/stripe/start-signup | Create pending_signups, redirect to Checkout |
| Google signup | POST /api/stripe/start-signup-google | Pending row with google_sub |
| Stripe.js | Hosted Checkout | Adaptive 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]”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]”| Item | Requirement / debt | Priority |
|---|---|---|
| FX resilience | D14 — stale cache, second upstream, startup warm | High for launch UX |
| Public robots.txt | Real sitemap when gate lifted | Launch |
| Invite-only registration | REQ-AUTH-11 INVITE_ONLY_REGISTRATION | Policy |
| Localised marketing copy | REQ-I18N / §7.35 | Wave 1 i18n |
| Zero Trust Access allowlist | Alternative/complement to worker gate | Optional |
8. Billing and subscription solution design
Section titled “8. Billing and subscription solution design”8.1 Commercial model [Current]
Section titled “8.1 Commercial model [Current]”| Tier slug | Display name | USD/year | Core modules |
|---|---|---|---|
essential | Essential | $39 | medication_dispensing, care_calendar |
professional | Family | $69 | + prescriptions, sleep, vitals, key contacts (read) |
complete | Complete | $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_recipientson 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]”8.3 Lifecycle flows
Section titled “8.3 Lifecycle flows”8.3.1 New subscriber (signup) [Current]
Section titled “8.3.1 New subscriber (signup) [Current]”- Marketing or app initiates
start-signup/start-signup-google. - Row in
pending_signupsholds tier, auth material, opaque token. - Stripe Checkout session created; user pays.
- Webhook
checkout.session.completed→_provision_from_pending_signup:users,tenants,tenant_memberships,subscriptions, Stripe customer linkage.
- 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]”- Admin
POST /api/stripe/upgrade-tierwithnew_tier_slug. - One-time Stripe Coupon = prior annual amount in billing currency (local row if applicable).
- Checkout for new tier price with coupon applied.
- Webhook → cancel old subscription billing cycle, sync modules, reset
annual_anniversary_at.
8.3.3 Downgrade (deferred) [Current]
Section titled “8.3.3 Downgrade (deferred) [Current]”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.)
8.3.4 In-app upgrade surfaces [Current]
Section titled “8.3.4 In-app upgrade surfaces [Current]”| Surface | Behaviour |
|---|---|
UpgradeGate component | Shown when HTTP 402 or module disabled |
ModuleUpgrade page | Per-module marketing copy + upgrade CTA |
| Settings → Subscriptions | Admin view of active modules |
| Stripe Customer Portal | Invoice and payment method management |
8.4 Data model (billing) [Current]
Section titled “8.4 Data model (billing) [Current]”| Table | Role |
|---|---|
stripe_tiers | Tier slug, Stripe price IDs, limits JSONB |
stripe_tier_local_prices | Per-currency price IDs and amounts |
subscriptions | Tenant module entitlements (active / trial) |
stripe_customers | Maps tenant → Stripe customer |
pending_signups | Pre-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.
9. Data architecture
Section titled “9. Data architecture”9.1 Principles
Section titled “9.1 Principles”- PostgreSQL is the single source of truth — no authoritative client caches for clinical figures.
- Every PHI query filters by
tenant_id— RLS backstop on PHI tables (V034). - Schema changes only via migrations —
schema.sql+V###__*.sqlapplied at startup. - Clinical mutations audit in the same transaction —
audit_logappend-only. - 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]”9.3 Domain table inventory
Section titled “9.3 Domain table inventory”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.).
9.4 Files and uploads [Current]
Section titled “9.4 Files and uploads [Current]”| Storage | Path pattern | Content |
|---|---|---|
Docker volume lyncare_uploads | /app/uploads/<tenant_id>/ (new); legacy flat root supported | Prescription 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) |
| DB | URL columns on entities | Bare filename only; tenant enforced on serve via DB + image_path(filename, tenant_id) |
10. Security and compliance design
Section titled “10. Security and compliance design”10.1 Security architecture [Current]
Section titled “10.1 Security architecture [Current]”| Control | Design |
|---|---|
| Transport | TLS at Cloudflare; HSTS in production |
| Session | Short-lived access JWT in memory; refresh HttpOnly cookie |
| AuthZ | require_tenant_member, require_module, patient_access role checks |
| Defence in depth | RLS app_current_tenant_id() on PHI tables |
| Rate limiting | Auth, signup, invitation verify — signature-keyed buckets |
| Headers | CSP (API + marketing), X-Frame-Options: DENY, nosniff |
| Secrets | .env.production on host; never in frontend VITE_* except public keys |
| PHI logging | No patient names/DOB in application logs |
| MFA | Optional 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 intest_data_deletion.py).
10.3 Residual risks (accepted or planned)
Section titled “10.3 Residual risks (accepted or planned)”| Risk | Mitigation / plan |
|---|---|
| SQL predominantly in routers | RLS backstop; refactor to services/repositories (D6) |
Some SELECT * in routers | Tier 2 lint script; explicit column lists (rules) |
| Single-region deployment | Documented; multi-region deferred (D3) |
| LM Studio optional / off in prod | Graceful scan errors (D10) |
| Marketing FX 503 | D14 work items |
11. Deployment and operations architecture
Section titled “11. Deployment and operations architecture”11.1 Environment model
Section titled “11.1 Environment model”| Environment | Meaning | Database |
|---|---|---|
| Dev | dev-start.ps1, API :8021, Vite :5173 | lyncareos_dev |
| Optional Compose rehearsal | docker compose --profile production on non-prod machine | Docker volume (non-authoritative) |
| Production | Operations host, .env.production, tunnel to :8020 | lyncare_pg_data authoritative |
See 00-INDEX.md — Terminology.
11.2 Production physical architecture [Current]
Section titled “11.2 Production physical architecture [Current]”11.3 Scalability posture [Current + Target]
Section titled “11.3 Scalability posture [Current + Target]”| Stage | Posture |
|---|---|
| Day 1 | Single host, 2 Uvicorn workers, connection pool 10, Redis for shared state |
| Growth | Enable PgBouncer profile, tune DB_POOL_MAX, optional read replica URL |
| 100k model | Documented in 17-HARDENING-SCALE-RUNBOOK.md Part I — not day-1 target |
| Observability | Prometheus / pg_stat_statements deferred (D1, D2) |
12. Integration catalogue
Section titled “12. Integration catalogue”| System | Direction | Protocol | Purpose |
|---|---|---|---|
| Stripe | Outbound + inbound webhook | HTTPS REST | Billing |
| Google OAuth | Inbound ID token | HTTPS | Sign-in and signup |
| Cloudflare Tunnel | Outbound from host | QUIC | Expose app without inbound ports |
| Cloudflare Pages | Deploy static | Wrangler CLI | Marketing |
| Frankfurter | Outbound | HTTPS | FX rates for marketing preview |
| LM Studio | Outbound from worker | OpenAI-compatible HTTP | Prescription OCR/parse |
| Care alerts (in-app) | Browser poll + Badging API | HTTPS /api/alerts | Shared team alert queue + icon badge |
[Target] APNs, FCM, HealthKit, Health Connect — post-Capacitor.
13. Code review — technical assessment
Section titled “13. Code review — technical assessment”13.1 Strengths (verified in repository)
Section titled “13.1 Strengths (verified in repository)”- End-to-end commercial stack — marketing → pending signup → Stripe → webhook provisioning → onboarding is implemented and tested (
test_signup_flow.py,test_stripe.py). - Defence in depth for tenancy — application filters plus RLS migration
V034; dedicatedtest_rls.py. - Operational hardening scaffold — Redis SSE tickets, signature-based rate limits, scan worker decoupling, PgBouncer/read-replica compose profiles.
- Frontend architecture discipline — central API client, ESLint architectural rules,
ErrorBoundaryper route, lazy loading. - Broad automated test coverage — 45 backend test modules spanning auth, clinical domains, billing, migrations.
- Module gating consistency — server
require_modulealigned withtiers.jsonand UIModuleGate.
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:
| Pattern | Current state | Target state |
|---|---|---|
| SQL in routers | Dominant (~270 execute sites) | Routers delegate to services/repos |
| Repository coverage | 5 domains only | All clinical domains |
| Service coverage | Strong in billing, notifications, shopping, pain/vitals/mind | All routers thin |
SELECT * | Present in several routers/repos | Explicit column lists |
| Frontend types | Manual in api.ts | OpenAPI-generated api.types.ts (REQ-PLAT-10) |
| Data fetching | useEffect per page | TanStack 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.
13.3 Requirements fulfilment snapshot
Section titled “13.3 Requirements fulfilment snapshot”Approximate distribution from 02-REQUIREMENTS.md §7 (varies by module):
| Status | Scope |
|---|---|
| Done | Platform auth, eight modules’ core FRs, PWA, Web Push, billing, marketing signup, audit, RLS |
| Partial | Care 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 |
14. Target-state solution design
Section titled “14. Target-state solution design”14.1 Target logical architecture
Section titled “14.1 Target logical architecture”The target architecture extends the current platform — it does not replace it. Four capability layers stack on the existing FastAPI + PostgreSQL core:
14.2 Future module roadmap (solution view)
Section titled “14.2 Future module roadmap (solution view)”Future modules follow a repeatable delivery pattern:
- Migration: tables + RLS policies + indexes.
require_module(new_slug)router(s).- Service layer (avoid repeating router-SQL antipattern for new code).
- Pydantic models in
models.py. - TypeScript types (generated once REQ-PLAT-10 lands).
- UI page(s) behind
ModuleGate. - Tier assignment in
tiers.json+ seeder. - 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]”| Component | Design |
|---|---|
| UI strings | react-i18next namespaces per module |
| Locale config | Per-country terminology overrides from §1.8 table |
| Tenant default | tenants.locale |
| User override | users.locale_override |
| Stripe | Per-locale currency already supported via local prices |
| Layout | Logical CSS properties (NFR-12) before first RTL locale |
14.4 Native client architecture [Target]
Section titled “14.4 Native client architecture [Target]”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_typecolumn) (REQ-NATIVE-03). - Preserve
tokenStore, relative/apiURLs, noblob: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).
14.5 API evolution [Target]
Section titled “14.5 API evolution [Target]”| Change | Rationale |
|---|---|
/api/v1 as canonical prefix | Mobile client stability |
| OpenAPI-generated types | Contract drift prevention |
| Versioned deprecation window | Maintain /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)”| Workstream | Outcomes |
|---|---|
| Infrastructure | Stable VPS migration (D9); tunnel and backups verified |
| Billing | Stripe live keys; webhook verification (21) |
| Marketing | Lift beta gate; fix FX resilience (D14); OAuth origins for www |
| Security | Optional MFA_ENCRYPTION_KEY before SECRET_KEY rotation (D13) |
| Operations | CI 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:
- Handover + observations — shift continuity (REQ-CAL-10–14, REQ-OBS-*).
- Goals of care — safety-critical ACP (REQ-GOC-*).
- Behaviour + care protocols — dementia-centric (REQ-BEH-, REQ-PROT-).
- Respiratory module — IPF pathway (REQ-RO-*).
- Care intelligence — cross-domain analytics (REQ-CI-*).
15.4 Phase D — Global and native
Section titled “15.4 Phase D — Global and native”- 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/corewhen mobile team starts (Phase 1 roadmap).
Dates are indicative planning anchors — see 04-ROADMAP.md for committed phase ordering.
16. Non-functional requirements summary
Section titled “16. Non-functional requirements summary”| ID | Requirement | Current | Target |
|---|---|---|---|
| NFR-1 | Availability | Single-host SLA informal | VPS + monitoring |
| NFR-2 | Offline / resilience | Online-only | Write queue TBD |
| NFR-5 | Performance | Redis cache, ECharts; no perf CI | Perf budget in CI |
| NFR-6 | Accessibility | Partial Headless UI | Full WCAG audit |
| NFR-7 | Security | OWASP-aligned private beta | Continuous dependency audit |
| NFR-11 | i18n | English only | react-i18next Wave 1 |
| NFR-12 | RTL | Physical Tailwind | Logical properties |
17. Risks, dependencies, and known debts
Section titled “17. Risks, dependencies, and known debts”Consolidated from 32-KNOWN-DEBTS-REGISTER and code review.
| ID | Item | Impact | Mitigation |
|---|---|---|---|
| D6 | SQL in routers | Maintainability, test gaps | Incremental service extraction; new modules use services |
| D9 | Workstation production | Availability / backup risk | VPS migration before live payments |
| D10 | LM Studio disconnected | Prescription scan disabled | Configure tunnel URL or accept graceful failure |
| D12 | Manual deploy | Slow, error-prone releases | CI build + gated deploy (02 - ARCHITECTURE_DESIGN/12-CI-REFERENCE.md) |
| D14 | FX single upstream | Blank local prices on marketing | Stale cache + warm on boot |
| D1–D3 | Observability / multi-region | Limited ops visibility | Enable when scale demands |
| Product | 15 Future modules | Use case gaps | Phased module delivery §15.3 |
| Engineering | No OpenAPI types | Contract drift | REQ-PLAT-10 |
External dependencies: Stripe availability, Cloudflare Tunnel agent, Google OAuth client configuration, optional Frankfurter/LM Studio reachability.
18. Quality attributes verification
Section titled “18. Quality attributes verification”| Attribute | Verification mechanism |
|---|---|
| Correctness | 45 pytest modules; Vitest frontend tests |
| Security | test_rls.py, test_auth_*, rate limit tests, manual OWASP review |
| Tenant isolation | RLS + code review checklist (rules.mdc Tier 3) |
| Billing integrity | test_signup_flow.py, test_subscription_lifecycle.py, Stripe webhook tests |
| UX resilience | ErrorBoundary on all protected routes |
| Architecture compliance | ruff check, npm run validate:architecture, planned Tier 2 scripts |
Pre-merge commands (from project rules):
cd frontend; npm run validate:architecture; npm run lint:strict; npm run testcd backend; ruff check .; python -m pytest tests/ -x19. Appendices
Section titled “19. Appendices”Appendix A — Key file index
Section titled “Appendix A — Key file index”| Concern | Path |
|---|---|
| API entry | backend/main.py |
| Tier catalog | backend/billing/tiers.json |
| Auth | backend/auth.py, backend/routers/auth.py |
| Stripe | backend/routers/stripe.py, backend/services/stripe_provisioning.py |
| Marketing gate | marketing/palliative/_worker.js |
| Marketing page | marketing/palliative/index.html |
| Frontend routes | frontend/src/App.tsx |
| API client | frontend/src/lib/api.ts |
| Compose production | docker-compose.yml |
| Migrations | backend/migrations/V*.sql |
Appendix B — Glossary
Section titled “Appendix B — Glossary”| Term | Definition |
|---|---|
| Tenant | Subscriber family account; isolation boundary |
| Patient | Person in care |
| Module | Feature package gated by subscription slug |
| Carer / Observer | Roles via tenant_memberships and patient_access |
| PHI | Protected health information — names, clinical notes, etc. |
Appendix C — Document history
Section titled “Appendix C — Document history”| Date | Version | Change |
|---|---|---|
| 2026-05-18 | 1.0 | Initial 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.