Commit Graph
214 Commits
Author SHA1 Message Date
CatoandClaude Opus 5 614722b817 refactor(documents): one upload, whoever is uploading
A patient uploads their own lab results; a clinician uploads a report onto a
patient's record. Two forms, two skins — and two copies of the same upload: the
size pre-check, the FormData, the `data.success` handling, the "Uploaded ✓"
that fades after SAVED_FEEDBACK_MS, the reset of the file input, and a long
`accept=".pdf,.png,…"` literal typed out twice.

The pre-check is what made this worth doing. Refusing a file over
DOCUMENT_MAX_FILE_SIZE_MB *before* sending it is what stops a patient on a
phone pushing 40 MB up a mobile connection to be told no; a stale copy of that
rule would be invisible until someone's upload hung. The server enforces the
same limit — the client check is the courtesy, not the gate.

lib/hooks/useDocumentUpload.ts now owns all of it, and `patientId` is the whole
difference between the callers: the patient form omits it and the server files
the document against the signed-in user, which is why a patient cannot upload
onto someone else's record by editing a form. The portal's `router.refresh()`
rides along as `onUploaded`, since only its list is server-rendered.

DOCUMENT_ACCEPT moves to lib/config/portal.ts beside the other DOCUMENT_*
constants — it is configuration, not hook state.

Both forms keep their own markup, wording and placeholders; nothing rendered or
requested changes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
2026-09-15 11:52:00 +02:00
CatoandClaude Opus 5 6746d490a9 refactor(messages): one thread hook for both sides of the conversation
The patient's thread view and the clinician's thread view are the same
conversation from opposite chairs, and each carried its own copy of the same
sixty lines: fetch the thread, poll it while the tab is visible, scroll to the
newest message, post a reply, clear the box, say "Failed to send" the same way.

That is behaviour, not markup, and behaviour that is written twice drifts. If
the poll interval or the failed-send handling changed on one side only, a
clinician and a patient would disagree about whether a message had been
delivered — in a clinical conversation, on a medical platform.

/api/messages/[threadId] is already ONE endpoint for both: the server decides
who "you" are and marks each message `mine`. So the hook does not know, and
does not need to know, which side is asking — it takes the thread type as a
parameter and leaves the rest alone.

What stays per-page is what genuinely differs: the markup, the back link, the
wording ("Type a message…" vs "Reply to patient…"), the participants line the
patient sees, and the patient header the clinician sees. The portal's Retry
button now calls the hook's `retry`, which clears the failed state first so a
second failure is visible rather than silent.

No change to what either side renders or to any request made.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
2026-09-15 11:46:29 +02:00
CatoandClaude Opus 5 4802fe02df chore(lint): hold warnings at zero and ban stray console.log
Three small guards, one theme: a rule the repo already follows should be
enforced rather than remembered.

- `pnpm run lint` now runs with `--max-warnings 0`, so a warning fails the
  build instead of accumulating. The one outstanding warning is fixed first:
  /api/calendar/subscribe took a `Request` it deliberately never reads (the
  whole point of that route is that nothing on the request may decide where a
  calendar token is sent), so the parameter is gone and the comment says why.
- ESLint `no-console`, allowing `warn` and `error` — those are how a degraded
  state reaches the systemd journal on the box. The two existing `console.log`
  calls are genuine operator output (email provider unconfigured; orphaned
  files deleted) and move to `console.warn`, which is where an operator looks.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
