Commit Graph
9 Commits
Author SHA1 Message Date
GandClaude Opus 5 3e059f0818 chore: add a formatter (#83)
* chore: add a formatter, matching the style this repo already writes

singleQuote=false was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.

Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* style: format with prettier (304 files)

Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: teach git blame to skip the reformat

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* style: format the two files the reformat pass missed

prettier --check flagged app/shared.module.css and lib/domain/clinicians.test.ts
on a branch whose whole point was that everything had been formatted. Re-running
the same command with the same version fixes both, so the rollout's write step
did not finish what it reported.

The rollout now runs --check straight after --write and refuses to open a PR
unless it comes back clean, so a partial reformat fails at the source instead of
in CI.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 10:48:01 +00:00
GandClaude Sonnet 5 6fc4ac7086 feat(shell): notifications, grouped admin nav, admin mobile tabs, a working mega menu, and a real footer (#64)
Phase 1 of a full clinician/patient UI redesign George asked for after we
shipped the actor-aware cancellation copy fix (#63) — he judged the wider
nav/notification/mobile experience underneath it as poorly designed. This is
the shared foundation (nav, header, notifications, mobile, mega menu, footer)
that every individual page redesign in later phases will sit on top of.

In-app notifications (lib/domain/notifications.ts, app/api/notifications/*,
components/shared/NotificationBell.tsx): a companion to the existing email
sends, not a replacement — wired alongside sendEmail at 5 trigger sites
(new message, every booking lifecycle event, critical-signal + goal-achieved
in cron/signals, clinician application decisions, document uploads). One
shared bell component in both admin and portal headers, 30s polling reusing
the existing MESSAGE_POLL_INTERVAL_MS constant. Kept as an in-repo module,
not a published package — no second adopter yet to justify that (same
rule-of-three standard that produced threadkit, which vitareba already
imports for message read/write/unread — verified before starting, so no
messaging-domain work was needed here).

Admin nav (lib/config/routes.ts ADMIN_NAV_GROUPS, components/admin/AdminNav.tsx):
flat 8-item list replaced with grouped sections mirroring the portal's own
Care group, so the same clinician relationship reads the same shape from
either side. Fixed the "always-on badge" problem: urgentPatients and
pendingApplications were live state counts with no seen-at gate, so a
clinician who'd already reviewed everything still saw a nonzero badge
forever. Added profiles.patientsSeenAt/applicationsSeenAt (mirroring the
existing bookingsSeenAt/goalsSeenAt pattern) and profiles.lastKnownSignalAt
(there was no "when did this become urgent" timestamp at all) via one
generic mark-seen route instead of a 4th near-identical file.

Admin mobile (AdminBottomNav): replaced the fragile horizontal-scrolling
pill strip (flagged in its own code comment as tracking <th> order by hand)
with a bottom tab bar + "More" sheet, matching the portal's own BottomNav —
a clinician who is also a patient (the existing role-switch) shouldn't
relearn navigation switching sides.

Marketing mega menu (components/sections/Nav.tsx): was CSS :hover-only, no
keyboard access, no aria-expanded, unusable on a tablet or hybrid laptop.
Now click/focus-driven with proper button semantics, Escape + click-outside
(via the new shared useClickOutside hook — also used by the notification
bell and UserDropdown, its 3rd use). Extracted NavAuthActions to fix the
"future auth-state change needs editing two places" risk the desktop/mobile
duplication already had.

Marketing footer: was a logo and one copyright line, no links at all — now a
real sitemap footer (explore/account columns, address, emergency contacts).
EMERGENCY_CONTACTS existed in config but was wired into no authed screen
either; added to UserDropdown too.

New/changed columns: notifications (new table), profiles.patientsSeenAt,
profiles.applicationsSeenAt, profiles.lastKnownSignalAt — all additive,
drizzle/0015_loving_umar.sql.

pnpm verify (1299 tests, 0 lint errors) and pnpm build both green.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 20:19:48 +00:00
GandClaude Sonnet 5 28107ba62a refactor(portal): shared page-header + dark-banner primitives, sharper type scale, split two god-files (#60)
UI/UX pass toward the SpaceX.ai reference (extreme type-scale contrast,
confident whitespace, high-contrast minimal chrome) while keeping the
existing Cormorant/teal/off-white brand character:

- .pageTitle sized up (2.2rem -> 2.6rem) with tighter line-height and
  letter-spacing; micro-labels (.pageEyebrow, .breadcrumb) tracked wider
  for sharper contrast against it.
- .btnSecondary's border strengthened from --border (a pale beige, barely
  visible until hover) to --ink2 — a ghost button needs an edge the eye
  registers.

Code-debt fixes (audited first, not guessed at):

- New PortalPageHeader component replaces ~11 hand-rolled title/subtitle/
  action blocks across every portal page. Two of them (goals, documents)
  were duplicating the block twice in the same file for their error vs.
  loaded state; goals' error-state title had also silently dropped the
  teal-italic-emphasis convention every other page uses. Both pages now
  render the header once, unconditionally.
- New shared darkBanner primitive family in shared.module.css consolidates
  dashboard's heroCard and assessments' savedBanner — two independent
  definitions of the same ink-card-with-eyebrow-title-body-links idea that
  had drifted (2rem vs 1.75rem/2rem padding, 1.8rem vs 1.6rem title). Also
  fixes a real contrast bug picked up in the merge: dashboard's link used
  --teal (3.50:1 on dark, below AA) instead of --teal-on-dark (5.01:1).
- New --gradient-ink token kills a hardcoded gradient literal duplicated
  identically in portal.module.css's sidebar and profile's hero card.
- dashboard/page.tsx imported portal.module.css as `shared`, colliding
  conceptually with the real app/shared.module.css one directory up while
  dashboard.module.css was `styles` — renamed to `portalStyles`.
- bookings/page.tsx (636 lines) split into ClinicianPicker, BookingHistoryList,
  and RequestBookingForm — the slot-picker/reschedule state machine (the
  riskiest part to move) stays in the page.
- ProfileForm.tsx (416 lines) split into PersonalFields, ClinicalContextFields,
  LifestyleFields and EmailPreferencesFields — pure renderers over the
  parent's single `form` state and `set()` helper, so there's still exactly
  one source of truth and one submit.

pnpm verify (1266 tests) and pnpm build both green.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 09:34:30 +00:00
GandClaude Opus 5 aef5071908 feat(bookings): a doctor who can close intake, and an assistant that can join a patient's own thread (#56)
Two real gaps, both already half-built.

DOCTOR CHOICE ALREADY EXISTED — CareTeamCard on the profile page, and
/api/care-team already let a patient pick without an admin round trip. What
was missing was the other half of that sentence: the doctor's own say. A
clinician could not signal "I am full right now", so the only way to protect
a calendar from new patients was for Manuel to manually turn people away.

profiles.acceptingPatients is self-service — a clinician sets their own,
nobody sets it for them, and there is no admin override route. Enforcement is
ONE function, canPatientChooseClinician(), called at both places a patient
actually chooses a doctor: adding them to the care team, and booking a first
slot with them. Two different doors, one rule, so "not accepting" means the
same thing at both.

The rule is deliberately narrow: closing intake protects a calendar from NEW
patients, and must never look like a doctor dropping someone mid-treatment.
An existing relationship — care-team membership, or ANY prior booking, even
one still pending — always continues. A dual-role clinician can always choose
themselves. A closed clinician is never hidden from the roster; hiding a
person reads as the clinic disowning them, and an existing patient must still
be able to find their own doctor in the list. Staff booking on a patient's
behalf may override — the clinic picking up the phone is the exception being
made, not a patient finding a workaround.

Surfaced everywhere the roster already renders: a "Not accepting new
patients" badge in warn tone (never danger — this is a normal practice state,
not a fault) in the care-team picker and the booking picker, the Choose
button disabled with the server's own reason as its tooltip, and the Confirm
button on a closed doctor's slot honestly relabelled rather than left to fail
after the fact.

THE AI ASSISTANT ALREADY EXISTED, on one side. #53 wired threadkit's model
seam into thread conversations — consent-gated, participant-visibility-scoped,
prompted to defer every clinical question — and put an "Ask assistant" button
on the ADMIN thread view. The API route was already generic (requireSession,
any participant may call it); only the patient's own thread page never grew
the button. "They all can brainstorm solutions together" needed the same
control on both sides of the same thread, not a new capability.

Mirrors the admin handler exactly: on demand only, posts into the shared
thread so the clinician sees precisely what the patient saw, and turns the
451 legal-gate response into an actionable note ("turn on AI in your privacy
settings") rather than a dead button.

Also: two definitions of "the clinician roster" existed (care-team.ts and
scheduling-data.ts) for different reasons — one needs email for availability
rules and orders by account age, the other doesn't. Not merged; both note the
duplication and the rule that would trigger unifying them (a third caller).
The checkbox-toggle CSS pattern DID have two definitions with no reason
(portal-only, needed on admin too) — moved to shared.module.css, both sides
compose from it now.

+19 tests. 1264 passing; build green. Migration 0011 is additive-only, one
boolean column.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 22:34:31 +00:00
GandClaude Opus 5 9b83539eab feat(clinical): a lab result you can watch move (#36)
A blood test could only enter this system as an uploaded PDF. That meant the
single most valuable thing a clinician does — watch a number move — was
invisible to the software. Ferritin from 18 to 62 looked exactly like two files
in a list.

Measured values are now first-class: typed, unitful, dated to when the sample
was TAKEN rather than typed, and comparable to a published reference interval.
39 markers, in the SI units Swiss laboratories report, from the blood pressure
and resting heart rate that stimulant treatment turns on to ApoB, hs-CRP,
ferritin, vitamin D and the omega-3 index.

Three judgements the software now makes, and the reasoning behind each:

REFERENCE INTERVAL IS NOT A TARGET, AND NEITHER IS A DIAGNOSIS. `ref` is where
most healthy adults sit; `optimal` is a narrower, guideline-backed goal, kept
separate and rendered separately. Presenting a target as a normal range would
mark healthy people abnormal at scale. Every interval states its source, and CI
fails if one does not — an interval printed beside a patient's own result is a
medical claim, and an unsourced one is an unsourced medical claim.

SEX CHANGES THE INTERVAL WHERE IT ACTUALLY CHANGES IT. Ferritin 20 µg/L is
unremarkable against the male interval and worth a conversation against the
female one. profiles.biological_sex is recorded for that one purpose, asked with
a label that says so, and when it is absent the range says it was not tailored
rather than guessing. Testosterone, whose intervals do not overlap at all,
declines to rate rather than merge them.

DOWN IS NOT ALWAYS BETTER. A TSH falling from 8 to 5 is a patient improving; one
falling from 2 to 0.2 is a patient getting worse. Markers judged by distance
from the interval are computed that way, and movement smaller than the assay's
own noise reads as "steady" instead of an arrow that means nothing.

Alerts stay rare on purpose: only where a recognised action threshold exists
(hypertensive crisis, resting HR outside 40–120, eGFR <30, ALT >3× ULN). A
signal that fires on ordinary findings is one nobody reads.

Access is one definition, not one per surface: patient, admin, or a clinician on
the care team. Anything else answers 404, never 403 — a 403 would confirm which
people are patients at a psychiatric clinic. A patient records their own vitals;
laboratory results enter under a clinician, so the record always says who
vouched for a number. Enforced in the API, because a form is a suggestion and an
API is the actual door.

Gates, all mutation-tested (a gate that has never failed is decoration):
  • interval with no source, optimal wider than normal, alert firing inside the
    reference interval, one-sided sex interval — 8 defects injected, 8 caught
  • profile-discipline: a schema field absent from a form. This exact defect
    (zod field never reaching the form, silently unsaved) has hit sibling repos
    three times; fixing it a fourth was not the job — ending the class was.

+69 tests, 1058 passing.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 08:49:18 +00:00
GandClaude Fable 5 2b10a18392 fix(ux): portal shell survives assessment, dual-role switching, tabbed patient record (#26)
Four coherence fixes from George's walkthrough:

- /assessment no longer hijacks the viewport: the instrument renders
  embedded inside the portal shell (sidebar + header stay visible)
  instead of mounting the marketing full-screen overlay on top of it.
- Dual-role switching is first-class: 'Clinician area →' in the portal
  sidebar (admins only), '← Patient portal' in the admin sidebar, and
  the user dropdown offers the OTHER side instead of the one you're in.
- Admins can actually reach the patient portal again: the middleware
  rule bouncing /dashboard → /admin/patients predated dual-role care
  and made the portal unreachable for Manuel and George. Post-login
  'clinicians land in admin' now lives in the login page, where an
  explicit returnTo still wins.
- Admin patient record is tabbed (Overview / Clinical / Activity /
  Edit profile) instead of ~12 stacked cards; tab state survives
  refresh via URL hash. Admin header gains the same breadcrumb the
  portal has; admin messages list unread threads first.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 20:31:55 +00:00
GandClaude Fable 5 5f3c21e5d1 feat(clinic): multi-doctor care, AI everywhere with legal warning labels, GDPR surface (#24)
One shot, per George's directives: dual roles, mutual care, per-clinician
booking, AI as a first-class feature — and where regulation would have
stopped a feature, it runs anyway with the law rendered as a warning at
the moment of use, never as a silent wall.

Roles & care:
- users.isClinician marks doctors; role stays the ACCESS level. Dual
  roles by design: a clinician can be another clinician's patient
  (care_team table, symmetric pairs). Patient lists include anyone
  treated in care_team, so dual-role users appear.
- Roles are now DB-owned: resolveRole is promote-only (ADMIN_EMAILS
  bootstraps/recovers admin, never demotes) — login used to silently
  strip DB-granted admin, which cost an hour of "why am I a patient
  again".
- Per-clinician booking: bookings.clinicianId, unique slot index becomes
  (clinician_id, scheduled_at), availability rules per clinician email
  in lib/config/scheduling.ts, clinician picker pills in the slot UI,
  clinician named in confirmations/emails/admin views.

AI (lib/ai, OpenAI-compatible, env-configured):
- Patient "AI insight" on the dashboard; clinician "pre-consultation
  brief" and "differential discussion aid" on the patient page —
  the latter is the feature MDR would call a medical device if it
  diagnosed, so it lawfully hypothesises instead and EVERY output
  renders under the not-a-medical-device warning.
- Consent-at-click: missing GDPR Art. 9 consent doesn't block — the
  warning explains the law and one click records timestamped consent
  and runs. Providers without an EU DPA still run; each output carries
  the Schrems II warning (AI_DPA_SIGNED=true silences it).
- HTTP 451 responses carry blockId into lib/config/regulation.ts.

GDPR surface:
- Profile "Privacy & data" card: AI consent toggle, one-click JSON
  export of ALL user data (Art. 15/20), erasure request opening a
  tracked thread + admin alert (Art. 17 vs the Swiss 10-year retention
  duty — reconciled by a human, not a DELETE).

/regulation — the regulatory ledger: every gated feature with the exact
statutes, who passed them (institutions and named rapporteurs), what
they meant to protect, and who benefits in practice. Config-driven SSOT.

Verified in dev browser end-to-end both roles; 898 tests + build green.
Migration drizzle/0002 (additive + index swap, guard-compatible).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 15:06:41 +00:00
GandClaude Fable 5 daff9e2273 feat(bookings): native conflict-free slot booking — no Calendly, no paid SaaS (#23)
Patients can now book Manuel directly in the portal: pick a free slot,
instantly confirmed, double-booking structurally impossible. Fully
open-source and self-hosted — the dormant Calendly rail is removed.

- lib/config/scheduling.ts — SSOT for availability: weekly working
  windows (clinic wall time), slot length, buffer, lead time, horizon,
  per-day cap. Changing Manuel's hours = editing this file only.
- lib/domain/scheduling.ts — pure, injectable slot engine; timezone-
  correct via CLINIC_TIMEZONE (two-pass wall-time→UTC conversion, DST
  fall-back day-dedupe). 9 unit tests incl. CET/CEST regimes.
- bookings.scheduled_at + partial unique index on active bookings —
  the race between two patients picking the same slot is settled by the
  database, not application logic (23505 → 409 slot_taken). Additive
  migration drizzle/0001, auto-applied on deploy.
- GET /api/bookings/slots + slot path on POST /api/bookings: engine
  re-check → confirmed insert → patient confirmation + admin
  notification emails with the exact Zürich time.
- Bookings page: day tabs + slot grid picker (design-system native,
  44px touch targets), booked slot vanishes from the feed, 409 refreshes
  the list with a friendly message; manual request flow stays as
  fallback. Admin bookings + patient card show exact scheduled times.
- Calendly fully removed: webhook route + signature lib + tests,
  CALENDLY_URL config, banner. External calendar free/busy (CalDAV /
  Google) plugs into the engine's busy-interval input later.
- shared.module.css: mainWrap min-width:0 — first nowrap scroll row
  exposed the classic grid-track blowout on mobile.

Verified in-browser at 1280px and 390px: slot pick → confirm → banner →
list row; slot disappears; same-instant rebook returns 409; admin sees
"Mon 17 Aug, 09:45" under Confirmed; zero mobile overflow after fix.
pnpm verify green (886 tests) + production build green.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 13:42:55 +00:00
GandClaude Fable 5 1fd5e016ed refactor(design): one shared visual SSOT for portal + admin, config-driven nav (#22)
An audit found ~160 duplicated CSS rules across 11 module files: 8 re-
implementations of the card surface, 11 primary-button variants, 7
progress bars at 4 heights, the message thread byte-copied between
portal and admin, and eyebrow labels at 5 letter-spacings. Plus one real
bug: .booking-status-pending referenced --warn-12, which was never
defined — the badge background silently rendered transparent.

Now:

- app/shared.module.css — SSOT for every primitive portal and admin
  share: shell, page header, cards + variants, buttons, pills, Cormorant
  stat scale, progress bars, empty states, form basics, message thread,
  doc lists, error boundary. portal.module.css and admin.module.css
  re-export via cross-file composes (the forms.module.css precedent);
  page modules keep deltas only. Net -195 lines with the new layer
  included; every duplicated geometry now has exactly one definition.
- Design uplift riding on the shared layer: grouped sidebar with
  eyebrow labels + gradient, teal wash under a blurred sticky header,
  serif stat numerals on one scale, uniform tracked-uppercase buttons,
  one pill geometry, message bubbles as "mine = teal accent right,
  other = neutral left" on both portal and admin.
- Nav structure is config: PORTAL_NAV_GROUPS / PORTAL_BOTTOM_NAV /
  PORTAL_ROUTE_SHORT_LABELS in lib/config/routes.ts — PortalNav renders
  both navs from it; bottom-bar labels no longer hardcode copies.
- Tokens: --warn-12 defined (pending-badge bug), --shadow-xs,
  --z-sticky; raw z-indexes replaced with scale vars; the last inline
  scoreColor() style replaced by scoreClass + currentColor.
- design-discipline test: new globals.css self-check so an undefined
  var() referenced by a utility class can never ship silently again.

Verified in-browser at 1280px and 390px: all 8 portal pages, message
thread both roles, admin patients + thread; zero horizontal overflow on
mobile. pnpm verify green (905 tests) + production build green.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 12:21:02 +00:00