Skip to content

05 — Developer Guide

Conventions, workflows, and commands for working on LynCareOS. Read existing code before adding new code — the repository is the source of truth; this guide points to the patterns that are actually used.

Related: 01-ARCHITECTURE.md (stack and Docker), 02-REQUIREMENTS.md (solution scope), 03-DESIGN-SYSTEM.md (UI), 14-FRONTEND-PRESENTATION-STACK.md (presentation tools), 04-ROADMAP.md (phases and gaps).

Version: 1.72
Last Updated: 2026-08-05 17:38:42


LynCareOS/
├── backend/ Python FastAPI app
│ ├── main.py App factory, CORS, routers, static SPA; lifespan opens DB + tenant scheduler
│ ├── run_server.py Dev server (Windows-friendly; port 8021)
│ ├── config.py Environment variables (incl. LM Studio, uploads)
│ ├── database.py Pool, get_db(), init_db(), MODULES tuple
│ ├── billing/ tiers.json (Stripe bundles) · module_delivery.json (UX readiness)
│ │ module_delivery.py — live/partial/planned helpers
│ ├── auth.py JWT, dependencies (tenant, module, patient, …)
│ ├── models.py Pydantic models (where used)
│ ├── schema.sql Idempotent DDL supplement (PostgreSQL)
│ ├── schema/lyncareos_v1_baseline.sql Full v1 baseline (greenfield init_db)
│ ├── migrations/ Active VNNN__*.sql + runner.py; pre-v1 in archive/pre-v1/
│ ├── seed_admin.py Super-admin seed script
│ ├── requirements.txt
│ ├── care_modules/ Feature-flagged Care Profile board plugins (flags, manifests, board API)
│ ├── routers/ Feature routers (`/api/...` — not `/api/v1/`)
│ │ New: condition_packs.py · observations.py · help_requests.py
│ ├── services/ Domain services (lmstudio, images, shopping_service, care_shifts_service, …)
│ │ New: field_crypto.py · scan_queue_pg.py · condition_packs_service.py
│ │ observations_service.py · help_requests_service.py · patient_scripts_service.py
│ ├── repositories/ Pure SQL functions extracted from routers (care_shifts, alerts, pain, shopping)
│ │ New: condition_packs.py · observations.py · help_requests.py · medication_groups.py
│ ├── scripts/ Seeds, catalog tooling, CI gates (check_router_sql.py), one-off fix scripts
│ └── tests/ pytest (see §9)
├── frontend/ React + Vite + TypeScript
│ ├── src/
│ │ ├── pages/ Route-level screens
│ │ ├── components/ Shared UI + feature folders (shopping/, sleep/, calendar/, medication-schedule/, …)
│ │ │ New: condition-packs/ · observations/
│ │ │ Pain UI: pain/BodyMap.tsx · PainBodyMapTab.tsx — **2D only** (no 3D in launch bundle)
│ │ │ integrations/README.md — stub for future plug-in host files (no imports yet)
│ │ ├── care-modules/ Care board plugins (cancer, breathing) — lazy when VITE flag set
│ │ ├── context/ Auth, theme, module, patient; careModuleFlags = hook only
│ │ ├── hooks/ e.g. useAuthenticatedImage
│ │ ├── lib/api.ts fetch wrappers, token storage; re-exports OpenAPI + manual types
│ │ ├── lib/api.types.ts Auto-generated from openapi/openapi.json (do not edit)
│ │ ├── lib/api.contracts.ts Named Schema aliases for api.ts and feature code
│ │ ├── lib/moduleDelivery.ts live/partial/planned labels (imports billing/module_delivery.json)
│ │ ├── lib/types/ Domain-scoped TypeScript types split from api.ts (types/care.ts, …)
│ │ ├── components/billing/ ModuleAccessRow.tsx — Subscriptions entitlement + delivery labels
│ │ └── main.tsx
├── packages/ Plug-in modules (not imported by production frontend build)
│ └── clinical-anatomy/ @lyncareos/clinical-anatomy — 3D body/skeleton turntable (WIP)
│ src/ ClinicalAnatomyViewer, region3dMap, hostAdapter
│ public/models/ GLB assets + licenses.json
│ demo/ Standalone preview — `npm run dev` → http://localhost:5175
│ README.md Plug-in contract; see docs/plans/2026-05-31-anatomy-viewer-r3f.md
│ ├── index.html
│ ├── vite.config.ts Dev proxy `/api` → backend
│ ├── tailwind.config.js
│ └── package.json
├── docker-compose.yml postgres, pgbouncer, redis, app, scan_worker (all with profile `production`); volumes for DB, uploads, Redis
├── dev-start.ps1 Postgres + backend + Vite (Windows); dev-stop.ps1
├── start.ps1 Unified start/stop (production or -Dev)
└── docs/ Architecture, requirements, roadmap, runbook, …

