Commit Graph
159 Commits
Author SHA1 Message Date
CatoandClaude e9994c9823 chore(brand): replace remaining VitaReBa display uses with Vita (#117)
Rename the brand in everything a reader sees: download filenames
(vita-data-export.json, vita.ics), the package name, the company.ts
register comment (Vita GmbH), CI and test comments, and test fixtures
for the sender display name and ICS calendar name.

Kept on purpose: the HIN mailbox, the vitareba.* domains, the deploy
app / Postgres role names, and the booking ICS UID suffix (@vitareba),
which subscribed calendars match on — changing it would duplicate every
existing booking.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-15 09:07:26 -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
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 Opus 5 57704c93ad fix(bookings): a clinician's own card lied to them about their own intake (#57)
Found by using the feature after shipping it: George closed his own intake in
the admin settings, then opened his own patient bookings page and saw his own
card marked "NOT ACCEPTING NEW PATIENTS — Viewing only, contact the clinic to
book" — against HIMSELF, despite already having a confirmed appointment with
himself and despite the server's own rule always allowing a dual-role
clinician to choose themselves regardless of their own setting.

canPatientChooseClinician() has always had this self-rule — it was the very
first line of the function, and #56's own tests cover it. The bug was never
in the rule. It was that the two client-side pickers (CareTeamCard, the
booking clinician selector) computed their OWN "is this closed to me" flag
from acceptingPatients + care-team membership only, and neither one knew
which roster entry was the viewer's own account — so they could not apply the
one exemption that matters most for exactly the people this product's dual
roles exist for.

/api/bookings/slots now returns selfId alongside the fields it already
returned (careTeam, clinicianId) — the same shape of fix as everywhere else
in this codebase that already passes selfId down from a server component
(profile/page.tsx → CareTeamCard). Both pickers now exempt "choosing
yourself" from the closed-intake badge and from disabling Confirm, matching
the server exactly rather than each re-deriving a smaller copy of its rule.

No test coverage added for this specific defect: it is a display-layer
mismatch with server truth, in a codebase with no DOM test environment
(recorded gap — see the portal-nav-icon outage fix). Verified instead the way
that outage was found: by using it in the browser, as the two accounts this
feature is actually for.

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

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

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

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

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

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

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

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

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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 22:34:31 +00:00
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
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 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 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 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 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 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
GandClaude Opus 4.8 b2a497d554 test(api): cross-user patient-data isolation regression net (#5)
Auth is app-layer only (no RLS), so a single deleted
eq(userId, session.user.id) where-clause leaks one patient's medical
data to another — and the existing route tests mock the DB blindly, so
they keep passing when that happens.

This net closes the gap: the DB mock compiles each route's real Drizzle
where-condition via PgDialect and evaluates it against an in-memory
store holding TWO patients' rows. An unscoped query returns the other
patient's data — exactly like real Postgres — and the assertions fail.

Locked surfaces (each verified by mutation testing — deleting the
scoping fails exactly the corresponding test):
- GET  /api/checkin        — history scoped to session user
- POST /api/checkin        — upsert existence check scoped (no cross-user
                             update path), UPDATE where binds user_id
- GET  /api/documents      — ?patientId ignored for patient sessions

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 14:04:00 +02:00
Mao NakamotoandClaude Opus 4.8 008fa90d67 chore(infra): scrub stale Vercel/Neon doc-drift after self-host migration
The June 2026 self-host migration moved hosting/DB/storage onto the Hetzner
box (Caddy + self-hosted Postgres + local-disk uploads) but left several
docs, a config default, dead deps, and a stale test mock pointing at the old
managed stack. This corrects the present-tense drift only.

- CLAUDE.md: Stack line, DB schema heading, cron section, Document Storage,
  db:push comment, "rely on Vercel" note, and the Deploy Workflow block now
  describe the self-hosted box (vitareba.ch) instead of Vercel/Neon/Blob.
- README.md: replaced create-next-app boilerplate with a real project README.
- lib/config/company.ts: SITE_URL fallback default vitareba.vercel.app ->
  vitareba.ch (the documented marketing domain; runtime env still overrides).
- package.json/pnpm-lock.yaml: removed dead deps @vercel/blob and
  @neondatabase/serverless (zero live imports after migration).
- app/api/documents/upload/route.test.ts: mock repointed from @vercel/blob
  (no longer imported) to @/lib/storage putLocal, matching the migrated route.
- vitest.config.ts: exclude **/.next/** so stale standalone test copies don't
  shadow source tests.
- .gitignore: ignore /uploads (local-disk UPLOADS_DIR default).
- .mailmap: collapse legacy g-but identity onto canonical Mao Nakamoto.

vercel.json is intentionally KEPT: its `crons` array is the SSOT for the
schedule list that the box's systemd timers mirror.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 21:34:16 +02:00
Mao NakamotoandClaude Fable 5 527aee5958 feat(selfhost): migrate to self-hosted Hetzner (Vercel/Neon/Supabase exit 2026-06-12)
Standalone output, portable Postgres driver, proxy-aware fixes as needed.
Runbook: fleetcrown/docs/infrastructure/hetzner-migration.md

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 19:48:13 +02:00
g-butandClaude Sonnet 4.6 2fb657105a fix(api): validate UUID route params to prevent 500 on malformed IDs
Adds UUID_RE check at the top of every dynamic route handler ([id],
[goalId], [threadId]) so invalid param values return 400 instead of
causing a PostgreSQL type error (500). Adds badRequest() helper to
lib/utils/api-response.ts alongside the existing serviceUnavailable().
Test PARAMS fixtures updated to use valid UUIDs so all 798 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 08:44:32 +02:00
g-butandClaude Sonnet 4.6 2d6f35af60 test(api): add route tests for cron/emails, weekly-digest, documents/upload, webhooks/calendly
Brings test coverage to 798 tests across 55 files. Completes the
API route test suite — all routes now have unit tests except the
NextAuth handler.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 21:22:32 +02:00
g-butandClaude Sonnet 4.6 3a8370ae6a test(api): add route tests for cron/checkin-reminder, assessment-leads, convert, and documents (25 tests)
cron/checkin-reminder: 401 auth, 500 workflow DB failure, 200 success — route delegates to
the workflow so only the thin HTTP layer is exercised here. assessment-leads: public POST
with JSON/schema/DB validation. assessment-leads/convert: auth, UUID validation, and the
intentional error-swallowing path (DB failure → still returns 200). documents: GET with
admin all-docs/filtered/patient branching, UUID query-param validation; POST with admin
guard, insert failure, 201 + notification callback verified (email sent/skipped by patient
email presence).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 21:08:49 +02:00
g-butandClaude Sonnet 4.6 d38bcd8ec2 test(api): add route tests for admin patients sub-routes and goal CRUD (30 tests)
Covers: /api/admin/patients/[id]/goals (GET + POST), /api/admin/patients/[id]/notes
(GET + POST, including admin-name lookup failure path), /api/admin/patients/[id]/profile
(PATCH with and without name — verifies users table update is skipped when no name
provided), /api/admin/goals/[goalId] (PATCH with completedAt set/clear logic, 404 on
empty returning, DELETE). All auth-guard, DB-failure, schema-validation, and success
branches covered.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 21:03:47 +02:00
g-butandClaude Sonnet 4.6 d05353aff2 test(api): add route tests for /api/goals, /api/admin/patients, /api/admin/patients/[id]
12 tests covering the three read-only admin and patient GET routes: auth guard
(401), DB failure (500), not-found (404 for the [id] route), empty-list, and
success with data. All three routes follow the same guard → query → respond
shape, so this completes the simple GET route coverage.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 20:54:31 +02:00
g-butandClaude Sonnet 4.6 d29accfe32 test(api): add route tests for /api/messages (GET + POST, 14 tests)
Covers: 401 unauth, 500 DB failure, 200 patient/admin GET branching, 400
schema validation, 201 success for both patient and admin POST paths, and
notification callbacks — verifies admin emails receive patient messages
and patient email receives admin messages. Also confirms no notification
is scheduled when admin email list is empty.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 20:50:30 +02:00
g-butandClaude Sonnet 4.6 c24a6dcbf5 test(api): add route tests for change-password endpoint
10 tests covering: auth guard, schema validation (missing field, too-short
password), DB-read failure (500), OAuth-only account (no password set, 400),
account lockout (429), wrong-password branch with failed-attempt recording,
DB-update failure (500), and success path verifying the new hash and lockout-
state clearing. Security-sensitive path — brute-force and lockout branches now
verified by test rather than manual inspection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 20:11:21 +02:00
g-butandClaude Sonnet 4.6 03c572750c refactor(ssot): use displayName() for patient sender names in message notifications
Replace patient?.name ?? "patient" with displayName() in admin notification
emails so name resolution is consistent: email local-part shown when no name
is set, rather than the generic word "patient".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 19:51:15 +02:00
g-butandClaude Sonnet 4.6 bb4a6c6b42 chore(imports): merge duplicate imports in bookings/route.ts
Three separate import statements from the same module merged into one each.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 19:44:26 +02:00
g-butandClaude Sonnet 4.6 7ee94c9ace refactor(ssot): extract serviceUnavailable() helper and standardise displayName usage
- Add lib/utils/api-response.ts with serviceUnavailable() — replaces 17
  identical NextResponse.json({error: "Service unavailable..."}) call sites
- Replace all patient.name ?? "there" / patient.name ?? patient.email fallbacks
  with displayName() — the existing utility already handles these cases
- Merge duplicate @/lib/config/routes imports in bookings/route.ts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 19:39:56 +02:00
g-butandClaude Sonnet 4.6 626a0914b1 refactor(ssot): replace magic numbers with named constants
- Add DAYS_PER_WEEK and WEEKLY_DIGEST_STREAK_WINDOW_DAYS to lib/config/portal.ts
- Replace raw 7/14/90 offsets in cron-weekly-digest with those constants
- Replace hardcoded >= 100 in cron-emails with GOAL_PROGRESS_COMPLETE_PCT
- Replace streak threshold literals in email templates with CHECKIN_STREAK_MILESTONES

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 19:00:11 +02:00
g-butandClaude Sonnet 4.6 36ae08544f test(api): add route tests for account registration and auth password-reset flows
Covers POST /api/account (7 tests), POST /api/auth/forgot-password (8 tests),
and POST /api/auth/reset-password (6 tests) — 21 tests across 3 files.

Account: validates email/password schema, email-uniqueness check, race-condition
409 from empty onConflictDoNothing returning[], welcome email queue via
runAfterResponse. Pattern: insert mock NOT seeded in beforeEach to prevent
mockReturnValueOnce queue bleed across tests.

Forgot-password: all paths return 200 (anti-enumeration); side effects
(sendEmail / DB writes) distinguish paths. Tests cover invalid email,
unknown user, OAuth-only account, DB failure, rate-limit window, token-op
failure, success, and stale-token replacement.

Reset-password: 400 for invalid body or expired token, 500 for DB failure,
200 success verifies password hashed, lockout state cleared (failedLoginAttempts=0,
lockedUntil=null), and token consumed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 18:35:24 +02:00
g-butandClaude Sonnet 4.6 badf862301 test(api): add route tests for assessment and admin programme endpoints
Covers GET/POST /api/assessment (8 tests) and GET/PATCH
/api/admin/patients/[id]/programme (12 tests).

Assessment POST: validates all 5 dimension keys via assessmentScoresSchema,
distinguishes first-assessment vs retake (isFirstAssessment flag), and
gracefully defaults to first-assessment when the prior-check DB call fails.
Programme PATCH: update path skips notification email; insert path fires
patient enrolment email via runAfterResponse; missing patient email is
handled silently.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 18:28:12 +02:00
g-butandClaude Sonnet 4.6 00eb51850e test(api): add route tests for bookings and messages endpoints
Covers GET/POST /api/bookings, PATCH/DELETE /api/bookings/[id], and
GET/POST /api/messages/[threadId] — 39 tests across 3 files.

Uses the established capture-and-invoke pattern for runAfterResponse
callbacks (fire-and-forget; invoked explicitly to avoid floating-Promise
races). Key assertions: admin booking creation triggers patient
confirmation email; patient booking triggers admin notification only when
ADMIN_EMAILS is configured; PATCH confirmed/cancelled fires patient email
while attended does not; patient self-cancellation triggers admin alert;
admin/patient message routing sends to the correct recipient; mark-read
fires after GET response.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 18:16:16 +02:00
g-butandClaude Sonnet 4.6 1c20d0a5e1 test(api): route tests for /api/profile and /api/checkin
/api/profile (12 tests):
- GET: 401 when unauthenticated, 500 on DB failure, merged profile+user data
  returned correctly, null when no profile row exists
- PATCH: 401, 400 for invalid body (sleepHoursAvg out of range), 500 on DB
  failure, admin notification sent when completeness crosses 70% threshold
  (callback captured and invoked explicitly to avoid floating-Promise races),
  no notification when below threshold / already above / no admin emails,
  db.update(users) called only when name field present

/api/checkin (14 tests):
- GET: 401, 500 on DB failure, todayCheckin identified in history, null when
  absent, ?days param respected
- POST: 401, 400 for out-of-range values (with details field), 500 on DB
  failure, existing check-in path uses UPDATE (no streak check), new check-in
  path uses INSERT + captures runAfterResponse callback, 7-day streak fires
  milestone email, non-milestone streak is silent, missing user is silent

Note: runAfterResponse is mocked to capture (not auto-invoke) the callback.
Tests that verify side effects call the captured callback explicitly after
awaiting the route handler, avoiding the floating-Promise race that occurs
because the route does not await runAfterResponse.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 17:57:07 +02:00
g-butandClaude Sonnet 4.6 4cbdd5ffaa refactor(api): extract cron logic to lib/workflows, standardise fire-and-forget
- Move all business logic out of the 5 cron route handlers into pure,
  injectable lib/workflows/* functions so they can be unit-tested without
  spinning up a Next.js server
- Add runAfterResponse() util (wraps next/server `after`) to replace the
  ad-hoc .then().catch() fire-and-forget pattern used across 9 API routes;
  errors are now logged consistently and work is not dropped at request
  lifecycle end
- Add 540 tests (5 new suites) covering cron workflows; fix vi.hoisted()
  pattern so vi.mock factories don't hit the temporal dead zone
- Replace magic signal strings in patients page with PATIENT_SIGNAL constants
- Replace magic "pending" string in bookings page with BOOKING_STATUS.pending
- Replace hardcoded 30-day window in reports page with CHECKIN_DISPLAY_DAYS
- Extract duplicate streak-message inline IIFE in email templates to the
  streakMessage() helper already in lib/domain/checkin (DRY)
- Add `pnpm typecheck` script to package.json

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 17:05:46 +02:00