2026-09-15 11:30:47 +02:00
CatoandClaude Fable 5.1 f1c60c61e8 chore: rename FleetCrown to Loki (#104)
The product was renamed on 2026-09-14: bitbaum/loki, loki.orangecat.ch,
LOKI_* env keys, loki-* units. This repo referenced the old name in
6 files changed, 12 insertions(+), 12 deletions(-).
Email addresses at the old sending domain stay until the new domain is
verified in Resend.


Claude-Session: https://claude.ai/code/session_016YJVAanfj8keVSXyZnTemh

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 16:26:31 -07:00
CatoandClaude Opus 5 4efbb6429b fix(ai): report the model that ANSWERED, and correct an overstated comment I wrote (#99)
Two corrections, both mine.

1. THE PROBE NAMED THE CONFIGURATION, NOT THE RESPONDER. It reported
   `process.env.AI_MODEL` as `servedBy`, so with the comma-separated list
   this repo now supports it printed
   "openai/gpt-oss-120b,openai/gpt-oss-20b" — the setting, not the model
   that answered. That is a claim about something never observed, in the
   one route whose whole job is to observe.

   aiChat now returns `model` (from complete()'s resolved link) and the
   probe reports that. It matters beyond tidiness: when the first id rots
   the chain falls to the second, and "which one served" is exactly the
   fact you want at that moment.

2. THE DOC COMMENT OVERSTATED THE LAW. It said pointing patient data at
   the fleet's freeChain() "would be a data protection breach".
   lib/config/regulation.ts is the authority and it says otherwise: the
   `cloud-ai-processing` block is GATED, not blocked. Health data is GDPR
   Art. 9 and Swiss Criminal Code Art. 321 — the strictest rules this
   product touches — and the lawful path through them is the one this app
   already implements: explicit, timestamped, withdrawable per-patient
   consent (the Art. 49(1)(a) derogation) plus a warning on every output
   naming the line the data crossed.

   So the endpoint is a DEPLOYMENT decision, taken by whoever runs the
   clinic and answers for it. freeChain() is still not used here — not
   because it is unlawful, but because it would silently override that
   decision with a fleet-wide default the operator never made.

The distinction is not academic: stated as a breach, the feature stays
dark forever waiting for a provider nobody is procuring. Stated
correctly, it is a choice the operator can make today with consent and a
warning — which is what the ledger's house rule ("build it anyway,
disable it at the exact moment it would run, and say which law did it")
was written for.

verify green — lint, typecheck, 1340 tests.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 12:17:35 -07:00
CatoandClaude Opus 5 eabd50ae30 feat(health): /api/health/ai — prove the provider answers, without touching patient data (#97)
Every AI route here is behind a session AND a patient-consent gate: the
insight route, both admin briefs, the thread assistant. So "does the
provider answer?" could only be checked by signing in and running a real
analysis over a real patient's record. That is a bad way to test a
deploy, and it meant the answer was usually "nobody knows".

  GET /api/health/ai            free.
  GET /api/health/ai?probe=1    a real call. 200 or 503. Needs the secret.

THE PROBE CARRIES NO PATIENT DATA, and that matters more here than
anywhere else in the fleet. It asks a fixed, meaningless question about
the colour of the sky — no digest, no profile, no identifiers. It
exercises the transport and the credentials, which is all a liveness
check ever needs, and it is safe to run unattended on a schedule
precisely because there is nothing personal in it. A test asserts the
request body contains none of patient/digest/checkin/assessment/goal/
medication.

IT REACHES THE OPERATOR'S ENDPOINT, not a fleet default. `ask` (ai-kit
0.15.0) calls `aiChat`, so the probe goes to whatever AI_BASE_URL names —
the endpoint chosen against lib/config/regulation.ts for EU/CH residency.
A probe built on ai-kit's freeChain() would talk to Groq and OpenRouter,
which is exactly what this app must not do. A test pins that every
request went to the configured host.

"Not configured" and "the vendor refused" are reported differently: they
want different fixes, and collapsing them sends someone to check a key
that is fine.

ROUTE-AUTH INVARIANT: app/api/route-auth-invariant.test.ts caught this
route immediately — it sits under the public /api/health prefix and
imports no guard from lib/auth/guards. It authenticates itself with
AI_PROBE_SECRET (constant-time compare, inside ai-kit), because its
callers are uptime monitors and deploy scripts, which have no user to be.
Added to SELF_AUTHENTICATING with that reasoning, as that list demands.

verify green — lint, typecheck, 1340 tests.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 08:30:11 -07:00
CatoandClaude Opus 5 fdc4519f97 refactor(ai): the fleet engine owns the request; the operator still owns the provider (#94)
aiChat's fetch had no timeout at all, so a provider that accepted the
connection and never answered held a clinician's request open
indefinitely. It also caught 429 and reported "AI provider error (429)",
having read the body, logged it, and thrown it away — the three kinds of
429 share a status code and want opposite responses, and only that body
tells them apart.

complete() (ai-kit 0.9.0) brings a per-link deadline, the 429 taxonomy,
and every link's failure in the error rather than only the last. The
empty-200 check this file already had is now the engine's; it stays.

WHAT DELIBERATELY DID NOT CHANGE: where the data goes. The fleet's
freeChain() is Groq then OpenRouter — both US-hosted, neither under a
DPA with this clinic — so adopting the shared engine must not touch
provider selection. AI_BASE_URL/AI_API_KEY/AI_MODEL remain the only
endpoint, chosen by the operator against lib/config/regulation.ts.

A test asserts every request goes to the configured host. If it ever
fails, that is a data protection breach, not a test that needs updating.

AI_MODEL now accepts a comma-separated list, so a rotted model id has
somewhere to fall — every entry served by the SAME endpoint, so a longer
list changes nothing about residency.

The chain is built PER CALL, not at module scope: Next evaluates
module-level code during the build, where these vars are absent, and a
chain frozen there would stay permanently empty on a deployment whose
configuration is fine. Tested by loading the module with nothing set and
configuring afterwards.

Verified by mutation: dropping the second model turns exactly the test
that names it red. verify green — lint, typecheck, 1331 tests.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 22:28:09 +00:00
ab2c2b0397 refactor(email): migrate transport to @bitbaum/mail-kit (#91)
Replace the bespoke Resend-SDK transport in lib/email/index.ts with the
fleet's shared @bitbaum/mail-kit. The app keeps its public seam
(sendEmail/isEmailConfigured/SendResult) and clinic defaults (reply-to
clinic inbox, DEFAULT_FROM_EMAIL fallback); the sandbox-sender and
placeholder-key guards now live in mail-kit. Email-queue cron sends pass
an idempotency key so a retried run cannot double-send. Removes the
resend dependency.


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-05 10:08:09 +00:00
c84bf110e9 feat(schema): the practice is a row, seeded from COMPANY and asserted equal (#89)
`COMPANY` is a const, and 0 of 24 tables carry an org column — so "the clinic"
is a literal you must fork, not a value you can vary. That is the same shape
this repo already corrected twice one level down: `COMPANY.clinicianName` and
the hand-authored per-email scheduling map both stopped being true the moment
there were two of the thing they named.

Adds `organizations`, seeded with this deployment's practice (migration 0016),
and `getOrganization()` so reading the practice is a function call rather than
a module constant. The ~109 existing `COMPANY.x` reads are correct for a
single-practice deployment and are deliberately untouched: surfaces convert
one at a time when a second practice arrives. That is the difference between
a later refactor and a later rewrite, which is the whole point.

`COMPANY` stays the source of the seed rather than the reverse, because the
manifest, OG image and sitemap render at build time with no database — a
clinic whose name exists only in a row cannot render its own favicon.

Two expressions of one fact is the arrangement that rots, and this repo has an
instance that did: `--muted` was darkened for WCAG AA on 2026-04-15 and
`COLOR_MUTED` in lib/config/theme.ts only caught up on 2026-04-28, shipping
the contrast-failing grey in every OG image, manifest and email for 13 days.
That file still says "update both manually" and still has no test. This one
has one, and it needs no database — the seed is parsed out of the migration.

Proved by mutation, not by passing: a drifted value fails the matching field,
and deleting `ON CONFLICT` fails the idempotency assertion. The first draft of
that second case reported "no tests" instead, because the parser was keyed to
the clause it was testing — a gate whose breakage looks like silence is not a
gate, so it now terminates on the statement's own semicolon.

No tenancy column, by decision: separate database per deployment cannot leak
between practices, whereas `org_id` on 24 tables makes every WHERE clause
load-bearing for confidentiality, and user-isolation.test.ts guards patient
isolation, not practice isolation. Recorded in CLAUDE.md.

pnpm verify: 88 files, 1321 tests, green.


Claude-Session: https://claude.ai/code/session_01G2LBioUzJP4oBL9LeH9qAe

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-05 08:33:45 +00:00
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 Opus 5 721c30a177 fix(cron): say which thing is actually broken (#82)
/api/cron/emails returned {"error":"Database unavailable"} while the database
was fine — psql connects with the app's own DATABASE_URL and the schema has 25
tables. The route hardcoded one of the workflow's two possible errors, so an
email-configuration failure was reported as a database failure.

The log line beside it made the same mistake in the other direction: it said
"RESEND_API_KEY not configured" while the key was present, 36 characters and
correctly prefixed re_. isEmailConfigured() is false for TWO reasons, and the
second one — a sandbox sender, which is exactly the case the guard was written
for — announced the first.

Both now name the reason that applies. The guard itself is correct and stays:
refusing to mark a queue sent when the sender reaches nobody is the whole point
of it.

The underlying condition is unchanged and is an operator decision: RESEND_FROM
is a sandbox address, so no patient email can be delivered until a verified
domain is set.


Claude-Session: https://claude.ai/code/session_01UvjGNAS9CMfEGNW26tUR4P

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 09:40:49 +02:00
GandClaude Fable 5 83b87fd7aa feat(messages): consent-at-click for the assistant, one shared AskAssistant component (#66)
The 451 gate now says whose consent is missing (consentIsYours, decided
server-side — only the server knows whose consent it checked). The patient
gets an 'I consent — ask anyway' button; a clinician gets honest copy
(no_patient_consent) instead of a button that would record the wrong
person's consent and look broken.

Third call site of the ask-AI-handle-451 pattern → one shared component,
rendered outside the compose form so Enter never summons the assistant.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 12:30:16 +00:00
GandClaude Sonnet 5 0cd2d59723 fix(admin): clinician onboarding is owner-only now, and /admin/profile is two screens instead of five stacked cards (#65)
George's report, verbatim: "there should be a way to apply as a clinician.
doctors should not see the applications in their tools. registration as a
clinician should not be public" plus a pasted dump of the calendar-connect
copy calling it "too complicated," and the admin dashboard overall "awful."

Investigated before changing anything, because "grant clinician access" is
security-sensitive:

- The public "apply to become a clinician" flow (ClinicianApplicationCard on
  every patient's profile page) was fully open — any registrant could submit
  a request, no allowlist, no invite. That's the literal thing George said
  shouldn't be public.
- Approval never actually worked end to end: approveApplication set
  isClinician=true but never granted role=admin, and /admin/* is gated on
  role=admin only. An approved applicant got booking/profile visibility but
  had NO route to actually manage their own hours, bio, or calendar sync —
  the feature was half-built.
- I considered fixing that by widening /admin/* to any isClinician account.
  Investigated first and stopped: /admin/patients, /admin/patients/[id],
  and app/api/bookings GET are ALL globally scoped today — any admin session
  sees every patient's full clinical record and every clinician's bookings,
  with zero per-clinician filtering (only /admin/messages is properly
  participant-scoped, via threadkit). Widening access without building real
  care_team-based scoping across those three surfaces first would hand a
  newly-onboarded clinician read access to every other clinician's patients'
  clinical notes — a privacy bug, not a UI nit. NOT doing that in this pass;
  it's a separate, larger, security-critical project of its own.

What shipped instead, scoped to what's safe and concretely asked for:

- Removed the public self-apply flow entirely (ClinicianApplicationCard,
  the public /api/clinician-applications submit route, the pending/approve/
  decline review ceremony). Replaced with lib/domain/clinicians.ts: an owner
  adds a clinician directly by email (grantClinicianByEmail) or removes one
  (revokeClinicianStatus) — no public registration path exists any more.
  Reuses the existing clinician_applications table as an audit row (who
  granted it, when) rather than adding a new table for the same fact.
- New owner-only page at the same /admin/applications path, relabeled
  "Clinicians": search-free, just an email field and a roster with Remove.
  Moved out of the "Patients" nav group into "Practice" (alongside Reports)
  — deliberately separated from the day-to-day clinical nav a working
  clinician lives in, since who is staff is an owner decision, not part of
  the patient pipeline. Dropped its nav badge: there's no pending queue
  left to signal.
- Simplified the calendar-connect copy on /admin/profile: trimmed both
  paragraphs, and collapsed the three-provider "Where to find it" block into
  a closed-by-default <details> disclosure instead of always-visible text.
- Split /admin/profile from five stacked independent cards into two tabs
  (Profile & hours / Calendar sync) via the existing SectionTabs component
  (already used on the patient detail page) — added an ariaLabel prop to it
  since it's now used in a second context, rather than hardcoding a label
  that only made sense for the first caller.

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

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 21:10:07 +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 0e04ec25e6 fix(admin): patient-facing copy shown to clinicians, a booking with no visible signal, and two real gaps in the patient record (#63)
You caught this live: cancelling a patient's appointment from /admin/bookings
showed George (as the clinician) the PATIENT's own late-cancellation copy —
"...if you are unwell or something has happened, cancel anyway and message
your clinician" — telling him to message himself. BookingActions already had
an actorLabel prop that varied the reason-field wording, but the actual
warning banner was one hardcoded string used for both sides. Split into
lateWarningPatient/lateWarningClinic in lib/config/cancellation.ts.

Root-caused the other half of the same report: "he never received a
notification when a patient booked him." An email IS sent on every new
booking (already implemented) — the real gap is that admin's "Bookings" nav
badge only counts status=pending, but a native slot booking is born
status=confirmed and never touches pending. So a real booking landed with
zero visible change anywhere in George's own UI until he happened to open
the page. Mirrored the exact pattern the patient portal already uses for
"new goals" (profiles.goalsSeenAt): added profiles.bookingsSeenAt, an
/api/admin/bookings/mark-seen endpoint that clears it on page visit, and the
nav badge now counts pending+confirmed bookings created since last seen.

Then audited /admin/patients (list + detail) as asked. Two real bugs, not
vague dissatisfaction:

- Date of birth rendered the raw "1989-11-24" string straight from the
  database — every other date on this exact page goes through
  formatDateLong. Fixed, anchored to local midnight (not UTC) the same way
  this file already handles check-in dates, so the displayed day can't
  shift at a timezone boundary.
- PatientBookingsCard's own type declared a `clinician` field that the JSX
  never rendered, and the query feeding it didn't even fetch the relation —
  so an admin looking at any patient's booking history had no way to tell
  which doctor a given appointment was with. Now fetched and shown.
- CareTeamCard's "Remove" and "Add to care team" buttons were the identical
  bold primary style — detaching a clinician and adding one are not the same
  weight of action. Remove is now the secondary/ghost treatment.

Scope note: this pass fixed the concrete bugs an audit surfaced rather than
re-skinning the whole admin patient record to match the portal's SpaceX-
influenced redesign — that's ~9 more components (assessment/messages/goals
cards, notes, programme assignment, booking log, measurements, profile edit)
and a genuinely separate initiative. Said so rather than silently scoping it
down.

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

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 14:05:23 +00:00
GandClaude Sonnet 5 9811bad941 feat(scheduling): real clinician profiles, working hours, calendar sync surfacing, and a clinician-application process (#62)
Three complaints in one message, all rooted in the same gap: nothing about
"who is a clinician and when do they work" was ever real, self-service data.

## The fake availability

lib/config/scheduling.ts hardcoded a per-clinician-email override object.
One entry's own comment called it what it was: "evenings-and-Friday
product-testing window". Every patient booking against it was offered
times a developer had typed into source, not a real schedule.

Replaced with clinician_profiles (new table, additive migration): a
clinician's own bio, title, specialties and working hours, self-service via
a real day x window editor (not a JSON blob) at /admin/profile. The row is
optional per clinician — no row means DEFAULT_AVAILABILITY, the exact
fallback contract the old override map gave an unlisted clinician, now
backed by a database column instead of a source edit. All 5 call sites that
read a clinician's rules (booking, rescheduling, cancellation email,
calendar feed, slot listing) now read the real per-clinician row.

## The calendar-connect feature nobody found

lib/domain/calendar-sync.ts + the clinician_calendars table + a full
connect-a-real-ICS-feed UI (CalendarSubscriptions) already existed and
already worked — verified live: the DB had zero rows, meaning nobody, ever,
had connected a real calendar. It was buried at the top of /admin/bookings
next to two other calendar-shaped cards with similar names. Moved to a
dedicated /admin/profile settings page alongside the new bio/hours editor,
where "your calendar" and "your availability" live together instead of
being three cards stacked above a booking table.

## Clinician profiles, both directions

- Patients can now see a clinician's bio, title, specialties and working
  hours (app/(portal)/care-team/[clinicianId], linked from the Care Team
  card's name) — GET /api/clinicians/[id], a curated view that never
  exposes booking-engine tuning (leadTimeHours, horizonDays, maxPerDay).
- Clinicians already see patient profiles via the existing admin patient
  view — this pass didn't need to add that side.

## Clinician application process

users.isClinician defaults to false for every new account; there was no
path to becoming one except a developer flipping it by hand. New
clinician_applications table: a patient submits a message from their
profile page, an admin approves or declines from /admin/applications
(nav badge shows the pending count). Approval grants isClinician inside a
transaction with marking the application decided, so the two can't
half-apply. Declined applicants see the reviewer's note and may re-apply.

## Also

- Extracted requireClinician() into lib/auth/guards.ts (was duplicated
  locally in accepting-patients/route.ts; this PR added a second real
  need for it) — CLAUDE.md's "notice on the 2nd, extract by the 3rd" rule.
- Caught by clinician-profile.test.ts before it shipped: this Zod version's
  z.record() with an enum/literal key schema validates as an EXHAUSTIVE
  record (every key required), not partial — would have made the weekly-
  hours editor reject any patch that left a day closed, i.e. every real
  patch. Fixed with z.partialRecord().
- reviewed_by on clinician_applications added to schema-discipline's
  RETAINED_AUTHORSHIP (deliberately no onDelete policy) — it's staff-only
  authorship provenance, the same pattern as patient_notes.admin_id.

pnpm verify (1292 tests, up from 1266) and pnpm build both green.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 11:44:32 +00:00
GandClaude Sonnet 5 6504e6d65e feat(portal): a Care Team home, brand rename to Vita, and a blog (#58)
Patients had no dedicated place to see who treats them, switch clinicians,
or jump straight into messaging or booking with a specific doctor — that
lived as a small card buried on the profile page with no message/book
actions. New /care-team page (+ nav tab) centralizes it; the old profile
card is now a one-line link-out so the feature has a single home.

Message and booking pages accept ?to=/?clinicianId= so Care Team's
actions land pre-addressed instead of on whatever the picker defaults to.

Brand renamed VitaReBa -> Vita across all user-facing copy, config and
translations (de/en/fr). Left the live domain (vitareba.orangecat.ch),
the real HIN mailbox (vitareba@hin.ch) and deploy identifiers untouched —
those are infrastructure, not brand text, and renaming them is a separate,
riskier change.

Team roster: removed Jonas Montagna, added George as Chief Engineer.

assessment_results gains an additive assessmentType column (default
'inflection_edge') so a second instrument is a config entry, not a
migration.

New minimal blog (lib/blog/posts.ts SSOT, list + post pages, nav link)
with one post on why the platform is built the way it is.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 10:07:50 +02: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 0e354d4c3c fix(bookings): a booking card that answers "when", and a late rule that is fair (#55)
Five things, all of them the same underlying problem: the booking flow was built
for date-only requests and never revisited when real appointments arrived.

THE CARD BURIED THE ONLY THING ANYONE OPENS IT FOR. It read as one flat
sentence — "Consultation · Mon 17 Aug, 17:00 · George" — so WHEN had the same
weight as the word "Consultation", followed by "Requested 16/08/2026", a date
nobody has ever needed, in a different format, directly under the one that
mattered. It is now when → what and who → where, with the time set in the
display face, and the requested date is gone.

THE DASHBOARD DROPPED THE TIME ENTIRELY. It said "17 August 2026" for a 17:00
consultation, because the card's props were Pick<"status" | "preferredDate"> —
it could not see scheduledAt even when one existed, and no type error was
possible because the field was not in scope. Widening it made the compiler
point at the query, which had never fetched the clinician either.

THE DASHBOARD SHOWED THE WRONG BOOKING. It ordered by createdAt, so a patient
with a consultation on Monday and a vague request typed yesterday was shown the
request. "Your next appointment" now means the next appointment.

THREE DATE FORMATS ON TWO SCREENS. "17 August 2026", "Mon 17 Aug, 17:00" and
"16/08/2026", all describing the same kind of thing. formatAppointment() is now
the one way to write an appointment, and it formats in CLINIC time — the general
date helpers use the runtime's zone, which on the box is UTC, so a late
appointment rendered on the previous day.

"LESS THAN 24H AWAY · CANCELLING NOW IS RECORDED AS LATE" — permanently, under a
confirmed appointment, at a patient who had not asked to cancel anything. Two
separate faults:

  • It was NOISE. The policy belongs where the decision is made: it is already
    beside the confirm button when booking, and in the confirmation step when
    cancelling. A standing warning is just an alarm nobody switched on.
  • It was UNFAIR, and this is the real bug. Slots open 12 hours ahead while the
    notice window is 24, so an appointment booked for tomorrow evening is
    ALREADY inside the window the moment it is created. The patient books it and
    is immediately told cancelling would count against them, having never been
    offered a way to do better. "Late" now also requires that the booking existed
    long enough to have been cancelled in time. A rule that marks someone down
    for a choice the software never gave them is a bug wearing a policy.

MOVING AN APPOINTMENT COULD SILENTLY CHANGE THE DOCTOR. "Move" opened the picker
on whichever clinician it happened to be showing, not the one the appointment is
with — so moving a consultation with George could reassign it to Manuel the
moment a time was picked. It now opens on the right clinician, and says that
changing clinician is something you may do here, which the picker always allowed
and nothing ever mentioned.

+6 tests. 1243 passing; build green.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 18:42:39 +00:00
1968424fcc feat(messages): an assistant that takes part in a thread, on request (#53)
Wires threadkit's model seam to this app's existing provider (lib/ai),
so nothing new is chosen: the operator still picks an EU/CH-hosted,
DPA-covered endpoint via AI_BASE_URL/AI_API_KEY/AI_MODEL.

The assistant is a participant, so it reads through the same visibility
window as everyone else and sees nothing said before it was invited.
First use invites it; visible_from defaults to now.

The prompt is written for the patient even when the clinician asks: in a
shared thread everyone reads every reply, so the audience is the most
vulnerable person in the room, not whoever pressed the button. It defers
all clinical questions, refuses medication changes, and escalates
emergencies rather than counselling.

Consent is the patient's: a clinician pressing the button is not consent
on their behalf. 451 with a regulatory blockId when the gate is closed,
matching /api/ai/insight.

Co-authored-by: Mao Nakamoto <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 15:41:44 +00:00
GandClaude Opus 5 c9acf7276e fix(calendar): the subscribe link pointed at localhost (#48)
Every clinician's calendar subscription link read

    https://localhost:4011/api/calendar/<id>/<token>.ics

Pasted into Google or Apple Calendar it resolves to nothing — on their machine,
silently, and probably days later when they wonder why the clinic calendar is
empty. Found by opening the page in a browser.

The route built the link from `new URL(req.url).origin`. This app sits behind
Caddy, which proxies to 127.0.0.1:4011, so inside the process the request's own
URL is the INTERNAL one. The existing `|| PORTAL_URL` fallback never fired,
because "https://localhost:4011" is a perfectly non-empty string — a fallback
that only triggers on empty cannot catch a wrong-but-present value.

It now uses PORTAL_URL, which is configured, is already the SSOT for every link
in every email, and cannot be set by a request. Deliberately NOT
X-Forwarded-Host: that is attacker-controlled input, and this link carries a
calendar token.

WHY NOTHING SAW IT. It typechecks. It renders. It is a valid URL. No test in
this repo renders a page, and the string is only wrong in an environment no test
runs in. The whole class — "ask the request which host you are on" — is
invisible to every gate here.

So lib/config/public-url.test.ts now bans deriving a user-facing origin from
req.url, the Host header, or X-Forwarded-*, and asserts the configured origins
are https, carry no port, and are not loopback — ":4011 in a link" being the
exact shape of this bug. It reads code with comments stripped, so documenting
why a pattern is banned does not trip the ban. Reintroducing the defect fails
it, verified.

1213 passing.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 13:48:21 +00:00
GandClaude Opus 5 afec888102 fix(portal): one missing icon took down every page in the patient portal (#47)
The whole patient portal has been answering "Something went wrong" since #45.
Dashboard, check-in, messages, bookings, labs — all of it, for every patient.

PortalNav looks up an icon per route:

    const Icon = ROUTE_ICONS[href];
    ...
    <Icon />

ROUTE_ICONS was typed `Record<string, React.ComponentType>`. A Record keyed by
`string` accepts every key, and therefore PROMISES a component for keys it does
not contain. When #45 added /labs to PORTAL_NAV_GROUPS, the lookup returned
undefined, React was handed `<undefined />`, and answered "Element type is
invalid". PortalNav lives in the portal LAYOUT, so a single missing entry took
out every page beneath it at once.

Nothing caught it. tsc was satisfied — the type said any string was fine. The
1205 tests passed, because not one of them renders a component: there is no DOM
test environment in this project at all. The build succeeded, because the
failure only exists at render time. Adding a route to the nav was a one-line
config change that could not fail, right up until it took down the product.

The fix is the type. ROUTE_ICONS is now keyed by PortalRoute — the union of
PORTAL_ROUTES values — so a nav route with no icon is a compile error. Verified
by deleting the labs entry again: tsc now fails where it previously passed.

ROUTE_BADGE_KEYS gets the same treatment as Partial<Record<PortalRoute, …>>.
It is genuinely partial — most routes carry no badge — and saying so in the type
is different from leaving the key loose and hoping.

Also gives /regulation an icon. It has been in PORTAL_ROUTES the whole time and
would have crashed the portal identically the day anyone put it in the nav.

The remaining gap is honest and not closed here: NOTHING in this repo renders a
component, so "does the portal actually load" is not a question the test suite
can answer. That needs a DOM environment and a layout smoke test, and it wants
its own change rather than being bolted onto an outage fix.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 13:29:45 +00:00
GandClaude Opus 5 aafe0a7d41 feat(portal): patients can see their own numbers, and what to do if one frightens them (#45)
Labs and vitals existed only on the clinician's side. A patient could not see a
single measured value about themselves — which makes the whole measurement layer
something done TO them rather than with them, and quietly teaches that their
record is a thing kept from them.

/labs shows them the same rendering their clinician sees: the same intervals,
the same trend arrows, the same words. Deliberately the same component, because
a softened patient view would eventually disagree with the clinical one about
what a number means, and the one place that must never happen is a page showing
someone their own blood results.

They can add their own vitals, and only their own. A home blood-pressure cuff
produces better data than one reading taken in a consulting room by someone who
is nervous — that is real clinical value, not a toy. Laboratory results stay
read-only so the record always says who vouched for a number. The API already
enforced both; this page just renders the result.

EMERGENCY_CONTACTS FINALLY EXISTS SOMEWHERE. It has sat in config since the
regulatory work, rendered on no page at all, which is the same as not having it.
It now appears in two places chosen on purpose: beside a patient's own results,
where a number can frighten someone at eleven at night, and on the messages
page, where a patient in distress is most likely to be sitting. Saying plainly
that nobody is reading that inbox at 2am is not a disclaimer — it is the
difference between waiting for a reply and calling 144.

The same notice states the scope: this platform records and displays, it does
not diagnose, and a value outside an interval is not a diagnosis while one
inside it is not proof of health. That is the honest description of what the
software is, and it is also the thing that keeps a portal page from being
treated as a clinician on call.

Also: a subscribed calendar can correctly find NOTHING, and it looks exactly
like a broken parser. Google's holiday feeds mark every event TRANSP:TRANSPARENT
— holidays are informational and are not meant to block anyone's diary — so
subscribing one and seeing zero busy periods is right. Verified against the real
Swiss holiday feed: 160 KB, every VEVENT transparent, zero intervals; strip the
TRANSP lines from the same bytes and the parser finds them all. The UI now says
so instead of leaving a working subscription looking dead, and the parser
carries the note so nobody "fixes" it by ignoring TRANSP.

1217 passing; build green.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 12:55:02 +00:00
68a7e8c344 feat(messages): participation-based threads, ready for groups and AI (#43)
* feat(messages): participation-based threads, ready for groups and AI

Access to a thread is now membership in thread_participants, resolved by
threadkit. It was a role check plus threads.patient_id, which gave every
admin every patient's thread and returned the whole clinic from an
unfiltered GET — correct only while there was exactly one clinician.

Read state moves to a per-participant high-water mark. The flag on the
message row meant the first person to open a thread cleared the badge for
everyone; invisible with two people, wrong with three.

Messages gain an author actor, so an AI can write without being given a
users row and a login.

The migration is additive and the backfill reproduces today's access
exactly: patient, named clinician, and every current admin, all with
visible_from set to the thread's creation time. Narrowing access in a
migration would have locked the clinic out of live conversations.

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

* chore(db): regenerate migration as 0010 after rebase

main took 0008 and 0009 while this branch was open. The snapshot is
regenerated rather than hand-patched, so it reflects the merged schema
including the booking work, not the schema as it looked before it.

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

---------

Co-authored-by: Mao Nakamoto <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 12:51:06 +00:00
GandClaude Opus 5 3592f814f5 feat(bookings): the clinician's real calendar blocks slots here (#44)
Slot generation only knew about appointments booked inside VitaReBa. Anything
in a clinician's actual life — a school concert, a hospital rota, a conference —
was invisible, so the picker cheerfully offered patients hours their doctor was
already committed to. The first person to find out would have been the patient,
at the door.

A clinician pastes the private "secret address in iCal format" URL their
calendar app already publishes, and their real commitments start blocking slots.
No OAuth application to register, no vendor to depend on, nothing to pay, and it
works identically for Google, Apple, Outlook and Nextcloud.

READ-ONLY BY CONSTRUCTION. Nothing here can write to anyone's calendar.
VitaReBa's own appointments travel the other way, through the .ics invites
already attached to confirmation emails.

ONLY THE TIMES ARE STORED. Not titles, not guests, not descriptions. A
psychiatric clinic should not hold a mirror of its doctors' private lives in
order to avoid double-booking them, and the parser is written so it cannot.

THE DANGEROUS PART IS THE FETCH, and it looks like nothing. "The server fetches
a URL the user typed" is server-side request forgery: the request originates
inside the box, so it reaches the Postgres port, the cloud metadata service and
every other app on the host — none of which the internet can reach. An attacker
need not even see a reply; a calendar that "fails to parse" with 800 events has
already answered. So: https only (webcal is https wearing a hat), every resolved
address must be publicly routable, redirects followed by hand and re-checked at
every hop because a public host is free to redirect to 127.0.0.1, bounded bytes,
bounded time. 32 tests cover the closed side — loopback, all three private
ranges and their off-by-one edges, link-local metadata, CGNAT, IPv6 loopback and
IPv4-mapped IPv6, file:// and gopher://.

Busy time is CACHED, not fetched during slot generation. A network call on every
page load makes the picker slow, and a calendar host that is down would make the
clinic look completely free. A stale cache offers one slot that is taken; no
cache offers every slot that is taken.

Failure is per-calendar and fails SAFE: an unreachable feed keeps its previous
busy times rather than emptying them, because not reaching a calendar is not
evidence its owner is free. The error is recorded and shown, since a feed that
broke last week looks exactly like having no calendar at all.

The parser handles what real calendars actually contain: folded lines, TZID
wall-clock times, floating times (read in the clinic's zone, not UTC — reading
them as UTC frees hours nobody is free), all-day events, RRULE with INTERVAL /
COUNT / UNTIL / BYDAY, EXDATE, and the two properties that legitimately mean
free — TRANSP:TRANSPARENT and STATUS:CANCELLED. Unbounded rules are expanded
only within the horizon; a daily rule with no end is genuinely infinite. One
malformed event never costs the rest of the year.

Where the parser is unsure it errs toward BUSY. The asymmetry is the whole
design: a missed busy hour sends a patient to an empty room, an invented one
costs an unbooked slot.

External busy time is used without the appointment buffer. That buffer is time
the clinic reserves after its own consultations; someone's dentist appointment
already has whatever margin they gave it, and padding it would silently delete
two further bookable slots around every event in their life.

+75 tests. 1217 passing; build green. Migration 0009 is additive-only, two new
tables. Needs a systemd timer for cron/calendar-sync every 15 minutes.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 12:24:09 +00:00
GandClaude Opus 5 7c7ef1cc8d feat(bookings): a patient can get out, and an appointment can move (#42)
Two things were true before this and neither should have been.

A PATIENT COULD NOT CANCEL A BOOKED APPOINTMENT. The self-cancel path accepted
only bookings still in `pending`, and every slot booking is created `confirmed`.
So the moment picking a time started working, everyone who picked one was stuck
with it — with no way out in the product at all. The same gate existed twice, in
the API and again in the button, which is why nobody noticed one of them.

NOTHING COULD BE MOVED, BY ANYBODY. There was no reschedule anywhere. The only
way to change a time was to cancel and rebook, which loses the appointment's
history and sends a patient two contradictory emails.

Both sides can now cancel and move. The rules are one pure function that the
API enforces and the button reads, so a control cannot offer something the
server will refuse.

THE POLICY: 24 hours' notice, and a late cancellation is RECORDED, NEVER
REFUSED. The reasoning is in lib/config/cancellation.ts and worth stating here.
A late fee needs stored card details and turns "I woke up unable to function"
into a bill — at a metabolic-psychiatry practice, the patients most likely to
cancel late are the ones it exists to help. Removing the button inside the
window does not produce attendance, it produces a NO-SHOW: the clinic finds out
at the appointment instead of the night before, and the patient learns the
portal is a thing that traps them. So cancelling is always possible, it says
plainly that it is late and that there is no charge, and the clinician sees it
flagged. A pattern of late cancellations is clinical information, not just an
accounting one.

The window is stated next to the confirm button when booking, not first met
while trying to cancel. A rule you discover at the moment it costs you is
experienced as a trap however reasonable it is.

RESCHEDULING NEEDED A REAL CALENDAR COUNTER. The .ics SEQUENCE was derived from
the booking's status, and moving an appointment does not change its status — so
the patient's calendar would have kept the old time forever and they would have
arrived on the wrong day having done everything right. bookings.revision is now
the counter, bumped on every change, with the old status table kept only as a
floor so nothing already published can appear to go backwards.

Details that matter:
  • Someone else's appointment answers 404, never 403 — a 403 confirms the id
    is real, which is a disclosure about another patient at this kind of clinic.
  • An appointment does not block its own move; the naive re-check treats the
    booking being moved as busy and refuses every reschedule.
  • Cancelling through the admin status button records the same shape as the
    patient's cancel button. One act, one kind of history.
  • Cancellation sends an .ics CANCEL. An email alone leaves a ghost entry that
    still buzzes the patient's phone on the day.
  • lateCancellation is STORED, not derived: it is a judgement made against the
    policy in force at that moment, and re-deriving it against a changed window
    would rewrite whether someone did the right thing two years ago.

+46 tests. 1130 passing; build green. Migration 0008 is additive-only.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 11:48:35 +00:00
GandClaude Opus 5 c6d688d79b fix(admin): patient rows carried every patient's password hash (#41)
GET /api/admin/patients and /api/admin/patients/[id] returned the Drizzle row
verbatim — `db.query.users.findMany(...)` with no `columns:` projection — so
every response carried each patient's bcrypt digest, plus failedLoginAttempts
and lockedUntil.

Confirmed live on prod before fixing: 2/2 rows in the list response and both
detail responses carried a `$2b$12$…` hash.

This is a worse shape than the FleetCrown /api/me case that prompted the sweep.
There the digest was the caller's own. Here an admin console shipped OTHER
people's credential material to a browser, in a clinic app, where those people
are patients. A digest is not a password, but it is the input to an offline
attack that costs the attacker nothing, and it moves the secret from a place
nothing can read it to a place everything can.

lib/db/user-view.ts is now the single answer to what may leave the server:
an ALLOW-list whose halves are exhaustive over the schema, so a new users
column fails the test until it is classified exposed or withheld. A deny-list
can only name what existed when it was written.

failedLoginAttempts and lockedUntil stay exposed deliberately — not secrets,
and an admin helping someone locked out needs to see them.

Negative-tested in both directions, because a gate that cannot fail is not a
gate: dropping `role` from the list fails with "users.role is in NEITHER list";
re-exposing `password` fails with "in BOTH lists" plus the projection and
serialization assertions.

Verified: tsc clean, eslint clean, 1100/1100 tests (8 new).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 10:49:18 +00:00
GandClaude Opus 5 d18c2fe560 fix(bookings): booking answered 400 for the only people using it (#40)
Nothing has ever been booked with a real time on it. Both rows in the
production bookings table are date-only requests from April, and every attempt
to pick a slot in the portal came back 400 "Invalid data".

The route decided which kind of booking it was by looking at WHO was asking:

    if (session.user.role === admin) -> handler that requires a patientId

An admin who picked a time for themselves was routed into the book-for-someone-
else handler, which demands a patientId the slot picker never sends. Both
accounts at this practice are admins, and its clinicians are their own patients
by design — care_team exists for exactly that — so the admin branch swallowed
the ordinary case for everyone who had one.

The rule now: THE BODY SAYS WHAT IS BEING ASKED FOR, THE ROLE SAYS WHAT IS
PERMITTED. A body carrying `slot` is a slot booking whoever sends it. Booking
for someone other than yourself is the only thing role governs, and a patient
who tries it is told nothing about the field existing.

One consequence worth having: an admin can now book a slot FOR a named patient,
which is what taking a booking over the phone looks like. Same code path, same
engine re-check, same unique index — "who it is for" is a parameter, not a
second implementation.

WHY EVERY TEST WAS GREEN. The matrix had a hole exactly where the bug lived:
slot bookings were only tested with a patient session, admin bookings only with
a patientId. Nothing exercised "an admin books their own appointment". A suite
is worst at seeing what nobody wrote down.

My first attempt at the missing tests still passed against the broken code,
because they asserted the response body — and the mocked insert returns a
"confirmed" fixture no matter what the route does. Falling through to the
request handler also answers 201. They now assert the ROW THE ROUTE WROTE:
userId, clinicianId, scheduledAt, status. Reintroducing the defect fails them,
as does removing the permission check, as does writing the booking against the
requester instead of the named patient — all three verified by mutation.

1098 tests passing.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 10:39:02 +00:00
GandClaude Opus 5 909c2b2896 feat(admin): the first screen answers the first question (#39)
/admin redirected to the patient list. A list sorted by a badge answers "how is
everyone" — a fine second question. The first one, at 08:00 on a Tuesday, is
"what needs me", and the product's own stated goal is that Manuel opens the
admin and knows without calling anyone. Most patients are fine; a page listing
all of them buries the four who are not.

Today is that page. Five sections, and the order IS the design:

  Results to review   urgent     a value past a recognised action threshold
  Patients to contact urgent     a critical signal
  Waiting on a reply  attention  a thread the patient wrote last
  Bookings to confirm attention  a request nobody has answered
  Next steps          routine    an attention signal — assessed but not booked

Anything routine placed above something urgent teaches the reader to scroll past
the urgent one, so only two sections are allowed to shout.

Decisions worth stating:

IT INVENTS NO SECOND OPINION. Who is critical is computePatientSignal, the same
function the patient list uses. Two definitions of critical in one product means
the list and the dashboard eventually disagree and the clinician trusts neither.
The only things added are the two questions the signal cannot answer: has a
measured value crossed a line that should not wait, and is a person sitting
there waiting for a reply.

OLDEST FIRST, EVERYWHERE. The newest item is still fresh in mind; the oldest is
the one already forgotten. Sorting newest-first buries exactly the wrong thing.

A STALE VALUE IS NOT AN ALERT. A blood pressure of 186 this week is today's
problem; the same reading from eighteen months ago is history, and shouting it
every morning is how the top of the screen stops being read. Results older than
180 days do not raise anything — if that is still the newest value, what is
needed is a repeat measurement, not an alert.

NOTHING IS TRUNCATED SILENTLY. Sections cap at eight and say how many more
there are. "8 shown" and "8 in total" must not look the same to someone deciding
whether they are done for the day.

AN EMPTY INBOX IS THE GOAL, NOT A BUG, and is designed as such rather than
rendered as a blank page.

Also fixed while here: getAdminUnreadThreadIds selected messages by
role=patient. A clinician who is also somebody's patient has role=admin, so
their messages were dropped from the badge entirely — undercounting exactly the
dual-role people care_team exists to support. It now asks the same question as
getAdminUnreadPatientIds: was the sender this thread's own patient.

+24 tests over the pure builder. 1092 passing.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 10:17:22 +00:00
GandClaude Opus 5 c1997b4675 fix(health): the watchman took the site down (#38)
The privilege check I added yesterday never ran. It threw on every request, and
because a failed check returned 503, a healthy application reported itself dead
in every monitor.

Two mistakes, and the second is the one worth keeping.

THE BUG. Interpolating a JS array into a Drizzle template expands it into a
comma-separated PARAMETER LIST, so `unnest(${names}::text[])` reached Postgres as
`unnest(($1,$2,...)::text[])` — a record cast to an array, rejected with 42846.
It is now a real array constructor with each name bound separately.

WHY IT SHIPPED. I verified the statement by hand in psql, where it was perfectly
valid, and concluded the query worked. A hand-written equivalent is not a test of
the query the client sends; the whole failure lived in the gap between the two.
There is no database in CI, so "run it and see" was not available — but
compiling it was. schema-usable.test.ts now builds the statement through
Drizzle's own PgDialect and asserts what the driver will actually transmit:
names bound as parameters, a real array constructor, the missing-table branch
ahead of the privilege branches, and no table name ever spliced into the text.
Reintroducing the exact defect fails it.

THE SEMANTICS. A definitive negative and an inability to answer are different
faults and must not share a status code:

  tables genuinely unusable  -> the app IS broken       -> 503
  the check itself throwing  -> the app is serving fine -> 200, and say so

Returning 503 for a broken diagnostic takes a working application offline
everywhere and blocks every future deploy on a bug in the watchman rather than a
bug in the product. Health now answers {ok:true, schemaCheck:"failed"} in that
case and logs loudly — a degradation that is visible is not a degradation that
is hidden. The check that actually matters, tables the app cannot use, still
returns 503.

1092 tests passing.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 09:47:19 +00:00
GandClaude Opus 5 6d69dba4c0 fix(health): "database reachable" is not "database usable" (#37)
Yesterday's deploy went green, the health check returned 200, and every request
touching the new measurements table would have failed with permission denied.
The app role had no rights on it at all — no select, no insert, nothing.

Migrations are applied on the box by the postgres superuser, so a table a
migration creates is OWNED by postgres. The application connects as its own
role, which is granted nothing on a table it does not own. The table exists, the
connection works, `select 1` succeeds, and the feature is dead. CI cannot see
any of this: CI has its own database where the test user owns everything.

This is the second time. The first was care_team, and it was fixed by hand, which
is why there was a third table waiting to break the same way. So the fix is
structural, in three parts:

  1. Prod now carries ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA
     public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO vitareba. Tables
     created from here on are granted automatically. Existing tables granted;
     all 19 verified usable.
  2. /api/health now asserts the property instead of assuming it. One catalogue
     query, no patient data read, and the deploy pipeline already waits on this
     endpoint — so losing the privilege turns a deploy red rather than quiet.
     The public body never names a table; a health endpoint that enumerates the
     schema is a free map for anyone who asks. Detail goes to the logs.
  3. The table list is DERIVED from the schema's exports, not written down. A
     hand-kept list goes stale exactly when a table is added, which is the
     moment the check matters. tables.test.ts cross-checks the derived list
     against every pgTable() in schema.ts in both directions, so a table that
     exists but is invisible to the check fails CI.

Verified against the real database, both ways: all 18 tables report clean, an
invented table reports "table missing", and revoking select on measurements
inside a rolled-back transaction reports "no select privilege". Prod privileges
confirmed intact afterwards.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 09:11:34 +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 Opus 5 af912589ac fix(brand): say what the practice says about itself (#35)
Compared our marketing surface against vitareba.com, the practice's own live
site, and fixed everywhere we contradicted it or invented facts about real
people.

Manuel Riegner's title. His site says "MD and General Practitioner"; ours said
"Founder · Surf Your Life", and the German and French translations rendered him
as "Gründerin" and "Fondatrice" — feminine forms, for a person whose own site
writes "Arzt und Facharzt für Allgemeinmedizin" and "Médecin et généraliste".
All three locales now carry his own wording, taken from his own site, rather
than a translation we invented. His name is Riegner; our docs had a different
surname entirely.

The second founder. We published "Dr. Montagna · Metabolic Psychiatrist". The
practice's own team page does not list him at all, and nothing sourceable backs
either the doctorate or the specialty. He is a co-founder per the Swiss
commercial register, so that is what we say — a title we can source, and no
clinical credential we cannot. Asserting a specialty for a real person on a
medical site is not ours to do.

Contact. Patient mail pointed at manuel@surfyourlife.org, the founder's
coaching brand. The practice publishes vitareba@hin.ch — HIN being the Swiss
secure-email network for medical correspondence. Routing clinical mail through
a coaching inbox blurs exactly the line the practice draws in its own words:
"a Swiss-registered medical entity — not a coaching brand wearing medical
clothes." Phone added, founding year corrected to 2024 per the register.

Italian removed. The practice works in EN, DE and FR — its FAQ commits to
consultations in those three. A localised site is a promise of care in that
language; offering Italian sets a patient up to arrive and not be understood.
i18n/routing.test.ts now keeps locales, message files and that promise in step.

EMERGENCY_CONTACTS added to config (144 · 112 · 143), ready for the surfaces
that need it. A platform asking a psychiatric population about mood and stress
every day has to be able to say where to go when the answer is "not safe" — and
that it is not that service.

pnpm verify green: lint, typecheck, 989 tests.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 18:21:45 +00:00
GandClaude Opus 5 c7e5688e00 feat(cron): erase the file, not just the row (#34)
After deleting a probe patient on production, `documents` held 0 rows and the
box still held 2 medical files. delLocal() has existed since the local-storage
migration and was never called from anywhere — there is no delete route, so no
uploaded file has ever been removed under any circumstance.

Erasing a patient removes their document ROWS through the database cascade,
and a cascade cannot call application code. So the record disappears while the
medical file it named stays on disk forever. That is not erasure (GDPR Art. 17),
it is bookkeeping — and it is invisible, because the DB looks correct.

A reconciler is the only thing that can close this: it is the only part that
runs after the database has already decided what no longer exists. Daily at
03:00 it deletes stored files that no document row points at.

Direction is deliberate — it deletes files with no row, never rows with no
file. A row whose file is missing is a restore artefact, already handled at
read time with a 410; deleting that row would destroy the patient's history
instead of a leftover byte.

It also fails CLOSED: if the document read throws, it deletes nothing and
reports failure. An unreachable database returns zero rows, which reads as
"nothing is referenced" — the naive version would wipe every patient document
on the box. That case is the test I care most about in this commit.

pnpm verify green: lint, typecheck, 985 tests.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 13:33:41 +02:00
GandClaude Opus 5 d3ef867471 fix(db): erasure was still blocked — by the message the patient sent (#33)
Correction to the previous commit. It claimed documents.uploaded_by was the
only thing vetoing a patient's deletion. It was only the FIRST veto: Postgres
reports one constraint and stops, so fixing that one revealed the next.

  ERROR: update or delete on table "users" violates foreign key constraint
         "thread_messages_sender_id_users_id_fk"

I had put sender_id in the retained-authorship list, reasoning that a medical
record must keep its author. That reasoning is right for a note, a programme
assignment and a goal — only staff can write those, so they can never block a
patient's own erasure. It is wrong for a message, because a PATIENT is a sender
too. The rule ended up protecting the patient's data from the patient.

sender_id becomes nullable with SET NULL. Erasing a patient still removes their
messages — threads cascade on patient_id, messages on thread_id — so the null
case only arises for a deleted clinician's reply in a thread that survives,
where keeping the text with an unknown author beats deleting a patient's
clinical history. Membership in RETAINED_AUTHORSHIP now requires that only
staff can write the column, which is the property that actually matters.

Both thread views dereferenced msg.sender.role directly. Drizzle still types
the relation as non-null, so the compiler did not catch it — a deleted sender
would have thrown at render. Both now treat an authorless message as staff-side,
which is the only case that can reach a reader.

Verified on production rather than assumed: a throwaway patient that had
checked in, messaged, booked and uploaded a document now deletes cleanly.

pnpm verify green: lint, typecheck, 978 tests.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 11:11:09 +00:00
GandClaude Opus 5 8ccf0a3071 fix(db): a patient who uploaded a document could not be erased (#32)
Found by deleting a throwaway patient on production after exercising the real
paths — check-in, message, booking, document upload. The delete failed:

  ERROR: update or delete on table "users" violates foreign key constraint
         "documents_uploaded_by_users_id_fk" on table "documents"

documents.uploaded_by was the only reference into users with no delete policy,
so Postgres defaulted to NO ACTION and the row became a veto. Everything else
cascaded correctly; this one constraint made GDPR Art. 17 erasure impossible
for any patient who had ever uploaded a file — a right the product offers at
/api/account/deletion-request.

uploaded_by is provenance, not ownership, so it becomes nullable with SET NULL.
That makes both deletions work for the right reason: erasing the PATIENT still
removes the document through the userId cascade, while removing an UPLOADER (a
clinician who leaves) leaves the patient's records intact instead of deleting
them. bookings.clinician_id and threads.clinician_id — already nullable, also
policyless — get the same treatment, so a departing clinician degrades their
bookings to clinic-wide and leaves patient threads to fall back to the clinic.

The four remaining policyless references are deliberate and now say so:
thread_messages.sender_id, patient_notes.admin_id, programme_assignments.
assigned_by and clinical_goals.set_by_admin_id are AUTHORSHIP of clinical
content. Anonymising them on staff departure destroys traceability and
cascading them destroys the patient's history, so the FK is left to refuse —
the correct operation for a departing clinician is to deactivate the account.

lib/db/schema-discipline.test.ts requires every users reference to either
declare a policy or appear in that retained-authorship list with a reason.
Verified the gate actually fails: reintroducing the original constraint makes
two of its three tests go red.

pnpm verify green: lint, typecheck, 978 tests.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 10:45:14 +00:00
GandClaude Opus 5 5d59edf295 fix(prod): email that reaches patients, links that resolve, documents behind auth (#31)
Found by testing the deployed site rather than the test suite. Each of these
was invisible locally and total in production.

1. No patient could receive any email.

RESEND_FROM was "VitaReBa <onboarding@resend.dev>" — Resend's shared sandbox
sender, which delivers ONLY to the provider account owner. Production logs
show every other recipient rejected outright:

  "You can only send testing emails to your own email address ... verify a
   domain at resend.com/domains, and change the `from` address"

So: no welcome mail, no check-in reminder, no message notification, no weekly
digest — and no password reset, which is the only way back into an account.
Prod now sends from the verified fleetcrown.orangecat.ch (delivery confirmed
end-to-end), and isEmailConfigured() treats a sandbox sender in production as
NOT configured, so forgot-password fails loudly with its existing 503 instead
of answering "check your inbox" to a patient who will never get one.

Emails also carry a reply-to now. A clinical email nobody can answer is a
dead end; replies reach the clinic instead of an unmonitored noreply@.

2. Every link inside those emails pointed at a host that does not exist.

PORTAL_URL fell back to https://vitareba.ch, and the deployed env sets no
NEXT_PUBLIC_APP_URL — the domain has no A record and no NS delegation at all.
The dead host was baked into the running build in 41 places. SITE_URL had
already been corrected for exactly this reason; PORTAL_URL had not, so the
reset link was dead even once mail started arriving. Both fallbacks now name
the host that actually serves, and company.test.ts pins the invariants: same
origin, https, and not a host known not to resolve.

3. Patient documents were served to anyone with the URL.

Caddy served UPLOADS_DIR as a plain file_server under /uploads/*, with no
session involved, and the UI linked documents.fileUrl straight into an href.
Any medical document uploaded would have been readable by anyone holding or
guessing the link — forever, and links leak through history, referrers and
forwarded mail. Nothing was exposed only because no document had been
uploaded yet, which makes this the zero-migration moment to close it.

Documents are now read back through GET /api/documents/[id]/file, which
requires a session and answers 404 — never 403 — for a document that is not
yours, because a 403 would confirm the id is real. lib/storage-discipline.test.ts
fails CI if a component ever links the raw storage URL again.

4. Baseline security headers were absent on a health-data portal.

The portal could be framed by any site and leaked full portal URLs through
the Referer header. Adds frame-ancestors/X-Frame-Options, nosniff,
Referrer-Policy, Permissions-Policy and HSTS. Deliberately not a full CSP:
script-src for Next's inline bootstrap needs nonce plumbing, and a broken CSP
silently breaks the app.

pnpm verify green: lint, typecheck, 975 tests. pnpm build clean.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 10:08:02 +00:00
GandClaude Opus 5 ef293be78a fix: name each patient's own clinician, and stop trusting stale sessions (#30)
* fix(bookings): confirm bar only pins once there is something to confirm

At 390px the sticky confirm bar was pinned from the moment the picker
rendered, so an empty, disabled bar parked a white slab over "2 · Pick a
day" — covering the step the patient still had to reach. It now sticks
only after a slot is selected, which is when following the thumb is
actually worth the screen it costs.

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

* fix(clinic): every patient is told their own doctor's name, not one from config

COMPANY.clinicianName was a second source of truth for "who treats this
patient". care_team is the first. The config answer was wrong for every
patient who is not Manuel's — which is the whole point of signing up more
clinicians — and it appeared in 20+ places: every onboarding email, the
dashboard, the check-in page, the profile form, programme phase copy.

Killing the property makes the compiler enumerate every site. Each one now
resolves the real name via clinicianLabelFor(patientId), falling back to a
neutral "your clinician" when nobody treats them yet. Copy that says "your
clinician" is never wrong; copy that names the wrong doctor destroys trust
in a clinical product.

Where the actor is not the primary clinician, it now says who actually
acted: newDocumentEmail names the uploader, programmeAssignedEmail names
the admin who enrolled. Where the actor is unknowable — an unread reply
can come from any care-team member — the copy stays unattributed rather
than guessing.

Also fixed along the way:
- the public Inflection Edge results CTA interpolated an English name into
  German/French/Italian copy; the four message files now carry a localised
  "our clinical team" and the placeholder is gone
- phase descriptions said "you will hear from him"; now "from them"
- /checkin was a client route with no way to reach the database, so it is
  split into a thin server page + CheckinForm

Never-Twice: lib/domain/clinician-discipline.test.ts fails CI if config
regrows a clinician*Name key, or if any shared copy hardcodes a name from
TEAM_MEMBERS. It caught two leaks this sweep had missed (programmes.ts,
next-step.ts).

pnpm verify green: lint, typecheck, 940 tests.

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

* fix(auth): a deleted or demoted account stops working within 5 minutes

JWT sessions are self-contained. The jwt callback only touched the database
at sign-in, so nothing afterwards knew the row it came from had changed:
deleting a user left their session fully working, and revoking an admin left
them admin — both until the cookie happened to expire.

The callback now re-reads the users row when the token is older than
SESSION_REVALIDATE_MS (5 min), and returns null when the row is gone, which
ends the session. Role and email verification are refreshed from the row on
the same pass, so a demotion also takes effect within one interval.

A failed lookup deliberately does NOT end the session: an unreachable
database is not evidence a user was deleted, and treating it that way would
sign the whole clinic out during a blip. The token is returned unstamped so
the check retries on the next request.

The decision logic is a pure function pair in lib/domain/auth.ts rather than
inline in the NextAuth factory, so it is testable: 10 cases cover deletion,
demotion, the promote-only ADMIN_EMAILS recovery path, a backwards clock,
and the database-down path.

Middleware (lib/auth/edge.ts) still reads the token without a database — it
cannot reach one from the Edge runtime. That is only coarse routing; every
data path goes through requireSession()/requireAdmin() in the Node runtime,
which is where this check now runs.

pnpm verify green: lint, typecheck, 950 tests.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 17:16:29 +02:00
GandClaude Opus 5 be52705aa8 feat(clinic): book a named doctor, choose your provider, calendars that actually sync (#27)
Booking, messages and documents all needed the same missing fact — who treats
you — and none of them had a way to learn it. This adds one definition of the
care team and makes every surface read from it.

Choose your provider
- /profile gains a care-team picker: a patient chooses their own clinician
  (previously only an admin could create the link, so a new patient had no way
  to say "this is my doctor"). Self-pairs allowed by design: a dual-role
  clinician can be their own patient and walk the patient path.
- lib/domain/care-team.ts is the SSOT — roster, "who treats me", primary
  clinician — consumed by booking defaults, message recipients and document
  notifications.

Booking
- Slot picker redesigned mobile-first as three explicit steps: who you'd like
  to see (avatar cards, "Your clinician" badge), pick a day (scroll-snap date
  rail with free-slot counts), choose a time (grouped morning/afternoon/
  evening rather than a wall of times). Every control is a >=44px touch target
  and the confirm bar sticks above the mobile nav.
- The default clinician is now the patient's OWN clinician, not whoever sorts
  first. The confirm bar states the real appointment length, timezone and that
  an invite is attached.
- The booking email now also reaches the clinician whose calendar it lands in,
  deduplicated against ADMIN_EMAILS.

Calendars, without a paid SaaS
- Every confirmed booking ships an RFC 5545 invite (.ics) on both emails — one
  tap adds it in Gmail, Apple Mail or Outlook, no integration to configure.
- Each clinician gets a subscribable feed at /api/calendar/<id>/<token>,
  surfaced with copy-paste instructions on /admin/bookings. Cancelled bookings
  are published as CANCELLED so they disappear rather than linger.
- The feed token is an HMAC of the user id (lib/domain/calendar-token.ts): no
  column, no migration, rotatable for everyone by changing the secret. A wrong
  token 404s — a 401 would confirm the id belongs to a real clinician.
- Fixed a bug this would have shipped with: the feed sat behind the middleware
  session gate, and calendar clients send no cookies, so it could never have
  worked in prod. route-auth-invariant.test.ts caught it.

Messages
- Threads are addressed to a clinician (threads.clinician_id, nullable for the
  threads that predate multi-clinician care). Patients pick a recipient; the
  server defaults to their primary clinician; replies follow the thread's
  addressee instead of mailing every admin. Admin lists show "-> Dr X".

Documents
- Patients can upload their own documents. Ownership is decided server-side in
  both upload routes — only an admin may name the owner — and who gets notified
  follows who uploaded: clinician uploads notify the patient, patient uploads
  notify their care team (falling back to ADMIN_EMAILS so nothing lands in a
  mailbox nobody reads).

Also: --portal-bottom-nav-h hoisted to a token (the 60px was duplicated in two
files), slotParts() groups by CLINIC hour so a 09:30 Zürich slot reads as
morning from Tokyo, and h23 hour cycle so midnight is 0 and not 24.

pnpm verify green (932 tests, +18 new for ics/calendar-token/slotParts);
pnpm build green. Migration 0003 is additive (ADD COLUMN + FK, no new tables).

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 01:26:32 +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 300e9d02ef fix(admin): one definition of "patient" + bookings answer "who am I seeing next" (#25)
First-principles audit of the admin against the mission line ("Manuel
opens the admin and knows — without calling anyone — exactly who needs
attention today") surfaced two violations; both fixed:

- lib/domain/patients.ts patientScope() — THE definition of who counts
  as a patient (role=patient OR treated in care_team), now used by the
  patient list, the admin patients API and reports. Before, reports
  still filtered role=patient only: it claimed 3 patients / 0 critical
  while the list showed 5 / 1 critical — two admin pages contradicting
  each other on the mission-critical number.
- Bookings admin defaults to a new "upcoming" view (active bookings with
  a scheduled time, soonest first) and the subtitle answers the daily
  question before the table loads: "Next: Fri 14 Aug, 09:00 — George ·
  2 upcoming · 0 pending". The old default was "pending" — but slot
  bookings are born confirmed, so a normal day showed an empty list and
  the real schedule was buried in created-at order. Subtitle no longer
  claims "0 total" while still loading.

Verified in dev browser: reports and patient list agree (critical = 1),
bookings opens on the sorted schedule. 898 tests + build green.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 15:54:49 +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
GandClaude Fable 5 6c530594f8 fix(auth): honest email-failure handling — no more silent password-reset lockout (#21)
An unconfigured or failing email provider used to be invisible: forgot-
password answered "sent" with nothing sent (permanent lockout for the
user), cron marked queued emails as delivered, and reset-password errors
surfaced as raw English strings on localized pages. Now:

- lib/email: sendEmail never throws, returns { sent } | { sent, error },
  checks the Resend SDK's error return (it doesn't throw); new
  isEmailConfigured() gate.
- /api/auth/forgot-password: 503 with a translated "contact us at
  {email}" message when the provider is unconfigured — checked before
  any user lookup, so no account enumeration.
- /api/auth/reset-password: machine-readable error codes; the page maps
  invalid_token to a localized message plus a "request a new link"
  recovery action instead of echoing API English.
- cron-emails: unconfigured provider leaves the queue pending (retried
  next run); a provider send error marks the row failed instead of sent.
- messages/{de,en,fr,it}: unavailable + expiredError keys.

Verified in-browser at 390px and 1280px: forgot-password honest 503,
reset flow with bad token shows localized error + recovery link.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 11:19:32 +00:00
GandClaude Fable 5 45966a8e86 Design-token discipline with CI teeth + clinic-timezone dates + skeleton loading (#19)
* fix(ui): mobile patient table fits a 390px card

Walkthrough at 390px showed the triage table still ~50px wider than its
card: desktop cell padding, and the email ellipsis targeting a <p> that
is actually a <div> — plus max-width on the td, which auto table layout
ignores; the cap now sits on the inner divs.

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

* feat(design): token discipline with CI teeth, clinic-timezone dates, skeleton loading

Design discipline (SSOT enforced, not aspirational):
- Normalize every raw border-radius, transition duration, rgba() and hex
  in *.module.css to the globals.css token scale (26 files); add
  --radius-2xs (2px bars) and --radius-pill (2rem pills)
- lib/design-discipline.test.ts: 8 CI rules — no raw colors in css modules,
  radius/transition must use tokens, every var() must resolve in
  globals.css, no hex in TSX, style={{}} only in a data-driven allowlist
  (with staleness check)

UX intuition:
- formatDateISO now uses Europe/Zurich (CLINIC_TIMEZONE SSOT in
  lib/config/company.ts) instead of UTC: a 00:30 check-in no longer lands
  on yesterday's date, overwriting it and killing the streak; client and
  server now agree on 'today' even when the patient travels
- Shared <LoadingState/> shimmer skeleton (reduced-motion aware) replaces
  nine bare 'Loading…' strings across portal and admin

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 16:51:53 +00:00
GandClaude Fable 5 34371bb37f feat(ux): mobile-first dashboards — one next step, minimum reading (#17)
The dashboard asked patients to scan seven prose cards to figure out what
to do. Now it computes ONE next step and puts it first, full-width and
tappable — everything else is glanceable status.

- lib/domain/next-step.ts (+tests): SSOT priority funnel — baseline
  assessment > today's check-in > unread reply > profile (<70%) > stale
  assessment retake > booking > all-caught-up. NextStepCard renders it
  as the first element, urgent steps in teal.
- The check-in prompt, onboarding card, and stale-assessment notice are
  gone — the funnel replaces all three (OnboardingCard deleted, checkin
  card is now status-only, community check-in counts no longer shown to
  patients).
- Assessment hero drops its interpretation paragraph (lives on
  /assessments); consultation/leverage cards trimmed to essentials.
- 'Welcome' (not 'Welcome back') for brand-new users.
- Mobile: smaller page title, tighter card padding; admin patient list
  collapses to Signal · Patient · Last check-in with the whole row
  tappable (analytic columns are one tap away on the patient page) and
  emails ellipsized so nothing scrolls sideways.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 21:16:39 +00:00
GandClaude Fable 5 433de2f8a9 One-shot usability: unbreak login, admin patient view, mobile admin (#16)
* fix(auth): unblock the public API surface — login was unreachable in prod

The middleware session-gated ALL of /api, so every anonymous endpoint
307-redirected to the login page: the NextAuth session + credentials
callback (login itself), registration, password reset, the assessment-
leads funnel, and the Calendly webhook. Signed-in traffic looked healthy,
so nothing caught it.

- PUBLIC_API_PREFIXES in lib/config/routes.ts (SSOT) — each listed
  prefix authenticates itself (NextAuth, HMAC signature, CRON_SECRET,
  or Zod-validated no-PII writes)
- gated /api paths now answer 401 JSON instead of an HTML login page
- new /api/health (fleet convention): 200 = app up + DB reachable
- route-auth-invariant.test.ts pins the class: every route under a
  public prefix must self-authenticate; every gated route must import
  a guard

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

* refactor: delete the dead unlocalized auth tree + audit fixes

next-intl (localePrefix: always) redirects /login -> /de/login, so the
app/(auth) tree never rendered — a full duplicate of the localized auth
pages, drifting separately (hardcoded English, stale styles). Deleted.
Its stylesheet WAS live (portal forms imported it): the shared form
primitives now live once in app/forms.module.css; auth.module.css
re-exports them via composes.

Also from the audit sweep:
- public/robots.txt deleted — it shadowed app/robots.ts, so the
  portal/admin/api disallow rules never shipped
- portal nav labels: one SSOT (PORTAL_ROUTE_LABELS) for PortalNav and
  NavBreadcrumb — breadcrumb was silently blank on /goals and
  /documents because the two copies had drifted
- global 404 now links to the public homepage, not the auth-gated
  dashboard
- manifest icons existed only as references: generated icon-192/512.png
  from the brand mark (404'd on every page load before)
- Google auth provider only registers when its env is configured
- dead SignOutButton component + create-next-app template SVGs removed
- drop package.json pnpm.onlyBuiltDependencies (moved to
  pnpm-workspace.yaml allowBuilds long ago; pnpm warned on every run)

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

* fix(ui): admin patient page 500, dead mobile CSS, and portal polish

- schema: documents<->users is doubly connected (owner + uploader); the
  unnamed primary relation made Drizzle throw at query time and the
  admin patient-detail page — the core clinical view — 500'd in prod.
  Both sides now carry relationName. lib/db/relations.test.ts plans a
  query over EVERY declared relation so the next misconfigured relation
  (this was the second) fails in CI, not in prod.
- admin.module.css: the entire mobile @media block sat BEFORE the base
  rules it overrides (appended later), so phones got the desktop layout
  — 4-across stat tiles clipping their labels, oversized title, no
  form-grid collapse. Block moved after its base rules;
  lib/css-order.test.ts now fails any stylesheet where a base rule
  shadows an earlier @media override.
- proxy: admins landing on /dashboard (post-login default, PWA
  start_url) are redirected to /admin/patients — they were dropped into
  the empty patient portal.
- check-in scale: hovering the button just clicked painted the number
  teal-on-teal (.scaleBtn:hover outranked .scaleBtnActive)
- admin assessment-trend chart plotted newest-first — time axis read
  right-to-left; reversed to chronological
- sidebar wordmark was ink-on-ink (only 'Re' visible): Logo gains a
  'bright' on-dark variant, used by portal + admin sidebars

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 20:06:17 +00:00
G 26c18894af fix(meta): point the social preview at a host that resolves (#13)
SITE_URL fell back to https://vitareba.ch, which has NO DNS A record. Since
metadataBase is built from it, the generated og:image was advertised as
https://vitareba.ch/de/opengraph-image — a URL no scraper can fetch, so every
shared link rendered as a blank rectangle. Canonical URLs, robots.txt and the
sitemap named the same unreachable host.

The env override is untouched; only the fallback changes, so a missing
NEXT_PUBLIC_SITE_URL now degrades to correct instead of to a dead domain.
Point it back once vitareba.ch is live.
2026-08-07 09:17:13 +00:00
GandClaude Opus 4.8 ef131d98fd fix(db): add assessmentResults reverse relation — unbreaks all clinical crons (#6)
users.assessmentResults many() had no matching one() on assessment_results,
so Drizzle's relational query builder threw 'not enough information to infer
relation' — 500ing signals / check-in-reminder / weekly-digest silently in
prod (patients got no reminders). verify green.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 19:45:46 +02:00