There is no root npm workspace linking packages/* into frontend today — the production app builds from frontend/ only. New UI goes under pages/ and components/ following neighbours. New API code: add a routers/*.py (or extend one), wire in main.py, and extend lib/api.ts.

1.1 Pain & Stats vs clinical_anatomy (2026-05-31)

Section titled “1.1 Pain & Stats vs clinical_anatomy (2026-05-31)”
SurfaceLocationLaunch
Pain Record (2D)components/pain/PainBodyMapTab.tsx, BodyMap.tsxShipped — /pain
3D anatomypackages/clinical-anatomy/Not wired — slug clinical_anatomy is planned in module_delivery.json
  • Production does not depend on @google/model-viewer (removed from frontend/package.json).
  • Do not add 3D code under components/pain/; future plug-in uses one lazy file under src/integrations/ and toPainRegionTapHandler() from the package.
  • Preview 3D: cd packages/clinical-anatomy && npm install && npm run dev (place GLBs in public/models/ first).
  • Module spec: 26-PAIN-STATS-MODULE.md §13 · Plan: 2026-05-31-anatomy-viewer-r3f.md

ToolNotes
Python3.11+ locally; Docker production image uses 3.12
Node.js18+ (Docker frontend build uses Node 22)
DockerFor PostgreSQL in dev; for full stack with --profile production
PostgreSQL16 — via Compose locally, or your own instance with a valid DATABASE_URL

From the repo root:

Terminal window
docker compose up -d postgres

Wait until the container is healthy (docker compose ps). Default database: lyncareos, user/password: lyncare/lyncare (override via env).

Dev vs local UAT vs cloud production (isolation)

Section titled “Dev vs local UAT vs cloud production (isolation)”

Canonical names: 00-INDEX.md — Terminology.

  • Development (lyncareos_dev), local UAT (full Docker stack on your PC — profile production, DB name often lyncareos), and production (the designated operations host — live subscribers) are different hosts. The app only follows DATABASE_URL — there is no magic switch.
  • They never share data unless someone misconfigures (e.g. pasting a production DSN into backend/.env) or restores a dump across tiers. Do not point a dev laptop at the production database for casual work.
  • Local Compose UAT uses a Docker volume on your PC (lyncare_pg_data). Production on the operations host uses Docker volumes on that machine (see 03%20-%20DEPLOYMENT%20AND%20PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md) — not your dev laptop’s disk.
  • DATABASE_URL must match the host port Compose publishes when using Docker Postgres. Default is often localhost:5433 (see POSTGRES_HOST_PORT). For daily dev with dev-start.ps1, use lyncareos_dev, not the UAT DSN.
Terminal window
cd backend
python -m venv venv
.\venv\Scripts\Activate.ps1
pip install -r requirements.txt
copy .env.example .env
# Edit .env — DATABASE_URL, SECRET_KEY, ADMIN_* for seed_admin, etc.

Apply schema and seed (first time or after empty DB):

Terminal window
python -c "import asyncio; from database import init_db; asyncio.run(init_db())"
python seed_admin.py

Run the API on port 8021 (matches Vite proxy default and run_server.py):

Terminal window
python run_server.py

Alternative (manual):

Terminal window
uvicorn main:app --reload --host 127.0.0.1 --port 8021

On Windows, run_server.py sets WindowsSelectorEventLoopPolicy before uvicorn starts — required for psycopg async. Linux/Docker use the Dockerfile CMD (no special loop).

Terminal window
cd ..\frontend
npm install
npm run dev
  • .\dev-start.ps1 — native Postgres check, backend (run_server.py on 8021), Vite. Logs: backend.log, frontend.log. Stop with .\dev-stop.ps1. Does not start scan_worker — for prescription scans in dev, run Redis (default redis://localhost:6379/0) and in a second terminal: cd backend; .\venv\Scripts\python.exe -m workers.scan_worker.
  • .\start.ps1 — alternative: local UAT full stack (docker compose --profile production) or -Dev for dev servers; reads PORT / DEV_PORT from backend/.env (defaults align with .env.example).

Build and run Postgres + app (API + built SPA in one container) on the workstation — not the live production stack on the operations host:

Terminal window
docker compose --profile production up -d --build
  • App listens on 8020 on the host; API + SPA same origin.
  • Compose sets DATABASE_URL to the postgres service, ENVIRONMENT=production, UPLOADS_DIR=/app/uploads, and mounts lyncare_uploads so uploads survive restarts.
  • env_file: backend/.env loads secrets and tunables — keep SECRET_KEY, ALLOWED_ORIGINS, and LM Studio URLs in that file for container runs.

See 01-ARCHITECTURE.md for volumes, image stages, and edge/TLS notes.


Copy backend/.env.example → backend/.env. Key variables:

VariablePurpose
DATABASE_URLPostgreSQL DSN — for local Compose, use the published host port (often localhost:5433, see POSTGRES_HOST_PORT in root .env / docker-compose.yml; not the in‑container 5432 unless you intentionally run Postgres on 5432 on the host)
SECRET_KEYJWT signing; required when ENVIRONMENT=production (local UAT container or cloud)
ENVIRONMENTdevelopment (default) or production (stricter checks — applies to both local UAT Docker and the operations host; it does not by itself mean “live traffic”)
ALLOWED_ORIGINSComma-separated CORS origins; required for containerised runs with real origins (use * only for local dev)
ACCESS_TOKEN_EXPIRE_HOURS / REFRESH_TOKEN_EXPIRE_DAYSJWT lifetimes
GOOGLE_CLIENT_IDOptional Google sign-in (backend); pair with VITE_GOOGLE_CLIENT_ID on the client
DB_POOL_MIN / DB_POOL_MAXConnection pool size (defaults 2 / 10)
HOST / PORTUvicorn bind when running manually; 8020 in Docker image
DEV_PORTDocumented in .env.example for local dev (8021) — used by start.ps1 / Vite proxy; not used by the Docker CMD
LMSTUDIO_BASE_URLPrescription scan (default in config.py); server-side only. Docker on Windows reaching LM Studio on the LAN: use the host LAN IP (e.g. http://192.168.7.104:1234), not a stale address — restart scan_worker after edits.
LMSTUDIO_API_KEYBearer token from LM Studio Settings → API when server auth is on. Never commit; set in backend/.env (dev) or .env.production (VPS).
LMSTUDIO_MODELVision model id (e.g. Qwen2.5-VL)
LMSTUDIO_TIMEOUT_*Connect / read / write timeouts for scan requests

Connectivity check (from repo root): .\scripts\test-lmstudio.ps1 — probes GET {LMSTUDIO_BASE_URL}/v1/models. | UPLOADS_DIR | Prescription, shopping, and dispensing images; Docker: /app/uploads volume. New files go under /app/uploads/<tenant_id>/ (bare UUID filename in DB). Legacy flat files at /app/uploads/<filename> are still served until migrated (backend/scripts/migrate_uploads_to_tenant_dirs.py). Contact attachments: contact_attachments/<tenant_id>/. | | ICONSCOUT_CLIENT_ID / ICONSCOUT_SECRET_KEY | Optional — catalog asset scripts only, not required to run the app | | CARE_MODULE_BOARDS_ENABLED | false — when true, enables /api/care-modules/* board APIs | | CARE_MODULE_PREVIEW_USER_IDS | Default 1 — comma-separated user IDs who receive feature_flags.care_module_boards on /subscriptions/active |

Frontend optional: frontend/.env — VITE_GOOGLE_CLIENT_ID, VITE_API_URL (proxy target for /api, default http://localhost:8021), VITE_PORT.


  • Use APIRouter with a prefix such as /api/auth, /api/medicines, /api (care shifts), etc. Do not invent /api/v1/ unless the whole codebase is migrated consistently.
  • Patient-scoped routes that do not fit under a single prefix (e.g. /api/patients/{id}/medication-groups, /api/patients/{id}/dispense) use a second APIRouter without a prefix on the same module — see medication_groups and scripts routers wired in main.py (no separate medicines router after V103).
  • Inject AsyncConnection via Depends(get_db); use await db.commit() after writes.
  • Attach the right Depends(...) from auth.py: get_current_user, require_approved, require_tenant_member, require_tenant_admin, require_patient_access, require_module("…"), etc.
  • SPA catch-all: main.py serves index.html for any unmatched path with HTTP 200. When checking whether an API route exists (tests, probes), assert Content-Type: application/json — not status code alone. A missing route returns HTML, not 404.
  • Parameterized queries only — %s placeholders, never f-string SQL with user input.
  • dict_row — rows are dict-like; dict(row) is common in handlers.
  • Greenfield databases: init_db() applies backend/schema/lyncareos_v1_baseline.sql once (when public.tenants is missing), then the migration runner, then idempotent schema.sql.
  • Brownfield databases (dev, VPS): baseline is skipped; pending active migrations run, then schema.sql. Pre-v1 SQL lives in backend/migrations/archive/pre-v1/ — never add new files there.
  • Incremental changes after v1: add V002__…, V003__…, etc. under backend/migrations/ with idempotent statements (ADD COLUMN IF NOT EXISTS, etc.). migrations/runner.py applies pending active files in order and records them in schema_migrations. This is the standard path for new tables/columns used in production.
  • Document every forward migration: append a row to 11-DATABASE-SAFETY-AND-MIGRATIONS.md §1a in the same change set; add a §2x subsection there when the migration needs more than a one-line summary. Mirror new columns/tables in backend/schema.sql for greenfield installs.
  • Apply on dev: .\migrate.ps1 -Target Dev from repo root (sets DATABASE_URL → lyncareos_dev). Do not run bare python -m migrations.runner without -Target — default config may point at wrong database. Full rules: 11-DATABASE-SAFETY-AND-MIGRATIONS.md.
  • Avoid editing only CREATE TABLE in schema.sql for databases that already exist — existing DBs need migrations (or manual ALTER) to pick up changes.
  • After adding a migration, run .\migration-audit.ps1 -Target Dev and ensure greenfield rehearsal still passes if baseline DDL changed (24-V1-DATABASE-BASELINE-AND-CUTOVER.md).

Use HTTPException(status_code, detail) for client-facing failures. Let unexpected errors surface as 500 only when truly unhandled (FastAPI default).

6.5 Patient scripts as the medication entity (V103, REQ-MED-14)

Section titled “6.5 Patient scripts as the medication entity (V103, REQ-MED-14)”

Migration V103__merge_medicines_into_scripts.sql removed the tenant medicines table and routers/medicines.py. Each medication is a patient_scripts row (medicine_name_raw, color_hex, as_needed, stock/fills). Schedule items and dispensings reference script_id only.

LayerFileResponsibility
Repositoryrepositories/patient_scripts.pyScript row helpers, stock derivation, enrich (partial — more SQL in service during B3)
Serviceservices/patient_scripts_service.pyCRUD, fills, scan queue, alerts (stock_count_needed when dose log > 0 and on-hand ≤ 0), dismiss snooze, medicine-summary (total_stock_on_hand for all statuses)
Routerrouters/scripts.pyThin HTTP — GET/POST/PATCH /api/patients/{id}/scripts/*
Schedule / dispenserouters/medication_groups.py → services/medication_groups_service.pyGroups, dispense-view, batch dispense (script_id on items)

When adding a medicine picker or schedule row: use api.scripts.list(patientId) (frontend) / patient-scoped script list — never a tenant-wide catalogue. Legacy /admin/medicines redirects to /scripts in the SPA.

D23 (per-patient catalogue migration) is resolved by V103 — see 32-KNOWN-DEBTS-REGISTER.md.

6.6 Active-patient isolation for aggregates, export, and audit (REQ-MED-15)

Section titled “6.6 Active-patient isolation for aggregates, export, and audit (REQ-MED-15)”

REQ-MED-14 scoped pickers; REQ-MED-15 extends the rule to everything that aggregates, charts, counts, exports, or audits clinical data. The “currently selected person” lives only in frontend PatientContext, so the frontend must pass patient_id and the backend must validate and apply it.

  • Backend: dispensing-analytics endpoints, /api/alerts + /api/alerts/open-count, /api/billing/export/download, and /api/audit take an optional patient_id. When present, call ensure_patient_access(ctx, patient_id, db) then filter on patient_id (analytics share the _scope_dispensings helper in routers/analytics.py). When omitted, the legacy account/member scope is retained for admin tooling and the cancellation-portability export.
  • Frontend: any carer-facing page that charts/aggregates/exports must read usePatient().activePatient, pass activePatient.id to the API, include activePatient?.id in the useEffect dependencies (so it refetches on person-switch), and render nothing until a person is selected. Examples: Dashboard.tsx, Analytics.tsx, AlertInbox.tsx, AlertContext.tsx, admin/ExportData.tsx, History.tsx (audit tab).
  • Never add a new chart/aggregate endpoint that scopes only by tenant_id or by all-allocated-patients when a single person is selectable in the UI.

Regression: tests/test_patient_analytics_isolation.py. Plan: docs/plans/2026-05-29-active-patient-isolation-sweep.md.

6.7 First-dose adverse reaction follow-through (REQ-MED-16)

Section titled “6.7 First-dose adverse reaction follow-through (REQ-MED-16)”

When extending dispensing or alert flows:

  1. Detection — first_dose_reaction_service.maybe_prompt_after_dispense(); keyed by patient + normalized medicine name (not script_id).
  2. Prompt — FirstDoseReactionModal on Log Dose, Medication Schedule, and Alert inbox (Answer action).
  3. Yes path — respond_to_check(observed=true) → resolves first_dose_reaction, calls alert_adverse_reaction_reported(), returns check row.
  4. Detail modal — AdverseReactionDetailModal loads contacts via api.keyContacts.listContacts(patientId) (not .list()). Clinical roles from lib/contactRoles.ts: GP, Specialist, Palliative Specialist, Nurse, Pharmacist — Call (tel:) / Email (mailto:) when phone or email present.
  5. History — History.tsx merges api.firstDoseReactions.listLog() with dispensings; reaction rows use coral styling; More menu label Dispensing and Adverse Reactions History Log.
  6. Tests — backend/tests/test_first_dose_reactions.py (includes urgent alert on Yes); test_key_contacts.py::test_palliative_specialist_role_tag (V005).

Do not block generic resolve on adverse_reaction_reported — only first_dose_reaction requires structured response.

Key Contacts roles: import labels from lib/contactRoles.ts; do not duplicate ROLE_LABELS in pages.


The app uses fetch through src/lib/api.ts (request() with token refresh on 401). _tryRefresh() on bootstrap: POST /api/auth/refresh returns 204 when no refresh cookie is present (logged-out shell — not an error); 200 with tokens when the cookie is valid. Pages typically use useEffect + useState (or context) — there is no TanStack Query in package.json. New code may continue this pattern or introduce a data library only with an explicit team decision and dependency addition.

Rule: Only 401 should clear tokens and force login; 403 means “forbidden”, not “session dead” (see api.ts).

Dev auth pitfalls (2026-06-03): Access tokens live only in memory (tokenStore in api.ts). Use one dev URL consistently (http://localhost:5173, not 127.0.0.1) so the HttpOnly lyncare_refresh cookie round-trips through the Vite proxy (cookieDomainRewrite). After HMR reloads api.ts, AuthContext re-runs refresh when user is set but the in-memory token was cleared — otherwise Layout fires /patients etc. and the console shows 401 until you log in again. Hard refresh or re-login also fixes a stale session. ESLint enforces no bare fetch() in pages/components. Two approved escape hatches are exported from lib/api.ts:

HelperWhen to use
uploadForm<T>(path, fields)Multipart file uploads - handles FormData, token refresh, and 401 session clear identically to JSON request()
requestRaw(url, options?)Pre-auth flows only (e.g. Stripe complete-signup) where no Bearer token exists and the caller must inspect raw status codes (e.g. 202 Retry-After). On failure, parse structured payment errors via lib/paymentOutcome.ts — do not surface raw detail strings to users.

Never introduce a bare fetch() call in a page or component - extend one of the helpers above or open a discussion first.

request(path) path rule: pass paths without the /api prefix — request() prepends /api automatically (fetch(\/api${path}`)). Correct: request(‘/admin/alert-settings’)→/api/admin/alert-settings. Wrong: request(‘/api/admin/alert-settings’)→/api/api/…, which hits the SPA fallback and returns HTML with HTTP 200 (JSON parse then fails silently or shows a generic load error). When adding new api.* helpers, match existing call sites (/patients/…, /alerts/…, not /api/patients/…`).

7.1a Subscriptions page — entitlement vs delivery (2026-06-26)

Section titled “7.1a Subscriptions page — entitlement vs delivery (2026-06-26)”

Route: /subscriptions (pages/admin/Subscriptions.tsx) — tenant members can view; admins upgrade/cancel.

ConceptSourceUI
Entitlementsubscriptions rows + tiers.jsonPlan includes the slug
Deliverybackend/billing/module_delivery.jsonWhether the product surface is live today

Labels (components/billing/ModuleAccessRow.tsx via lib/moduleDelivery.ts):

  • Active — live module, entitled
  • Included — rolling out — partial (e.g. custom_observations, family_help)
  • Coming soon — planned tier placeholders (e.g. clinical_anatomy — not in tiers.json until productised)

Page layout (top to bottom on Subscriptions.tsx, 2026-06-26):

OrderSectionContents
1Your planCurrentPlanCard — tier name, price, limits, renewal
2Module accessEntitled modules (partitionSubscriptionsForDisplay → moduleAccess)
3Upgrade planPlanUpgradePanel — tier dropdown (admins only, when upgrades exist)
4Unlock with an upgradeLive/partial slugs not on the current plan (hidden on Complete)
5Care ProfilesAdd a Care Profile purchase grid (ConditionPackCard) when condition_templates is enabled
6Coming soonplanned delivery slugs the tenant does not yet own
—Cancel subscriptionAdmin link at bottom

Horizontal dividers separate major sections. If my-tier fails to load, the page falls back to a flat Module access grid with no split (see Subscriptions.tsx subscriptionGroups).

Excluded from module grids: condition_templates is omitted from Module access, Unlock with an upgrade, and Coming soon (SUBSCRIPTIONS_MODULE_ACCESS_EXCLUDE in lib/moduleDelivery.ts). Care Profiles are the dedicated commerce surface; per-patient apply is via dev QA panel or API until a new family workflow ships (archetype / Our care pattern UI withdrawn 2026-06-26).

Card order within each grid:

SectionSort rule
Module accessOrder of slugs in current_tier.modules (sortSubscriptionsByCurrentPlan) — matches backend/billing/tiers.json for that plan. Add-ons not on the plan sort after plan modules, alphabetically.
Coming soon / Unlock with an upgradeCheapest tier that includes the slug, then alphabetical within the band (sortSubscriptionsByTierHierarchy)

Do not sort Module access by tier band on Complete (or any plan) — that scatters cards into Essential → Family → Complete groupings even when the subscriber owns everything.

Retired route: /care-archetypes redirects to /subscriptions (exploratory browse page removed 2026-06-26).

Tests: frontend/src/test/lib/moduleTierUpgrade.test.ts, moduleDelivery.test.ts

Do not use the word Subscribed for partial modules. ModuleGate still enforces entitlement from /api/subscriptions/active; delivery labels are honesty for marketing reconciliation only.

When shipping a module to live, edit module_delivery.json (live array + primary_routes), mirror in moduleDelivery.ts (imports the JSON), run python scripts/generate_delivery_register.py, and add MODULE_META in routers/subscriptions.py if missing.

API contract: GET /api/modules/available → delivery[slug].status is live | partial | planned.

7.1b Post-checkout pages (signup billing UX)

Section titled “7.1b Post-checkout pages (signup billing UX)”
RouteComponentNotes
/billing/successBillingSuccess.tsxPOSTs session_id to /api/stripe/complete-signup; retries on 202; uses parsePaymentOutcome() / fetchCheckoutOutcome() on errors
/billing/cancelBillingCancel.tsxConfirms no charge via GET /api/stripe/checkout-outcome when session_id is present
—lib/paymentOutcome.tsShared outcome types, API fetch, pricing retry URL, support mailto builder

User-visible copy must come from user_message on the outcome object, not HTTP status text. Branch CTAs on charged: Try again → marketing pricing when false; Sign in + support when true.

7.1c Prescription script alert banners (2026-06-03)

Section titled “7.1c Prescription script alert banners (2026-06-03)”

Surfaces: Dashboard.tsx (Home), Scripts.tsx (Medications) for computed banners. stock_count_needed also raises a durable prescription_stock_count row in care_alerts (bell inbox, admin-only list/count) via alert_script_sync.py — deep_link /scripts/{id}?setup=stock&patientId={id}.

PieceLocation
Banner UIcomponents/scripts/ScriptAlertBanner.tsx — tap row → script detail; Ignore → api.scripts.dismissAlert
Copy + routeslib/scriptAlerts.ts
Refetch after fill/editlib/scriptsEvents.ts — call notifyScriptsChanged() from fill modal, edit save, etc.
Home stale-data guardDashboard.tsx — abort prior scripts.alerts fetch on scriptsDataGen bump; pageshow when bfcache restores

When adding a new alert type, extend: backend get_script_alerts + SCRIPT_ALERT_TYPES + migration CHECK + ScriptAlert TypeScript union + scriptAlertSubtitle().

Care alerts bell (stock mismatch): alert_script_sync.py upserts or auto-resolves prescription_stock_count when stock_count_needed_for_script is false (e.g. after pills_available PATCH with on-hand > 0). Sync is awaited on the request via alert_script_hooks.await_sync_prescription_stock_count_alert — do not rely on background-only sync before the client refetches. AlertContext + AlertInbox refresh on scriptsEvents / dispensingsEvents (badge even when inbox closed). repositories/alerts.py hides this type from non-admins. Tap → ?setup=stock → emphasizeStockField. Mark done = handled without updating stock; closing edit without save must not clear the row.

Carer-facing stock labels (lib/scriptStock.ts — use these constants, not internal API names):

LabelAPI fieldMeaning for carers
Doses availablestock_on_hand / total_stock_on_handWhat the family has on hand now (card + detail).
How many doses do you have available?pills_available PATCHEdit modal label (DOSES_ON_HAND_PROMPT) — ask for a physical count; do not show lifetime doses logged.
Last countedlast_physical_count + last_physical_count_atLast physical stock-take baseline.

total_dispensed remains on the API for alert logic only — not shown to carers.

7.1c Stream 2–3 modules (partial delivery)

Section titled “7.1c Stream 2–3 modules (partial delivery)”

Gated with ModuleGate in App.tsx. Discoverability is mostly via More (More.tsx) except where noted.

RouteModule slugComponentNotes
/observationscustom_observationsObservations.tsx → ObservationDashboardRequires usePatient().activePatient; API under observationsApi in lib/api.ts
/help-requestsfamily_helpHelpRequests.tsxAlso listed in More when module enabled
/planning-aheadcare_pathways (planned D31)—Not shipped. Spec 33; mockup docs/01 - BUSINESS REQUIRMENTS/assets/planning-ahead-mockup.html

Care archetypes (no standalone route): seven coordination patterns via GET /api/condition-packs/archetypes; no family UI as of 2026-06-26 (CarePatternPanel + ArchetypeOnboarding removed; Add Person is demographics only). Purchase/unlock via Care Profiles on /subscriptions. Legacy /care-archetypes → redirect /subscriptions.

Update backend/billing/module_delivery.json (partial / planned copy + primary_routes) and run python scripts/generate_delivery_register.py when changing delivery labels. Add care_pathways to planned at D31 kickoff.

RouteComponentNotes
/admin/alertsAlertSettings.tsxAdmin-only (AdminGate); loads api.alerts.getSettings() → GET /api/admin/alert-settings

Channel toggles include family_help (V093). Non-admins are redirected before the page mounts; a 403 from the API means the session user is not a tenant admin.

After deploy, no user action is required — mid-session browsers auto-recover from stale lazy chunks via lib/lazyWithReload.ts, and the service worker reinstalls on every deploy because npm run build stamps CACHE_NAME with the current main-bundle hash (see frontend/scripts/inject-sw-version.mjs). The SW_UPDATED postMessage triggers the reload chain in index.html. If you see a stale shell anyway, check that the /sw.js response from app.lyncareos.com carries Cache-Control: no-cache and cf-cache-status: DYNAMIC; if either is wrong, the Cloudflare Cache Rule lyncareos-sw-bypass has regressed. Full strategy: docs/plans/2026-05-29-spa-deploy-resilience.md.

Agent / release owner checklist: Treat cache verification as part of “deploy complete”, not optional. After deploy.ps1 succeeds, confirm (1) a new CACHE_NAME in live sw.js, (2) index.html no-store headers, (3) API smoke 200 — see 20-PRODUCTION-DEPLOYMENT-GUIDE.md §6. A hung local push-to-production.ps1 (e.g. Docker UAT backup) does not update production; never kill VPS processes to unstick a workstation script.

PatientProvider stores lyncareos_active_patient in localStorage. On each patient-list fetch it validates the stored id against the live tenant list before exposing activePatientId — stale ids from dev or another tenant are replaced with the first accessible patient (or cleared when the list is empty). Do not read localStorage for patient id in components; use usePatient().

Post-login and long-absence return always land on Home (Dashboard), not Calendar.

MechanismFileBehaviour
Login / register / tenant switchlib/loginTenantFlow.ts, lib/awayCalendar.ts → resolveHomePathAfterLogin()Always returns / (after touchAwayBaseline())
Tab return / shell ready after ≥10 min awaycomponents/Layout.tsx + lib/awayCalendar.tsnavigate('/', { replace: true }) when wasAwayLongEnoughForHome(); does not override an early nav click during module load (shouldApplyAwayHomeRedirect)
Away timestampmarkAppBackgrounded() on visibilitychange hidden, pagehide, logout (AuthContext)Stored in localStorage key lyncareos_last_away_at

Legacy name awayCalendar.ts is retained; calendar-specific landing was removed 2026-05-30.

7.1h Care Module plugins (cancer / breathing) — feature-flagged

Section titled “7.1h Care Module plugins (cancer / breathing) — feature-flagged”

Spec: 29 · 30 · 31

RouteSlug required on patientNotes
/care/cancer-at-homecancer_at_homeCancer Board V2 — CancerTodayContextPanel (Actions for today · Your treatment — cc-card + existing pickers; no Comfort mode toggle) → status summary → Today’s care plan (day/mode-driven) → date strip → Daily status (inline 8-spoke radar; Because + Next fork) → Other cancer tasks today → Watch closely → Activated across LynCareOS → Clinic and handover
/calendarcare board slug on patientCalendarFocusDayPanel — action pills for the focus date from the module manifest’s calendar_actions; tapping one writes date-scoped care_tasks. CalendarDayCell shows each applied action’s manifest icon in the month grid (via GET …/calendar-actions/range). Replaced the read-only CareActionsForTodayBlock (deleted 2026-07-31). See 15-CARE-CALENDAR-COMPOSITION.md
/care/cancer-at-home/visit-prepcancer_at_homeWeek at home, in brief — abbreviated bullet lines (story.lines); questions queue with Discussed checkboxes (visit_prep_discussed); Larger text toggle (CANC-H02 lite)
/care/breathingbreathing_difficultiesPhase A shell + daily breathing bundle

Enable locally (user id 1 only by default):

backend/.env
CARE_MODULE_BOARDS_ENABLED=true
CARE_MODULE_PREVIEW_USER_IDS=1
# frontend/.env
VITE_CARE_MODULE_BOARDS=true

Restart backend and npm run dev. Apply the matching Care Profile (pack slug) to the active patient — not the care situation alone. See §7.1i.

Platform super-admin (is_super_admin): must still receive feature_flags.care_module_boards from GET /api/subscriptions/active (fixed in ModuleContext 2026-06-04). Previously boards were forced off for super-admin accounts — sidebar Cancer board and Home strips never appeared for Peter even with flags on.

Production launch (base app only): leave both board flags false / unset.

Do not add care boards to tiers.json or module_delivery.json live until product sign-off.

Cancer hub API (api.careModules in frontend/src/lib/api.ts):

MethodPathPurpose
GET/api/patients/{id}/care-modules/board?slug=Manifest, zone, hub — tiles[].visual, primary_cta_visual, enriched catalog.treatment_modes / today_day_types (icons)
POST…/events?slug=Capture step
POST…/sessions/complete?slug=Complete session
PATCH…/settings?slug=Hub settings (cancer_at_home only in MVP)
GET…/visit-prep?slug=Visit prep aggregate — { story, summary, settings }; story.lead / story.sublead + story.lines[] from build_visit_prep_story() (paragraphs mirrors lines)
GET…/dashboard-chips?slug=Home Cancer today chips — e.g. Infusion visit packing: 2 of 6 ready (not US “chair day” jargon)
GET…/dashboard-panel?slug=Home Care board panel — chips, actions_for_today[], treatment_modes[] for CareBoardDashboardPanel
GET…/comfort-checkin/dates?slug=&days=ISO dates with at least one comfort check-in (default 90 days)
GET…/comfort-checkin/spoke-averages?slug=Rolling mean per spoke (1–4); days = longest fallback window with data (30 → 20 → 10 → 5 → 2)
GET…/comfort-checkin/week-series?slug=&anchor=Mon–Sun merged spoke levels for the calendar week containing anchor (ISO date); powers hub status narrative
GET…/comfort-checkin?slug=&date=&capture_instance_id=Board default: merged latest value per spoke across all instances on care_date; completed if any instance on that date completed. Optional capture_instance_id scopes to one instance (tools). Response capture_instance_id = write target (instance on the most recent comfort event that day). Hub loads without the query param.

Capture pop-ups (all FP modules): step wizards use CaptureSession → CareCaptureOverlay (frontend/src/components/care-capture/). Portals to document.body, z-[1100], scroll lock, opaque bg-canvas (not bg-background). Responsive: phone = full screen; tablet = centred card ~85% width + dim backdrop; desktop (lg+) = ~50% of main column width (min(32rem, calc((min(100vw-15rem,64rem)-4rem)/2))), centred over the board (lg:pl-60 for sidebar). Pass key={sessionId} when switching bundles. Visit prep / log dose use routes, not the overlay.

Capture layouts (manifest-driven):

layoutUXExample session
wizard (default)One question per screen; review step at endfever_pathway, chair_day_ack, tablet_safety
stackedAll steps on one screen (overlay — legacy)cancer_symptom_bundle, comfort_round — prefer inline radar on hub

Daily status (inline radar, preserved in V2): CancerComfortDateStrip on CareBoardPage — pick any day; recorded days show a dot. InlineComfortCheckIn (id="cancer-daily-status", aria-label="Daily status") — CancerComfortRadar + CancerComfortRadarChart (ECharts 8-spoke radar: Energy · Pain · Eating · Breath · Mood · Sleep · Fever · Treatment). Tap a dot on any spoke to score 1–4 (centre → edge); per-spoke axis label colours; health gradient web red (centre) → amber → indigo → green (edge); comfort score 8–32 (sum of eight spoke points). Solid polygon = selected day; dashed = Past N-day average from comfortSpokeAverages() (not static targets). Maps manifest segmented_bar steps via cancerRadarConfig.ts; postStep (POST …/events) on each tap (immediate DB write). When all eight spokes are saved in UI, completeSession runs automatically (no Save daily status button). Retrospective days: changing one or two spokes still shows the full spider — GET merges latest per spoke across instances; unchanged spokes keep prior event values. After complete: tap any dot to change a score (chart stays editable). Writes send care_date + capture_instance_id from the snapshot write target. Sessions: cancer_symptom_bundle (default) / comfort_round (Comfort mode). Symptom tile hidden when inline check-in shown. Scroll: board entry and route changes scroll Layout <main> via scrollAppMainToTop / scrollAppMainToElement (not window / indiscriminate scrollIntoView).

Radar files (do not modify in V2 work): cancer/cancerRadarConfig.ts, cancer/radarTapGeometry.ts, lib/radarHealth.ts, components/CancerComfortDateStrip.tsx, components/CancerComfortRadar.tsx, components/CancerComfortRadarChart.tsx. Removed from hub: spoke pills, ComfortSpiderDiagram, side-panel level picker, hub-mounted CareFlowRail.

Cancer Board V2 model + sections (2026-06-10): Pure builders in cancer/cancerBoardV2Model.ts derive V2 UI from existing hub state (no new APIs in Phase 1). Presentational sections in cancer/components/:

SectionComponentBuilder / behaviour
Context (top)CancerTodayContextPanel.tsxcc-card wrapping CancerDayPicker + CancerModeToggle (treatment modes only); patch today_day_type / treatment_modes + scroll #cancer-today-plan
Status summaryCancerStatusSummary.tsxbuildWeeklyStatusCopy() in comfortWeekInsightNarrative.ts — Mon–Sun spoke insights from comfortCheckinWeekSeries(anchor = careDate) (1–7 days; per-spoke trends, deterioration questions, when-to-call hints); fallback buildStatusReason(hub, zoneLabel) only when the week has no daily status days; hub red/amber alerts prefix narrative

Editing status narrative copy: All carer-facing insight strings live in comfortWeekInsightNarrative.ts (LEVEL_PHRASE, SPOKE_GUIDE, template rotation per spoke). Deterministic — no LLM. Priority: urgent spokes (e.g. severe breath, fever/chills) first; up to four non-duplicate sentences. Unit tests: frontend/src/test/lib/comfortWeekInsightNarrative.test.ts. Spoke concern colours on the radar use the same metadata in cancerRadarConfig.ts (including inverted fever_worry scale). | Today’s care plan | CancerTodayPlan.tsx | buildTodayPlan(hub), buildPlanSubtitle(hub) — open by default; day/mode steps only (no daily status or breakthrough review cards — see sections below) | | Daily status | InlineComfortCheckIn.tsx | existing radar wrapper (unchanged geometry) | | Other cancer tasks today | CollapsibleSection #cancer-other-tasks | hub tiles (renamed from “More for today”) | | Watch closely | CancerWatchClosely.tsx | buildWatchItems(hub) — site-aware (brain → neuro; lung/oxygen → equipment) | | Activated across LynCareOS | CancerActivatedAcrossLynCareOS.tsx | buildActivationItems(hub) | | Clinic and handover | CancerClinicHandover.tsx | buildClinicLines(hub, zoneLabel, zone) |

Care Flow Loop (after daily status save): Hub guides the carer without overlay layers.

PieceFileBehaviour
Flow stepscancer/cancerCareFlow.tsbuildCancerCareFlow({ checkInDue, checkInComplete, primaryCta, dayLabel }) → { steps, nextFork }; resolvePainLogFork(painLabel, breakthroughLogRoute) after high pain spoke
Step railcomponents/CareFlowRail.tsxNot mounted on hub (component retained for future generic extraction)
Becausecomponents/BecauseLine.tsxPrefix “What this tells us:”; copy from buildComfortBecauseLine() (Energy + Pain labels)
Next forkcomponents/NextStepFork.tsxDo now / Later / Skip after completeSession
WiringCareBoardPage.tsxhandlePlanAction / handleWatchAction for V2 sections; handleForkAction: session → openSession, route → navigate, expand → scroll #cancer-daily-status or open #cancer-other-tasks; refreshComfortSnapshot on date change (merged GET, no capture_instance_id param); refetch after each spoke + after auto-complete; checkinVersion remounts radar when snapshot updates

Frontend tests: frontend/src/test/lib/cancerBoardV2Model.test.ts — run npm test -- cancerBoardV2Model.

Home dashboard panel: CareBoardDashboardPanel on / when preview flags + matching care_profile_slug. Below 540px: Care board title then icon grid; 540px+: title left, icons clustered right.

Calendar focus day (2026-07-31): CalendarFocusDayPanel on /calendar — sits under the month grid and follows the focus date, not today. Tapping a date focuses it; holding for 450ms opens the scheduling sheet as before. CalendarActionPills renders the patient’s care-module calendar_actions; tapping a pill applies its task bundle to the focus date via POST …/care-modules/calendar-actions and tapping again undoes it. Tasks are date-scoped (shift_id null when nobody is rostered) and readable through GET /patients/{id}/care-tasks?start=&end=. Action pills follow the care-module preview allow-list; the tasks they create do not. Replaced the read-only CareActionsForTodayBlock. File map: 15-CARE-CALENDAR-COMPOSITION.md.

Calendar module task responses (2026-07-31): Module tasks are not checkbox-only. Each manifest task carries prompt + response_kind; the UI renders ModuleTaskResponseButtons (Yes/No, Taken/Not taken/N/A, Arranged/Not yet arranged, etc.). Answers persist with PATCH /api/care-tasks/{id} { "response_code": "<code>" } — requires V027 on dev (.\migrate.ps1 -Target Dev). Option sets: backend/care_modules/calendar_task_responses.py and frontend/src/lib/calendarModuleTaskResponses.ts (keep in sync). After changing Pydantic fields, run OpenAPI export + npm run generate:types. Rows created before V027 lack response_kind until the action is re-applied on that date.

Calendar month grid — care-module icons (2026-07-31): When a pill is applied, CalendarDayCell renders the action’s icon key (same mapping as the home care-board strip: careProfileIcon / CARE_PROFILE_ICON_MAP in care-modules/shared/careProfileVisual.ts). useCalendarModuleActionsRange loads GET /api/patients/{id}/care-modules/calendar-actions/range?slug=&start=&end= once per displayed month; careModuleDayIconKeys() in lib/calendarViewHelpers.ts picks applied actions for each ISO date (fallback: careModuleSlugIconKey() when module tasks exist but the range call has not run). Up to CAL_DAY_MODULE_ICON_LIMIT (5 in lib/calendarPageConstants.ts — matches the five calendar_actions on cancer_at_home; raise when a module ships more day types). Below Tailwind lg (CALENDAR_DAY_CELL_COMPACT_MODULE_ICONS_QUERY, max-width 1023px — phones and tablets), careModuleDayIconsForViewport() shows one module icon (careModuleSlugIconKey) whenever any action is applied; lg+ (desktop) shows one icon per applied action. General free-text / shift tasks still use the ClipboardList marker via dayActivityIndicators() (now includes date-scoped tasks from listForRange, not only shift-attached rows). Pill apply/undo refreshes the range through CARE_CALENDAR_ACTIONS_CHANGED and the focus-day onTasksChanged hook.

QA (Cancer Board V2): Load /care/cancer-at-home → page opens at top (title), not mid-board → confirm Actions for today + Your treatment at top (cc-card pickers) → tap a day type → Today’s care plan updates and page scrolls to it → toggle a treatment mode → plan gains/loses mode steps → pick today on date strip → tap all eight spokes → What this tells us / Next fork appear after auto-complete → tap a plan step or watch-row action → Other cancer tasks today expands when fork/plan directs there. Pick a past day with data → change one spoke → confirm all eight spokes still render. Tap a spoke again — score updates without a separate “another check-in” button.

Mockup: support-flow-mockup.html. Extraction (later): generic rail/fork moves to care-modules/shared/ after Cancer sign-off.

Widgets: traffic_light_3, emoji_face_5, segmented_bar (overlay / tile sessions). Configure in manifests/{slug}.json → capture_sessions.

Care board routes: CareModuleRoutes.tsx wraps each lazy page in Suspense (PageLoadingSpinner) + ErrorBoundary (labelled fallback, e.g. “Cancer board unavailable”). Layout also wraps <Outlet> in Suspense — belt-and-braces for lazy chunks.

Dev QA: After editing CareBoardPage.tsx, if Vite logs Could not Fast Refresh (export removed), hard-refresh (Ctrl+Shift+R) or restart npm run dev before retesting /care/cancer-at-home.

Pattern for new plugins: add care-modules/{slug}/CareBoardPage.tsx, entry in registry.ts, manifest JSON under backend/care_modules/manifests/, route in CareModuleRoutes.tsx — all behind the same flags. Optional hub service + care_module_patient_settings row per slug. Hub pages should default missing hub.* arrays (tiles, modes, alerts) to [] and show useCareBoard().error when the board API fails. New capture bundles: add capture_sessions in manifest JSON only (optional "layout": "stacked", per-step "widget": "segmented_bar"); UI reuses CaptureSession. Cancer check-in: _primary_cta() default → cancer_symptom_bundle; gentle/palliative → comfort_round; visit prep counts both session ids.

7.1i Care situation vs Care Profile (common QA confusion)

Section titled “7.1i Care situation vs Care Profile (common QA confusion)”
LayerUI labelExamplePersisted on patientLoads labels / boards
Care situationArchetype card (“✓ Selected”)The Breath-by-Breathpatients.archetype_idNo — story classifier only
Care ProfilePack apply / dropdownBreathing difficulties, Cancer at Homepatients.care_profile_slug, care_start_applied_atYes — apply_care_start_pack()

Where to apply a profile

FlowPath
New personPeople in care → Add Person → PatientCareStartWizard (demographics only)
Existing personNo family UI — use dev QA panel or PATCH …/care-pattern / POST …/care-start until workflow redesign
Dev one-tap (user id 1 only)Person detail → Care profile QA (dev) panel → Breathing / Cancer buttons

Day-one bootstrap (care_start_bootstrap.py): On new person create → four medication time slots (08:00, 12:00, 20:00, 00:00). On Care Profile apply → same slots (idempotent) + sample Paracetamol (pain) on paid packs (price_aud > 0, not free starter) + profile shopping lists with suggested items (SHOPPING_LISTS_BY_PACK_SLUG in seed_catalog.py; visible on Complete /shopping). Surfaces: Medication schedule, Log a dose, Shopping. Not the Care Module board tiles in FP specs (those are Phase B+).

Setting patients.archetype_id (API or future UI) does not load labels or boards until a Care Profile is applied. Boards need care_profile_slug ∈ { cancer_at_home, breathing_difficulties } plus preview flags (§7.1h).

7.1j Peter tenant — Care Profile + board QA (dev)

Section titled “7.1j Peter tenant — Care Profile + board QA (dev)”

For manual testing on tenant slug peter (login as Peter, choose peter — not test-card-*):

Terminal window
.\scripts\seed-dev-peter-care-qa.ps1

Script: backend/scripts/seed_dev_peter_care_qa.py (idempotent). It:

  • Activates condition_templates and custom_observations on peter (Subscriptions shows all Care Profile cards)
  • Grants admin_grant access to all active packs
  • Ensures QA — Breathing board and QA — Cancer board people with profiles pre-applied

After seed: hard refresh or re-login → Subscriptions → switch active person to a QA row → Home → Open care board chip (user id 1, flags in §7.1h). Sidebar also shows Cancer board / Breathing board when the active person has the matching care_profile_slug.

If schedule / shopping are empty but reason codes exist: profile was applied before day-one bootstrap shipped. Re-apply the pack (dev QA panel or API), re-run .\scripts\seed-dev-peter-care-qa.ps1, or:

Terminal window
cd backend
python -m scripts.backfill_care_bootstrap

Where to see each layer (QA Cancer):

LayerRoute / UI
Cancer hub (Board V2)/care/cancer-at-home — context panel + status summary + Today’s care plan + date strip + Daily status (8-spoke radar) + Other cancer tasks + Watch closely + Activated across LynCareOS + Clinic and handover
Visit prep/care/cancer-at-home/visit-prep — abbreviated week summary; show phone at desk
Home discoveryCareBoardDashboardPanel on Dashboard + sidebar Cancer board
Medication time slots + sample medScheduled Doses (/medication-schedule) — Care Start bootstrap
Profile shopping listsShopping (/shopping) — Complete tier / shopping module
PRN reason codesLog a dose, More → Reason codes

Cancer MVP (Part 5) ships: visual hub, infusion visit packing, fever pathway, visit prep + discussed toggles, dashboard strip, calendar oncology appointment_type (V016) with hub day sync, breakthrough /log deep link + tile sparkline, primary-site tips, comfort override banner. Still not shipped: full B–H workflows, deep site modules (CANC-T02–T12), radiation/immuno irAE tiles — see FP-cancer-at-home.

Cancer hub layout (Board V2): Header — patient name + cc-btn-soft Home; title row + CancerPrimarySitePicker (right). Body — CancerTodayContextPanel (cc-card; CancerDayPicker + CancerModeToggle — sets today_day_type / treatment_modes; scrolls to plan; day/treatment pills colour-coded; plan step left border matches linked pill) → CancerStatusSummary (weekly spoke insight for Mon–Sun week of selected careDate) → CancerTodayPlan (open; buildTodayPlan / buildPlanSubtitle — day-type + mode steps only) → optional comfort override + site tip → CancerComfortDateStrip → InlineComfortCheckIn / Daily status (8-spoke ECharts radar; per-tap save + auto completeSession; past N-day average overlay) → BecauseLine (What this tells us:) + NextStepFork → CollapsibleSection: Other cancer tasks today (#cancer-other-tasks) → CancerWatchClosely (includes breakthrough pain row) → CancerActivatedAcrossLynCareOS → CancerClinicHandover.

Comfort mode (gentle_mode): Backend setting still affects tile visibility, comfort override banner, and comfort-first plan when active — but no UI toggle on the hub context panel (removed 2026-06-10). Distinct from the Comfort / palliative focus treatment-mode chip. Backend copy: GENTLE_MODE_COPY in cancer_defaults.py.

Hub tile telemetry: cancer_board_visual.enrich_tiles() — infusion/line progress; symptom due/last; breakthrough 24h/7d + last_dose + 7d sparkline; breakthrough tile routes via hub.breakthrough_log_route (/log?reason_type_id=…&source=cancer); secondary Week story → visit prep.

Calendar ↔ hub (CANC-B01 lite): AddShiftForm optional oncology type chips → POST /patients/{id}/appointments with appointment_type. Hub reads today’s typed appointments → today.calendar_suggested_day_type, today.effective_day_type (manual Actions for today selection wins when today_day_type is not none); calendar suggestion also appears as a step in CancerTodayPlan.

Log a dose — Cancer context: LogDose.tsx reads ?reason_type_id= or ?reason=breakthrough&source=cancer and pre-selects reason chip; shows banner when source=cancer.

Analytics (Cancer): GET /api/analytics/by-reason?reason_pattern=breakthrough&patient_id=; GET /api/analytics/care-module-events?slug=cancer_at_home&patient_id= — hub also embeds metrics.breakthrough_trend_7d / checkin_trend_7d.

Tests: backend/tests/test_care_modules_cancer.py (7 cases incl. breakthrough route, calendar sync); backend/tests/test_visit_prep_narrative.py; backend/tests/test_cancer_board_effects.py.

PRN reason types are not a shared tenant catalogue. Each row in reason_types has patient_id (required after V014).

SurfaceBehaviour
APIGET /api/reason-types?patient_id={id} — required; ensure_patient_access
Care Start applyapply_care_start_pack() inserts missing labels for that patient only
Tier limitmax_reason_types counts per person in care, not per household
Log a dose / Historyapi.reasonTypes.list(activePatient.id); clears selected reason on patient switch
More → Reason codesAdmin UI scoped to active patient from header switcher

Medical descriptions (V013): pack_reason_types.description and reason_types.description for cancer_at_home and breathing_difficulties — source REASON_MEDICAL_DESCRIPTION_BY_PACK in seed_catalog.py. Shown on Reason codes admin, Log a dose (selected chip), and pack Preview modal.

Do not call GET /api/reason-types without patient_id — returns 422.

7.1g Auth branding and in-app brand assets

Section titled “7.1g Auth branding and in-app brand assets”

Unauthenticated routes and the desktop sidebar share the Calm Care login mockup pattern — illustrated backdrop, Heartmark 2, tri-colour wordmark — not the legacy glossy in-app PNG icon.

Asset / componentPathUse
Heartmark 2frontend/public/brand/lyncareos-heart-mark.pngLogin, register, desktop sidebar, mobile top bar, Getting Started hero back-layer
Auth backdrop (portrait + wide)auth-welcome-bg-portrait.png, auth-welcome-bg.pngAuthWelcomeBackdrop — portrait on phones, wide on sm:+
Getting Started herogetting-started-hero.pngWelcome block on GettingStarted.tsx
Tab favicon + PWA iconsfavicon.ico, favicon-16/32/48.png, icons/icon-192.png, icons/icon-512.pngBrowser tab + iOS home screen + manifest — same cache ?v= in index.html and manifest.json
Tri-colour wordmarkcomponents/brand/BrandWordmark.tsxLyn #2b3138 · Care #1f9dec · OS #2cbebe — auth + desktop sidebar + mobile top bar
AuthShell / AuthBrandHeader / AuthIconFieldcomponents/auth/Column layout · mark + wordmark + tagline · icon-inset fields
Glossy app icon (PNG)BRAND_APP_ICON_SRC in lib/brandAssets.tsLegacy in-app reference — not login/sidebar
Line-art house mark (legacy)lyncareos-login-mark.pngSuperseded on login by Heartmark 2; retained in repo

Asset regenerators (frontend/scripts/ — rerun after changing a source in Branding/):

ScriptSourceOutput
build_brand_mark.pyBranding/lyncareos-heart-mark-2.pngpublic/brand/lyncareos-heart-mark.png
build_auth_bg.pygenerated landscape artauth-welcome-bg[-portrait].png
build_gs_hero.pygs-hand-element-raw.png + heart markgetting-started-hero.png
build_favicon.pyBranding/lyncareos tab icon.pngfavicon.ico, favicon-16/32/48.png, icons/icon-192.png, icons/icon-512.png
build_login_mark.pyBranding/LyncareOS house icon.pnglyncareos-login-mark.png (legacy)

Auth pages keep the light welcome backdrop when the app shell is in dark mode. Constants live in frontend/src/lib/brandAssets.ts (cache-bust with ?v= on change).

Pages: Login.tsx, Register.tsx (extend PendingApproval.tsx when restyled). Sign-in uses cc-btn-primary + arrow; Google button label Continue with Google (GoogleSignInButton text="continue_with").

Reference mockup: docs/02 - ARCHITECTURE_DESIGN/assets/calmcare/lyncareos-login-onboarding.png. Getting Started: /getting-started (admin-only shortcut on More; 8-step checklist).

Brand touchpoint parity (mandatory when changing logo/wordmark):

SurfaceComponent / file
Login / registerAuthBrandHeader.tsx
Desktop shellDesktopSidebar.tsx
Mobile shellMobileTopBar.tsx
Browser tabfavicon.* + index.html
PWA / iOS home screenicons/icon-192.png, icons/icon-512.png, manifest.json

Automated gate: cd frontend && node scripts/check-brand-touchpoints.mjs (also runs in npm run validate:architecture and deploy.ps1 before npm run build). Do not deploy after updating only one surface — the 2026-05-30 mobile miss was incomplete implementation, not a deploy-script bug; deploy.ps1 faithfully shipped the repo as-is.

  • Prefer named function components at module level; keep hooks unconditional at the top.
  • Tailwind + shared classes in index.css (btn-primary, card, nav-link, …). See 03-DESIGN-SYSTEM.md.
  • Dark mode: class strategy on <html> via ThemeContext — pair dark: variants with light styles.

Week at a glance helpers (frontend/src/lib/weekGlanceHelpers.ts, tests in weekGlanceHelpers.test.ts):

Pure functions for the Dashboard WeekAtAGlance widget (components/dashboard/WeekAtAGlance.tsx). Keep all Monday-based week maths and per-day aggregation here — the component only fetches and renders.

  • weekDaysForOffset(offset, today?) — seven Date objects (Mon→Sun) for current/adjacent weeks
  • monthsTouchedByWeek(days) — distinct { year, month } pairs when a week straddles a boundary (drives dual month fetches)
  • formatWeekRangeTitle(days) — compact caption (25–31 May, 29 Jun – 5 Jul, …)
  • buildWeekGlance(days, shifts, appointments, today?) — per-day shift/appointment counts + carerChips (deduped by carer_id, ordered by time slot)
  • carerChipLetter(carerName, displayName) — first letter of login username, fallback display name
  • WEEK_GLANCE_MAX_CARER_CHIPS = 2 — max initials shown per day cell (+ overflow badge)

Widget fetches via api.shifts.list + api.appointments.list for each month touched, merges with dedupeById, and navigates to /calendar?date= on day tap. Gated on Dashboard by care_calendar module (or super-admin). Footer uses truncate whitespace-nowrap on the summary so Open calendar stays aligned on one row on mobile.

Calendar scroll-anchor pills (frontend/src/pages/Calendar.tsx):

Filter pills (All, Appointments, Tasks, Handovers) are scroll anchors, not content filters — every list section stays mounted. handleCalFilterClick calls computeRegionScrollTop to place the target region under the sticky dock; a trailing spacer (scrollSpacerPx) lets the last section scroll fully into view.

Shared day date strip (frontend/src/components/ui/DayDateStrip.tsx):

Horizontal month ribbon used on date-scoped pages — swipe/scroll days, prev/next month, Today jump, emerald dot when daysWithData contains that ISO date. Helpers in lib/dateStripHelpers.ts (selectableDaysInMonth, updateDaysWithDataSet, localTodayIso).

WrapperPage / widgetLabels
components/pain/PainDateStrip.tsxPain & Stats“with pain”
components/vitals/VitalsDateStrip.tsxVital Signs“with vitals”
components/medication-schedule/MedScheduleDateStrip.tsxMedication Schedule (/medication-schedule)“with doses”
Direct DayDateStripDashboard ScheduledDosesStrip“with doses”

Do not build a one-off week picker for these flows — use DayDateStrip (or a thin preset wrapper). The dashboard This week widget (WeekAtAGlance) is the exception: it uses weekGlanceHelpers for Mon–Sun week navigation, not DayDateStrip.

Vital Signs — intake/output capture (mobile-first) (components/vitals/*, page VitalsTracking.tsx):

TopicWhereNotes
Presentation stack14-FRONTEND-PRESENTATION-STACK.mdCanonical tools + component map
Mobile breakpointhooks/useMatchMedia.tsuseVitalsCaptureMobile() → max-width: 639px
Chart mobileuseChartMobileLayout()max-width: 767px; shared intakeOutputChartBase() in lib/chartTheme.ts
Capture sheetVitalsCaptureSheet.tsx + StickyActionBar.tsxFull-screen on mobile; inline cc-surface-float on desktop
Urine beakerUrineVolumeBeaker.tsx + urineBeakerConstants.tsDo not change interior geometry / shell PNG after sign-off
New capture defaultslib/urineCaptureDefaults.tsurineCaptureDefaults() — keep out of component file for fast refresh
Motionmotion/react + usePrefersReducedMotion.tsSheet enter, colour knob layoutId, volume number; no Motion on slider thumb drag
Theme tokenslib/vitalsTheme.tsVITALS_CAPTURE_CARD, section icon classes
E2E smokee2e/vitals-capture-mobile.spec.tsViewport 390×844
a11ye2e/a11y.spec.tsIncludes /vitals route

Quality gates before merge (vitals UI):

Terminal window
cd frontend
npm run validate:architecture
npm run lint:strict
npm run test
npm run build
npm run test:a11y # requires dev stack + Playwright auth env

Medication Schedule — Calm Care pill organiser (pages/MedicationSchedule.tsx):

Presentation helpers in lib/medScheduleCalmCare.ts (slotVisualMeta, slotGivenProgressLabel) map time slots to Morning/Midday/Evening/Night icons only (no daypart background tints). Slot cards use standard cc-card + shadow-soft: 4px left border is sage-500 when all scheduled doses for that slot are recorded for the day, otherwise the admin-assigned group color_hex. Per-medicine round status circles: pending/overdue show the scheduled dose_amount via ScheduleDoseCircleLabel (components/medication-schedule/ScheduleDoseCircleLabel.tsx); dispensed shows a sage check. Coral ring = overdue. Footer legend: sample number in circle = scheduled pending; sage tick = dispensed. Batch record uses the sky-gradient circle in the slot header. Date navigation uses MedScheduleDateStrip; daysWithDoses is loaded from GET /dispensings?date_from=…&date_to=… (90-day window, same pattern as ScheduledDosesStrip). PRN block is a normal cc-card with an amber left-border accent. CellSheet saves dose via addItem / updateItem; handleCellSaved merges into groups[].items so the circle updates without a full reload.

Unified Medications page (pages/Scripts.tsx, nav label Medications, route /scripts):

Prescriptions and tenant medicine catalogue share one surface — MedicationCard shows Doses available (summary.total_stock_on_hand from medicine-summary — same for active and exhausted) Last counted when last_physical_count_at is set (LastPhysicalCountLine), plus the countdown bar (stockCountdownBar() in lib/scriptStock.ts). When status === 'exhausted', show EXHAUSTED_REPEATS_LABEL; do not strike through the medicine name (strikethrough only for archived / superseded). Stock numbers come from the API only (services/script_stock.py); do not use totalDispensedFromScript() for production UI. After Log Dose, dispensingsEvents triggers notifyScriptsChanged() so the card refreshes. FillModal (record_fill) sets server baseline to prior on-hand + quantity_added; preview On hand after collection — historical dose log does not reduce a new pack. MedicineModal handles catalogue fields. Admin manual dose shortcuts (ManualDoseShortcutsSection.tsx) sit at the top (max 4). Legacy /admin/medicines → /scripts.

Stock data sources: List card reads GET …/scripts/medicine-summary; edit modal uses PatientScript from GET …/scripts (total_dispensed on enriched script rows). dispensingsEvents calls notifyScriptsChanged() after Log Dose / schedule dispense so Medications stock lines refresh.

ScriptDetail: Archive retires a prescription; stock block shows doses available, countdown bar, LastPhysicalCountLine. EditScriptModal: PATCH pills_available; field label DOSES_ON_HAND_PROMPT; numeric fields via lib/numericField.ts. ?setup=stock (and Care alerts prescription_stock_count deep link) opens edit for admins with emphasizeStockField — modal scrolls to DOSES_ON_HAND_PROMPT and shows an amber highlight when on-hand is 0 or needsStockCountGuidance(script). Same highlight when opening edit from Medications at zero on-hand (scroll only when emphasizeStockField). Prescription computed banners: Ignore 3 days (V105/V114); Home refetch via scriptsEvents.ts. Care alerts bell lists prescription_stock_count for admins only; saving a positive on-hand count clears the row without Mark done. Members use inline StockCountGuidancePanel on Log Dose / schedule.

Log a dose — Calm Care manual entry (pages/LogDose.tsx):

Stacked section cards via components/logDose/LogDoseSection.tsx for When, Dose amount, and Reason. Medicine is a plain heading plus a 2×2 grid of per-patient quick-pick pills with an optional Other medicines dropdown below. Quick picks are configured in place — the Edit quick picks / Choose quick medications link beside the Medicine heading opens LogDoseQuickMedsModal (max 4, GET/PATCH /api/patients/{id}/log-dose-settings, persisted to patients.manual_dose_quick_script_ids). There is no Medications settings screen for this; the log-dose link is the only entry point. On desktop Log a dose is itself a pop-up (LogDosePageShell, z-sheet), so the quick-picks dialog must stay on the z-dialog rung — see 04-OVERLAY-REGISTER.md §Stacking ladder. Cancer hub deep link: URL params reason_type_id, reason=breakthrough, source=cancer pre-select the breakthrough reason chip and show a context banner. When needsStockCountGuidance(script) (0 on hand but dose log or fills show activity), StockCountGuidancePanel on the form explains the mismatch — dose logging is not blocked; admins get Update doses on hand → /scripts/{id}?setup=stock. After Record dose, the success view refetches the script and shows the same panel when guidance still applies; admins see a note that Home / Medications also show the stock_count_needed banner. stock_count_needed requires dose log > 0 — not shown when both on-hand and dose log are zero. Dose amount via centred +/− stepper (lib/logDoseHelpers.ts). Primary action cc-btn-accent “Record dose”.

Shopping — Calm Care list + add-items sheet (pages/Shopping.tsx, components/shopping/*):

SurfaceKey filesNotes
Active listShoppingListRow.tsx, ActiveItemList.tsx, SwipeActionRow.tsxRows inside cc-card. Desktop: rounded-xl icon well, inline ± quantity, sage purchase check, remove. Mobile (≤639px): wrap row in SwipeActionRow — swipe right Purchased, swipe left Remove; qty via tap → BottomSheet stepper. Do not add a fifth inline control on mobile.
List stateShopping.tsxAfter fetchLists, reconcile activeListId against server lists; reset list/item state on patientId change. On item fetch 404 (“Shopping list not found”), re-fetch lists — do not leave a stale tab id pointing at a deleted list.
Add flowAddItemsSheet.tsx, CategoryBrowser.tsxMobile apricot FAB / desktop dashed Add items opens BottomSheet. Search + category browse live in the sheet only. Category picker: compact cc-card tiles (rounded-2xl). Subcategory filters: compact horizontal cc-chip row (!min-h-[30px], text-xs, 14px icons).
Catalog tilesCatalogItemTile.tsx, CatalogAddProductTileUniform picker cards: rounded-2xl surface, fixed 34×34 rounded-xl icon well + 10px two-line label. Grid constants (CATALOG_TILE_GRID, CATALOG_TILE_ICON_PX, CATALOG_TILE_ICON_WELL_EXTRA) exported from the same module — import for any new browse/search grids.
IconsIconResolver.tsxResolves emoji → svg/url raster → substitute → cart. Catalog pickers (CatalogItemTile, PurchasedTile, CategoryBrowser) must pass loadPriority="eager". On mount, sync rasterReady from img.complete && naturalWidth > 0 so cached assets are not left at opacity-0 behind the pulse placeholder.
List tabsShoppingListTabs.tsxcc-chip row inside a soft card.
Purchased historyPurchasedSection.tsx, PurchasedTile.tsxCollapsed by default; expanded horizontal strip of tiles matching CatalogItemTile proportions (imports CATALOG_TILE_* constants — do not reintroduce legacy tinted catalogListTileScheme cards or full-bleed square photos).
Dashboard nudgeShoppingDashboardWidget.tsxCalm Care card on Dashboard.tsx when shopping module enabled.
Legacy / testsShoppingItemCard.tsxTile grid retained for unit tests — do not wire back as the primary list UI.

Real-time sync: hooks/useShoppingSync.ts (SSE shopping_list_updated). Product spec: 06-SHOPPING-MODULE.md · Design: 03-DESIGN-SYSTEM.md §8.

Rule: All catalog add/search grids in the add-items flow must use CATALOG_TILE_GRID so every product tile stays the same cell size. Shopping card surfaces use rounded-2xl / rounded-xl wells — do not use circular .cc-icon-chip on list rows, catalog tiles, or category pickers; reserve .cc-chip for horizontal filter rows (list tabs, subcategories).

7.3 Types and OpenAPI contracts (REQ-PLAT-10)

Section titled “7.3 Types and OpenAPI contracts (REQ-PLAT-10)”

Pipeline (run after backend model or route schema changes):

Terminal window
cd backend
python scripts/export_openapi.py # writes openapi/openapi.json
cd ..\frontend
npm run generate:types # writes src/lib/api.types.ts
npm run check:types-drift # fails if api.types.ts is stale

Commit openapi/openapi.json and frontend/src/lib/api.types.ts together. CI job openapi-contracts enforces both with git diff.

FileRole
openapi/openapi.jsonCommitted OpenAPI export (offline input for generation)
lib/api.types.tsAuto-generated — never hand-edit
lib/api.contracts.tsStable export type X = Schema<'X'> aliases; add new aliases here
lib/api.tsrequest() helpers; import type from contracts for types used inside this file, plus export type { … } for consumers

Rules:

  • New request/response shapes: add or extend Pydantic models in backend/models.py and wire response_model on routes when possible, then re-run export + generate:types.
  • Do not redefine in api.ts a shape that already exists in api.contracts.ts / OpenAPI — alias it instead.
  • Response-only shapes not yet in OpenAPI (no response_model) stay as manual interfaces in api.ts until the backend exposes them in the schema.
  • Domain splits under lib/types/<domain>.ts continue (Phase 0 H-07). Request bodies in types/care.ts now come from api.contracts.ts (ShiftCreate, AppointmentCreate, …). Entity types without OpenAPI schemas (CareShift, PatientAppointment) remain manual.

When adding types in api.ts, use both import type (local scope for request<T>()) and export type (for other modules). Re-export-only blocks do not satisfy tsc inside api.ts. Run cd frontend && npm run build before scripts/deploy.ps1.

From repo root:

Terminal window
.\scripts\push-to-production.ps1 # default — dev + Docker UAT + VPS (see doc 20 §2b)
.\migration-audit.ps1 -Target Vps -NonInteractive # repo vs live schema_migrations
.\scripts\deploy.ps1 # VPS only — build, backup, push, migrate on startup, smoke test

7.4a Where the SPA is cached (browser vs Cloudflare)

Section titled “7.4a Where the SPA is cached (browser vs Cloudflare)”
SurfaceServes fromInvalidation on app deploy
app.lyncareos.comVPS Docker (backend/main.py static + API) via Cloudflare TunnelAutomatic — see below
lyncareos.com marketingCloudflare PagesSeparate — scripts/deploy-marketing-pages.ps1

The clinical SPA is not on Cloudflare Pages. Do not run a Cloudflare cache purge for app UI releases — the pipeline below handles it:

  1. Hashed bundles — Vite emits new assets/*.js / *.css filenames each build.
  2. Service worker version — frontend/scripts/inject-sw-version.mjs replaces __BUILD_ID__ in built sw.js so CACHE_NAME changes every build.
  3. Origin headers — backend/main.py sets no-cache, no-store, must-revalidate on index.html and sw.js so Cloudflare/browser revalidate every request.
  4. Client reload — frontend/index.html registers the SW, polls reg.update() every 5 minutes and on tab visibility, and calls safeReload() on SW_UPDATED / controllerchange (deferring while the user is typing in a form).

/api/* is network-only in the service worker — data is always fresh from the API.

7.4b Post-deploy verification (required for screen/UI releases)

Section titled “7.4b Post-deploy verification (required for screen/UI releases)”

After deploy.ps1 completes, verify before announcing the release:

Terminal window
curl.exe -s https://app.lyncareos.com/sw.js | Select-String CACHE_NAME
curl.exe -sI https://app.lyncareos.com/ | Select-String -Pattern "cache-control|cf-cache-status"
curl.exe -s -o NUL -w "%{http_code}" https://app.lyncareos.com/api/billing/tiers
  • CACHE_NAME must differ from the previous deploy — unchanged hash means mid-session users may not auto-refresh.
  • index.html must return Cache-Control: no-cache, no-store, must-revalidate.
  • Mid-session smoke (optional but recommended): keep a tab open before deploy; after deploy, navigate to a lazy route — expect a brief reload, not a stale-chunk error card.

Full checklist: 20-PRODUCTION-DEPLOYMENT-GUIDE.md §6. Background: docs/plans/2026-05-29-spa-deploy-resilience.md.

push-to-production.ps1 runs on the workstation. If it hangs during Docker UAT backup (db-backup.ps1), production is unchanged until deploy.ps1 step 5 finishes on the VPS. Recover by stopping the local PowerShell process and fixing Docker Desktop — do not kill production containers outside the normal vps-pull-and-start.sh --redeploy path inside deploy.ps1.

If the release includes V090+ and production has not been backfilled: .\scripts\production-migration-preflight.ps1 -RunBackfillIfNeeded runs automatically inside deploy.ps1, or run it manually first.

After first PHI backfill without explicit keys: .\scripts\production-phi-pin.ps1 on VPS (also runs at end of deploy.ps1 when keys are missing); on dev, .\scripts\dev-phi-pin.ps1 for backend/.env.

If email login fails after pinning PHI keys (username login still works): run python seed_admin.py or python -m migrations.scripts.repair_phi_email_indexes from backend/. See ../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md §401 email after PHI.

V1 baseline cutover (brownfield → squashed schema): one-time per environment — dev: .\scripts\v1-baseline\Invoke-V1Cutover-Dev.ps1; production: .\scripts\v1-baseline\Invoke-V1Cutover-Vps.ps1 (includes deploy + backup). Runbook: 24-V1-DATABASE-BASELINE-AND-CUTOVER.md. Normal releases after cutover use deploy.ps1 + forward V00N__… migrations only.

See [04 - OPERATIONS/11-DATABASE-SAFETY-AND-MIGRATIONS.md §7](../04 - OPERATIONS/11-DATABASE-SAFETY-AND-MIGRATIONS.md) and 03%20-%20DEPLOYMENT%20AND%20PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md §5.

  • Avoid any; use explicit interfaces and unknown with narrowing where needed.

Scripts API (api.scripts in lib/api.ts — post-V103 medication surface):

MethodEndpoint / helperUse when
list(patientId, …)GET /api/patients/{id}/scriptsAll carer-facing pages — Medications list, schedule matrix, Log Dose picker, chart legend
create / update / …POST|PATCH /api/patients/{id}/scriptsNew or edit prescription (name, colour, PRN, fills)
medicineSummary / alertsGET …/medicine-summary, …/alertsStock/expiry summaries on Medications page

Rule: Scope every call by patient_id from PatientContext. Reload when activePatient?.id changes. Schedule/dispense use api.medicationGroups and script_id on schedule items — not medicine_id.

Frontend regression: frontend/src/test/components/MedicationSchedule.test.tsx (calls listForPatient with active patient id, never the tenant-wide list).

Shared Core Principles (alerts, realtime, hooks)

Section titled “Shared Core Principles (alerts, realtime, hooks)”

Care alert surfaces — when to use which

SurfaceUse whenExamples
Team inbox (care_alerts + bell)Cross-module operational item the care team should see and resolveShopping list count, overdue dose, script stock count (admin), help board
In-page banner (/scripts/alerts, etc.)Contextual guidance on the page the user is already onScript stock count prompt on Medications; member-visible; per-user dismiss
BothSame domain condition, different audience/UXScript stock: bell (admin inbox) + banner (all roles on Scripts) — share script_stock_evaluator, do not merge UI

Realtime — SSE vs CustomEvent

MechanismUse whenExamples
Redis SSEMulti-device / multi-user sync for one patient scopeShopping list (useShoppingSync)
Postgres NOTIFY SSELong-running job progressPrescription scan queue
Browser CustomEventSame-tab cache invalidation after mutationSCRIPTS_CHANGED_EVENT, DISPENSINGS_CHANGED_EVENT → refresh bell count, Scripts list

Care alert modes

ModeBehaviourExamples
syncRecompute domain state; upsert or auto-resolve when clearedshopping, overdue_dose, prescription_stock_count
eventFire on mutation; dedup per entitypain, mind, calendar, help, shift cancel
scheduledAPScheduler triggers sync/raiseshift reminder, overdue hourly sweep

Adding a new alert type (target pattern)

  1. Register a handler in services/alert_registry.py (signal type → handler config).
  2. From domain code, call emit_alert_signal(AlertSignal(...)) after HTTP commit — do not call alert_service directly from new code.
  3. Sync handlers: one open row per dedup key; use auto_resolve_by_dedup when condition clears.
  4. Document channel key in tenant_notification_settings and AlertSettings.tsx if tenant-toggleable.

Alert-type inventory (current)

alert_typemodechanneldedup_keydeliveryemit signal / call site
shoppingsyncshoppingshopping:{patient_id}backgroundshopping.changed ← shopping_service
overdue_dosesyncoverdue_doseoverdue_dose:{patient_id}:{dose_date}background + crondose.dispensed, scheduler sweep
prescription_stock_countsyncmaster onlyprescription_stock_count:{patient_id}:{script_id}backgroundscript.stock_changed
body_pain_higheventbody_pain_highbody_pain_high:{patient_id}:{date}backgroundpain.recorded
mind_elevatedeventmind_elevatedmind_elevated:{patient_id}:{date}backgroundmind.recorded
calendar_eventseventcalendar_eventscalendar_events:{patient_id}:{entity_id}:{date}backgroundcalendar.changed
handover_noteseventhandover_noteshandover_notes:{shift_id}backgroundshift.handover
shift_cancelledeventshift_cancelledshift_cancelled:{shift_id}backgroundshift.cancelled
shift_reminderscheduledshift_remindershift_reminder:{patient_id}:{carer_id}:{date}scheduledAPScheduler
new_help_requesteventfamily_helpnew_help_request:{request_id}backgroundhelp.created
help_request_takeneventfamily_helphelp_request_taken:{request_id}backgroundhelp.taken
module_purchase_requesteventmodule_purchase_requestsmodule_purchase_request:{module}backgroundmodule.purchase_requested

Post-commit runner: schedule_after_commit in services/post_commit.py (pool connection via alert_tasks.run_alert_task).

Care alerts API (api.alerts in lib/api.ts — paths are without /api; see §7.1):

  • list({ status, patient_id, limit }) — GET /api/alerts
  • openCount(patientId) — badge count for active patient; AlertContext polls every 60s and on scriptsEvents / dispensingsEvents
  • resolve(id, note?) — POST /api/alerts/{id}/resolve (carers/admins only — observers get 403)
  • getSettings() / updateSettings(patch) — GET|PATCH /api/admin/alert-settings (tenant admin; includes family_help channel)

Alert types in UI (AlertRow.tsx): shift/calendar/handover/shopping/pain/mind/overdue dose; prescription_stock_count (Pill icon, admin-only in list/count); new_help_request and help_request_taken (HandHeart icon). prescription_stock_count deep_link → /scripts/{id}?setup=stock&patientId={id}; sync via alert_script_sync.py after dispense or pills_available PATCH. Overdue dose shows one inbox row per patient per day; when metadata.miss_count > 1, a numeric badge appears beside the title (body text also states the count, e.g. “3 scheduled doses not recorded”). Shopping shows one inbox row per patient; body states the live active-item count (e.g. “4 items on the shopping list.”); auto-resolves when all items are purchased or removed.

Overdue dose backend (after dispense or hourly sweep): alert_dose_sync.sync_overdue_dose_alert_for_patient — do not call alert_overdue_dose per group. Hooks: schedule_refresh_overdue_dose_alert in alert_dose_hooks.py. Requires migration V100 on the target database.

Shopping alert backend (after add/purchase/unpurchase/remove/recurring reset): alert_shopping_sync.sync_shopping_alert_for_patient — do not raise one alert per item. Entry point: alert_service.alert_shopping_item → sync; scheduled from shopping_service._schedule_shopping_alert_sync. Dedup key: shopping:{patient_id}; metadata: item_count.

Authenticated provider tree (App.tsx protected routes):

ProtectedRoute → ModuleProvider → PatientProvider → AlertProvider → Layout → <Outlet />

ModuleContext (ModuleContext.tsx): one GET /api/subscriptions/active on login — activeModules plus careModuleBoards from feature_flags.

Care boards (CareModuleFlagsContext.tsx): export useCareModuleFlags() only — no CareModuleFlagsProvider. The hook must run under ModuleProvider (e.g. CareBoardDashboardChip, CareBoardGate). Do not reintroduce a second provider; it caused useCareModuleFlags must be used inside <CareModuleFlagsProvider> when auth refresh failed or HMR left a stale tree.

Troubleshooting: 502 on /api/auth/refresh = Vite proxy cannot reach the backend — restart run_server.py and confirm VITE_API_URL in frontend/.env.

Condition packs API (conditionPacksApi in lib/api.ts, V077–V078):

  • listArchetypes() — seven care archetypes for onboarding
  • listPacks() — all Care Profiles with has_access, can_purchase, price_display, and billing_currency per tenant. Backend: one cached Frankfurter lookup per currency per list (see aud_minor_units_per_aud in stripe_service.py).
  • previewPack(packId) — pack metadata + seed lists; Subscriptions UI shows feature_bullets on the card and a marketing-first preview for cancer_at_home (V012)
  • purchasePack(packId) — Stripe Checkout for one-time profile unlock
  • api.patients.careStart.apply / .recommended / .patchCarePattern — Care Start apply, recommended pack, non-destructive pattern correction (C5c).
  • Backend: services/care_start_service.py, services/care_start_checkout.py (signup bundle + first-patient auto-apply), routers/care_start.py (prefix /patients, mounted at /api and /api/v1).
  • UI: PatientCareStartWizard.tsx on Add Person — demographics only (2026-06-26); CareProfileQaPanel.tsx (dev, user id 1) for one-tap apply; CarePatternPanel.tsx and ArchetypeOnboarding.tsx deleted. No standalone /care-archetypes page (redirect → /subscriptions).
  • Signup bundle: POST /api/stripe/start-signup optional care_start_pack_slug, care_start_bundle, archetype_slug → Stripe metadata → tenants.pending_care_start_pack_slug at provision.
  • Migrations: V006–V014 on dev (11-DATABASE-SAFETY §2i–§2n); apply with .\migrate.ps1 -Target Dev.
  • Tests: backend/tests/test_care_start.py, test_care_start_checkout.py, test_condition_pack_billing.py, test_medicines.py (per-patient reason list).

Reason types API (api.reasonTypes):

  • list(patientId) — GET /api/reason-types?patient_id=
  • create({ patient_id, name, description, color_hex, display_order, active }) — admin only

Dev performance: If every page feels slow with Redis stopped, confirm middleware/rate_limit.py uses memory:// when IS_PRODUCTION is false. Start Redis (docker compose up redis -d) for SSE tickets and FX cache. Subscriptions loads catalog, tier, and packs in parallel (Subscriptions.tsx).

Observations API (observationsApi in lib/api.ts):

  • listTypes(patientId) — observation types enabled for a patient (seeded from condition packs)
  • record(patientId, payload) — saves a single observation reading; returns threshold_breach flag
  • trend(patientId, typeId, window) — rolling mean + σ band (Bollinger-style) for a time window

Family help requests API (helpRequestsApi in lib/api.ts):

  • listTypes() — 25 default request types grouped by category
  • list(patientId, status) — open / taken / completed requests for one patient
  • create(patientId, body) — post a new help request; service commits then schedule_alert → alert_help_request (new_help_request)
  • take(patientId, id) — volunteer takes ownership; resolves open new_help_request:{id} alert and raises help_request_taken
  • complete(patientId, id) — mark as done
  • cancel(patientId, id) — requester cancels an open request

Raise alerts from the backend via emit_alert_signal(AlertSignal(...)) after commit — handlers run on a pool connection through schedule_after_commit (requires app lifespan / open pool — not available in pytest savepoint tests; call sync/handler functions on the test db fixture instead). Legacy direct alert_service.* calls are deprecated. APScheduler overdue-dose sweep uses alert_scheduler.py → registry / alert_dose_sync.py.

Pain entries API (api.pain in lib/api.ts, V082 + V092):

  • body_layer on create/update — allowed values: front, back, front-skeleton, back-skeleton, skeleton (legacy), mind, surface
  • Responses always include body_layer (required on read)
  • Bone overlay mode in PainBodyMapTab saves front-skeleton / back-skeleton; requires migration V092 on the target database
  • Bone overlay UI: BodyMap boneOverlayMode limits interactive hits to the body <img>; layer pills sit in a z-30 header above the map (see 26-PAIN-STATS-MODULE.md §4.1)

Observations API (observationsApi in lib/api.ts, added V079):

  • getTypes(patientId) — list available ObservationType entries for this patient (universal + archetype-specific)
  • list(patientId, { obsTypeId?, from?, to? }) — time-series PatientObservation entries
  • create(patientId, { observation_type_id, obs_date, obs_time, value_number?, value_text?, value_boolean?, notes? }) — record one observation
  • getTrend(patientId, obsTypeId, window) — Bollinger-band trend series (ObsTrendPoint[])
  • delete(patientId, obsId) — soft-delete (is_active = false)

Types: ObservationType, PatientObservation, ObsTrendPoint, ObsValueType, CaptureWidget.

Sleep trend helpers (frontend/src/lib/sleepTrendHelpers.ts, tests in sleepTrendHelpers.test.ts):

Pure functions for 10-day rolling bedtime / wake-time curves. Their only renderer was the legacy SleepGrid.tsx, removed 2026-07-28 when the Sleep Pattern recording surface moved to SleepDayClock.tsx (see doc 02-REQUIREMENTS.md REQ-SLEEP-03) — the calculation still lives here and is still tested, but nothing currently renders it. Re-wire onto the clock (e.g. a small trend chip) or retire via the reconciliation doc before relying on this again.

  • SLEEP_TREND_ROLLING_DAYS = 10 — trailing window size for the smoothed curves
  • SLEEP_SESSION_MAX_GAP_MINS = 30 — awake gap above which contiguous blocks split into separate sessions
  • BEDTIME_EARLIEST_MINS = 16 * 60, WAKE_WINDOW_START_MINS = 4 * 60, WAKE_WINDOW_END_MINS = 11 * 60, MAIN_SLEEP_MIN_MINS = 4 * 60 — anchor windows and minimum main-sleep duration
  • mergeWithinGapTolerance(intervals, maxGapMins) — generic interval merge; same helper drives both bedtime and wake derivations
  • getDayBedtime(dayEntries) — anchors on the latest evening start (≥ 16:00), then walks earlier same-day blocks back through any ≤ 30-minute awake gaps to find the true bedtime
  • getDayWakeTime(dayEntries, allEntries, date) — anchors on the latest morning end inside 04:00–11:00 (with ≥ 4-hour duration including overnight continuation from the previous day’s 24:00 entry), then extends through later blocks connected by ≤ 30-minute gaps

SleepGrid clips the smoothed curve at min(today, last calendar row with any logged sleep) so the line never runs into empty rows.

Help requests API (helpRequestsApi in lib/api.ts, added V080):

  • list(patientId) — open and recent help requests for the patient’s care circle
  • create(patientId, payload) — post a new help request
  • offer(requestId) — volunteer to fulfil a request
  • close(requestId) — mark request fulfilled

When changing registration or approvals:

  • Invited users: often users.status = pending and tenant_memberships.status = invited until an admin approves.
  • Approval should update both users.status = approved and tenant_memberships.status = active in a coherent way (see existing users router).
  • Invitation tokens: single-use, expiry — validate before accepting.

Pending count for admins: use the lightweight GET /api/users/pending-count (or equivalent) rather than loading the full user list for a badge.


Terminal window
cd backend
.\venv\Scripts\Activate.ps1
$env:TEST_DATABASE_URL = "postgresql://lyncare:lyncare@localhost:5432/lyncareos_test"
pytest -m "not slow"
  • TEST_DATABASE_URL (default postgresql://lyncare:lyncare@localhost:5432/lyncareos_test) — see tests/conftest.py. Conftest applies lyncareos_v1_baseline.sql on an empty test DB, otherwise schema.sql; seeds active migrations only; isolates each test with savepoints.
  • CI runs the same command on Postgres 16 (pytest -m "not slow" — 64 modules, ~797 tests). Live Stripe API tests are @pytest.mark.slow — run locally only when STRIPE_SECRET_KEY=sk_test_… is set.
  • D6 prep: python scripts/d6_router_test_coverage.py prints router SQL baseline vs test-file mapping.
  • Run tests before merging non-trivial backend changes.
  • Backend suites include (non-exhaustive): test_auth_routes.py, test_care.py, test_dispensings.py, test_prescriptions.py, test_medication_schedule.py, test_medicines_patient_isolation.py (REQ-MED-14 cross-patient leak guard), test_analytics.py, test_patient_analytics_isolation.py (REQ-MED-15 analytics/alerts/export/audit isolation), test_auto_dispense.py, test_first_dose_reactions.py (REQ-MED-16), test_key_contacts.py, test_shopping.py, test_catalog_admin.py, test_migration_runner.py, test_lm_studio.py, test_user_module_access.py, test_v029_sleep_subscription_backfill.py, and others under backend/tests/.
  • Analytics MV in tests: tests/conftest.py patches refresh_analytics_dispensing_summary to refresh on the per-test db connection (savepoint-visible). create_dispensing() also refreshes after direct inserts. Production uses the pool with REFRESH … CONCURRENTLY when autocommit allows.
  • Essential tier QA (dev): .\scripts\seed-dev-essential-tenant.ps1 — creates essentialqa / EssentialQA1! on lyncareos_dev with Essential-only modules (backend/scripts/seed_dev_essential_tenant.py). Requires DATABASE_URL in backend/.env pointing at lyncareos_dev.
  • Peter Care Profile + board QA (dev): .\scripts\seed-dev-peter-care-qa.ps1 — prepares tenant peter for Subscriptions catalogue + cancer/breathing board testing (backend/scripts/seed_dev_peter_care_qa.py). See §7.1j.

After migration V091, plaintext identity columns (users.email, patients.name/dob, tenants.name, care_groups.name) no longer exist. Tests must use tests/conftest.py helpers — never raw INSERT into those columns:

HelperUse when
insert_phi_userNeed only a user row
insert_phi_tenantNeed a tenant for an existing owner
insert_phi_patientNeed a patient with encrypted name/DOB
provision_phi_accountUser + tenant + membership in one call
create_user_and_loginFull account + JWT (uses PHI helpers internally)
create_patient / create_member_in_tenantWrappers around PHI insert helpers

Regression suite: tests/test_phi_field_encryption.py (30 tests, @pytest.mark.regression).

Terminal window
python -m pytest tests/test_phi_field_encryption.py -m regression -v

Note: pending_signups.email and medication_groups.name are unchanged — only the four identity tables above were encrypted.

Frontend: cd frontend → npm run test (Vitest), npm run test:e2e (Playwright). The unit suite is green at 233 passing.

Test environment shims (src/test/setup.ts): jsdom omits some DOM APIs that real components call. The setup file polyfills matchMedia, URL.createObjectURL, localStorage, and Element.prototype.scrollIntoView (a no-op) — the last is required by any component that calls scrollIntoView in a layout effect (e.g. components/ui/DayDateStrip.tsx). Add the shim here rather than per-test when introducing a component that uses an unimplemented jsdom API.


Terminal window
cd frontend
npm run lint
npm run build

npm run build runs tsc -b and Vite build — catches many TS errors.


Branches: feature/…, fix/…, docs/…, chore/…

Commits (Conventional Commits style):

feat(dispensings): add filter by medicine
fix(auth): preserve session on 403 responses
docs: align developer guide with Docker ports

Before opening a PR:

  • Frontend: npm run build and npm run lint pass
  • Backend: pytest where applicable
  • New API routes have correct auth / tenant / module dependencies
  • No stray console.log or secrets
  • Schema changes handled for new and existing DBs (DDL + IF NOT EXISTS alters as needed)

Backend

  • SQL built with string concatenation from user input
  • Skipping commit() after mutations
  • Public endpoints that return tenant-scoped data without auth
  • Hard-coded secrets (use config.py / env)

Frontend

  • Treating 403 like 401 for session handling
  • Storing secrets in source
  • Inline style={{}} when Tailwind can express the rule (exception: dynamic colours from API, e.g. profile swatches)

General

  • Assuming /api/v1/ or a monorepo shared package exists in this repo — they do not
  • Registering Care Module board routes without checking CARE_BOARDS_BUILD_ENABLED / server feature_flags — boards must remain optional for launch
  • Treating Care Profile pack unlock as sufficient to show board UI without CARE_MODULE_BOARDS_ENABLED — commerce and plugin UI are separate layers

  1. Read docs/02-REQUIREMENTS.md, 01-ARCHITECTURE.md, 04-ROADMAP.md, and this guide before large changes.
  2. Search for an existing pattern (router, page, component) and extend it.
  3. Prefer editing existing files over adding parallel structures.
  4. Do not change API response shapes without updating lib/api.ts and callers in the same change. Database is master — persist mutations through the API; do not treat the browser as the source of truth for clinical data.
  5. Match style of the file you edit (quotes, formatting).

The Pain Tracking feature uses a set of predefined rectangular zones (x1, y1 → x2, y2 as image-percentage coordinates) to translate a tap position on the body image into an anatomical label (e.g. “Left Tricep”, “Lower Back Centre”). Because male and female images have different proportions and framing, each gender maintains its own independent zone set.

Zones are defined in:

frontend/src/components/pain/BodyMap.tsx

as four arrays:

ConstantScope
FRONT_ZONES_MALEMale, front view
BACK_ZONES_MALEMale, back view
FRONT_ZONES_FEMALEFemale, front view
BACK_ZONES_FEMALEFemale, back view

The tool is development-only — it is gated by import.meta.env.DEV and is completely absent from production builds. There is no visible button — it is activated by keyboard shortcut to keep the UI clean during normal development.

  1. Start the dev servers (.\dev-start.ps1 or npm run dev).
  2. Log in and navigate to the Pain Tracking page (/pain).
  3. Select a patient whose gender matches the image you want to calibrate.
  4. Press Ctrl+Shift+K — the calibration overlay appears immediately.
  5. Press Ctrl+Shift+K again (or follow the on-screen prompt) to exit.
┌─────────────────────────────────────────────────────┐
│ ⚙ Calibrate Zones [Male] [Female] │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Body image with coloured dot per zone │ │
│ │ Each dot is DRAGGABLE — label shown nearby │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ Coordinate readout panel (appears after first drag) │
│ cx= 51.7 cy= 6.0 ← MOVED │
│ ... │
│ [Copy all] │
└─────────────────────────────────────────────────────┘
  1. Select gender using the [Male] / [Female] toggle that appears while calibrating. Calibrate one gender at a time.
  2. Drag each dot to the visual centre of the anatomical region on the body image. The dot label identifies which zone it represents.
  3. After moving a dot the readout panel appears below the gender toggle, listing cx (horizontal %) and cy (vertical %) for every zone. Zones you moved are marked ← MOVED.
  4. Click Copy all to copy the full coordinate block to the clipboard.
  5. Paste the block into this conversation or share it with the team.

Tip: Calibrate front and back separately — use the front image to refine all front zones, then switch to the back view by tapping the back body image (or scrolling to it) and dragging those dots.

14.3 Applying calibration output to the code

Section titled “14.3 Applying calibration output to the code”

The coordinate readout gives cx / cy — the zone centre as a percentage of the image container width and height. To convert to the x1, y1, x2, y2 rectangle used in the zone arrays:

halfW = half the zone's visual width (estimate from anatomy — typically 7–10 for narrow zones, 14–18 for wide ones like head/abdomen)
halfH = half the zone's visual height (typically 4–8)
x1 = cx − halfW x2 = cx + halfW
y1 = cy − halfH y2 = cy + halfH

Paste the coordinate block as a user message and the AI assistant will compute the new x1, y1, x2, y2 values and update the correct constant in BodyMap.tsx. Zones that are not marked ← MOVED can be left unchanged.

To add a new anatomical region (e.g. “Left Tricep”):

  1. Add a new Zone entry to the relevant array(s) in BodyMap.tsx with estimated coordinates.
  2. Place the entry before any broader zone it should override (zones are tested in order; first match wins).
  3. Run the calibration tool to drag the new dot into position.
  4. Apply the output coordinates using §14.3.

Both gender variants (_MALE and _FEMALE) must be updated — zones are not shared between genders.

All coordinates are stored as percentages of the image container, not pixels. The hotspot overlay uses the same percentage-based left / top CSS positioning. This means:

  • Zone detection and hotspot placement scale automatically with any container size.
  • The female image applies a scale(1.05) translateY(-5.5%) transform — zone coordinates for female images are calibrated after this transform is applied, so no manual adjustment is needed when the scale constant changes.

Re-run calibration whenever:

  • Body images are replaced or re-cropped.
  • The FEMALE_SCALE or FEMALE_OFFSET_Y constants in BodyMap.tsx are changed.
  • New zones are added to a view.
  • User feedback indicates a tap lands on the wrong label.

14.7 Future body types — children and babies

Section titled “14.7 Future body types — children and babies”

The calibration system is designed to be extended. Planned future variants:

VariantImages neededZone arrays to add
Child — maleChild Male Front.png, Child Male Back.pngFRONT_ZONES_CHILD_MALE, BACK_ZONES_CHILD_MALE
Child — femaleChild Female Front.png, Child Female Back.pngFRONT_ZONES_CHILD_FEMALE, BACK_ZONES_CHILD_FEMALE
Baby / infantBaby Front.png, Baby Back.pngFRONT_ZONES_BABY, BACK_ZONES_BABY

Key anatomical differences to account for:

  • Infant and child proportions differ significantly from adults — the head is proportionally much larger, limbs shorter relative to torso, and the abdomen more prominent. Zones cannot be copied from adult arrays; a full calibration pass is required for each new body type.
  • Infant zone vocabulary will differ — for example, fontanelle region (head), nappy area, and fewer granular limb sub-zones. Plan the slug names and labels before beginning calibration.
  • The arm-back / tricep split may not apply to infants — a single zone per arm is likely sufficient.

Code changes required when adding a new body type:

  1. Add the transparent PNG images to frontend/public/ (or assets/).
  2. Extend the gender (or introduce a new bodyType) prop type in BodyMap.tsx and PainTracking.tsx.
  3. Add the zone constant arrays and extend getZones() to branch on the new type.
  4. Add the new images to the BodyMap render logic with appropriate scale/offset constants (use the calibration tool to determine these).
  5. Extend the Patient model / schema / DB column to capture the body type selection (e.g. body_type: 'adult' | 'child' | 'baby' or derive it from date_of_birth automatically).
  6. Run the calibration tool for each new view (front and back) and apply coordinates using §14.3.

Image production guidelines for new body types:

  • Generate all variants (child male front, child male back, child female front, child female back, baby front, baby back) in a single AI image at identical proportions before extracting individuals — this ensures consistent scale across the set, exactly as was done for the adult male/female images.
  • Export as transparent PNGs with no background.
  • Target the same canvas height as the adult images so the image containers remain a consistent size across patient types.

For operational backup/restore scripts and volume safety, see [../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md](../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md) and repo scripts db-backup.ps1 / db-restore.ps1 where applicable.