mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
3ec80adbd244da35c452240e2b89f0cec5154fa4
25
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
3ec80adbd2 |
fix(medications): never snap a taken intake onto a future dose slot
A taken intake whose write named (or snapped near) a slot still in the future was attributed to that slot and rendered as taken before its time — a late morning dose collapsing onto the evening slot of a twice-daily med. The slot resolver now takes an isTakenWrite flag and a now reference: a taken write skips any candidate slot more than a small clock-skew grace into the future, so it snaps to a current/past slot or keeps its own row. Pending sync echoes are unaffected and still map to future slots. |
||
|
|
a55816bf58 | fix(medications): retrospective rolling-cadence compliance + currentCycle descriptor | ||
|
|
6871e8ea77 |
fix(medications): stop defaulted-now intake from auto-taking a far slot
A slot-less "taken now" write (no client scheduledFor) defaulted its instant to now/takenAt and snapped across the wide ±halfGap window onto the nearest scheduled slot. For a 07:00 / 19:00 med a midday write captured the 07:00 morning slot and stamped it taken — a phantom morning dose. The web fix only threaded the displayed slot on the card; any client posting takenAt-only (iOS bulk/sync) still tripped it server-side. Thread an instantIsExplicit flag through resolveSlotInstantForWrite into the canonical resolver. An explicit scheduledFor keeps the full ±halfGap snap unchanged. A defaulted-now write snaps only inside the tight dose-grace window and otherwise resolves to null (PRN), so it records a standalone taken-now row instead of back-filling a far slot. Both intake call sites pass scheduledFor !== undefined; takenAt alone is not explicit. Add resolver unit coverage for midday defaulted-now writes (07:00/19:00 → null at 11:00/12:00/13:00, explicit 07:00 still snaps) and a DB-backed regression that a takenAt-only midday write leaves the 07:00 slot untaken. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
037da560ad |
fix(compliance): compute medication streak in the user's timezone
The analytics compliance streak keyed days with host-local getFullYear/getMonth/getDate against a timeline whose slot.day is minted in the user's IANA zone, so the streak drifted off by a day whenever the server clock's zone differed from the user's. Consolidate onto the detail-page streaksFromTimeline helper threaded with the medication's timezone so both call sites share one correct day-keyed walk. Also fix the DST step in that helper: it stepped a fixed +24h while its comment claimed 25h, which could skip a local day on the 23h spring-forward boundary and run the window short. Snap each cursor to the user-local midnight and advance +25h then re-snap, mirroring the cadence expander, so every local calendar day is visited exactly once across 23/24/25h boundaries. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
e0f60d82cc |
fix(medications): correct weekly-cadence compliance returning 0% despite recorded intakes
A weekly injectable (e.g. a GLP-1 dose) with real recorded intakes reported 0% compliance on the medication card across every window (7 / 30 / 90 days). The web reads the server-computed rate verbatim, so the server value itself was wrong. The intake-to-slot matcher used a fixed +/-12h pairing radius. That is correct for a daily cadence (24h inter-slot gap) but far too tight for a once-weekly dose: a real intake is rarely logged within 12h of the schedule's configured time-of-day, because the user takes the shot on whichever day and time of the dosing week suits them. Those intakes fell outside the radius, every weekly slot read "missed", and the rate collapsed to 0% while the matching intakes were orphaned. Scale the pairing radius with the cadence gap. `pairDoses` now derives a per-slot radius from half the distance to its nearer neighbouring slot (so two adjacent slots never double-claim one intake), floored at the 12h base so daily and multi-dose-daily cadences keep their exact prior behaviour. `buildCadenceTimeline` additionally probes the schedule's intrinsic cadence over a padded window and passes half the minimum inter-slot gap as a radius floor, so a window holding a single expected slot (a weekly med over a 7-day window) widens correctly too. A weekly cadence now pairs an intake logged anywhere in the dosing week to that week's slot, reporting the true rate. Daily-cadence matching is unchanged. Adds unit coverage for the widened radius and a real-Postgres integration test mirroring the weekly-injectable row + off-time intakes. |
||
|
|
793602f464 |
fix(medications): cap intake snap tolerance to the inter-dose gap so multi-dose orals don't collapse
A daily oral with multiple timesOfDay and a wide schedule window had its dose-slot capture zones overlap, so a second same-day dose could snap onto an already-actioned slot and be dropped by the no-downgrade guard — the intake never landed as its own row. A twice-daily 08:00 / 20:00 schedule with an 08:00-22:00 window yielded a +/-7h half-span tolerance that exceeded half the 12h inter-slot gap, so the evening write collapsed onto the morning slot. Weekly and single-dose schedules (one slot/day) were immune. snapToleranceMs now caps the tolerance at half the minimum gap between adjacent sorted timesOfDay entries (the midnight wrap counted as one of those gaps) whenever a schedule has more than one slot, keeping the two nearest slots' capture zones disjoint. Single-slot schedules keep the full half-window-span behaviour, and the >=1-minute drift floor is preserved, so weekly injectables and once-daily orals are unchanged. Adds unit coverage for the wide-window two-dose case (distinct slots, no collapse) plus an explicit weekly single-dose regression, and an integration test driving both same-day writes through the DB-backed slot resolver and canonical-slot upsert to assert two distinct live rows. |
||
|
|
ba4349eda0 |
refactor(db): extract the P2002 predicate into one shared helper
The Prisma unique-constraint (P2002) narrowing predicate had been hand-copied into five call sites. Fold them into a single isP2002 in src/lib/prisma-errors.ts and import it everywhere (the two step-drain sites keep their local isUniqueConstraintViolation name via an import alias). Behaviour-identical; one place to chase a future P2002-semantics change instead of five. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
fef88787e9 |
fix(medications): surface a multi-day-overdue first rolling dose
A rolling cadence with no intake logged anchors its first dose at startsOn ?? createdAt. When that anchor falls on a prior calendar day the dose is overdue by a day or more, but nextOccurrenceAfter floored the search window to the start of the user's current day and dropped it — so the dashboard showed no next-due and the reminder worker, which shares this engine, emitted nothing. Clamp the floor to the first-dose day in the no-intake branch so a multi-day-overdue start dose surfaces as overdue. The post-intake re-anchor (lastIntakeAt + N) is unaffected. |
||
|
|
b99a015266 |
feat(medications): make injection-site tracking and rotation real
The injection_site column on intake events was read across several surfaces but never written, so site tracking was effectively dead. Wire it end-to-end as a per-medication opt-in, gated on an INJECTION delivery form and default off. - Schema: add medications.track_injection_sites + allowed_injection_sites and users.global_excluded_injection_sites (migrations 0099, 0100; additive, defaulted, no backfill). - Intake write path: accept an optional injectionSite on the per-med, status-toggle, and bulk intake routes. Persist it only on a taken injection with tracking enabled, validated against the medication's effective allowed set (per-med allowed sites minus the user-level global exclusion, deny wins) — a disallowed site returns 422 (the bulk route skips the entry). - Rotation: extend the least-recently-used recommender with an allowed filter; the picker disables sites outside the effective set. - UI: per-medication tracking toggle + allowed-sites editor in the dose wizard step, a skippable post-dose site prompt on both medication cards, and a Settings card for the user-level global exclusion. - Contract: injectionSite is additive on the intake request; OpenAPI regenerated. New GET/PATCH /api/auth/me/injection-site-prefs. The site capture is always optional and never blocks logging a dose. |
||
|
|
b3f61d0c75 |
fix(medications): surface the first rolling dose at the start date
Rolling schedules anchored next-due on start + N days when no intake had been logged yet, which skipped the dose due AT the start date and suppressed its reminder (the worker shares this engine). The +N cadence now begins only after the first intake is logged: with no intake the first dose is due at startsOn (or createdAt). A past start date with no intake surfaces the dose as due/overdue rather than rolling it forward — nextOccurrenceAfter floors the rolling search to the start of the user's day so an overdue or due-earlier-today dose stays visible. The post-intake re-anchor (lastIntakeAt + N) and the endsOn cap are unchanged; PRN, one-shot, RRULE and legacy cadences are unaffected. |
||
|
|
0e3a8f9cd3 |
fix(medications): read next-due from the server and confirm intake actions
Two fixes on the medication cards.
Next-due: the card recomputed "next intake" client-side from
`daysOfWeek` + `windowStart` alone, ignoring rolling intervals, RRULE,
one-shot doses, and the last-intake anchor. A rolling medication (e.g. a
35-day interval) showed "tomorrow" and never re-anchored after a dose.
`GET /api/medications` already returns `nextDueAt` per medication,
computed by the canonical recurrence engine anchored on the last intake.
Both card variants now render that value directly: the generic card
drops its `getNextOccurrenceTimestamp` walker, and the GLP-1 card drops
its weekly-only predictor that hardcoded a 7-day step. The day-label and
window-range rendering are unchanged; only the timestamp source moves to
the server. `nextDueAt` is threaded through the list page's medication
type into both cards.
Intake confirmation: tapping Taken / Skipped now raises a toast naming
the medication ("… recorded as taken" / "… skipped"), so the action has
clear feedback. The next-intake line refreshes on the invalidated list
query, which the next-due fix above makes accurate.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
710902a43c |
fix(medications): harden the slot upsert against races, downgrades, and double-decrements
Review of the slot-convergence change surfaced gaps that could mis-record a dose. Fold the write logic into one shared `applyCanonicalSlotWrite` used by both intake routes and close them: - Concurrency: catch the unique-key race on insert and converge by re-finding the slot row and updating it, instead of returning 500 (and dropping the tap) or leaving a duplicate. - No downgrade: a pending projection echo replayed onto a slot already marked taken or skipped is a no-op — it never clears `takenAt`. A recorded dose is immutable, so an offline re-sync cannot flip a taken dose back to missed. - Inventory: decrement a medication's remaining count only on a genuine pending→taken transition, not on an idempotent re-post. - Deterministic slot-row selection: prefer an existing actioned row, then the pending row, ordered by createdAt then id. - Snap instant: derive the canonical instant via the same `localHmAsUtc` the projector and reminder worker mint with, so the value is identical by construction across a DST transition rather than only test-pinned. - Cleanup job: isolate each slot's collapse in its own try/catch and guard the instant-normalisation against a tombstone collision, so one slot can no longer dead-letter a user's whole dedup pass. |
||
|
|
0d7d08f616 |
fix(medications): converge intake writes onto one row per scheduled slot
A twice-daily medication ended up with two rows for one dose slot: the projector / reminder worker mints a pending row (source REMINDER) at the slot's `localHmAsUtc` instant, while a "taken" write from the per-med or bulk intake route inserted a fresh row (source WEB / API). Because `source` is part of the `(userId, medicationId, scheduledFor, source)` unique key — and the written instant could drift by a minute from the projected one — the two rows coexisted: one taken, one still pending and overdue. The card then read the slot as taken, counted 100%, and suppressed the "due now" prompt for a dose the user had not taken. Resolve every scheduled intake write to the slot's canonical instant before writing and upsert in place, source-agnostic: - `resolve-slot-instant.ts` snaps an incoming instant to the nearest scheduled slot for that day (enumerated through the canonical recurrence engine, so PRN and cyclic off-weeks resolve to no slot) and anchors it on the same `localHmAsUtc` the projector and worker use. Off-slot and as-needed writes resolve to null and keep insert semantics. - The per-med and bulk routes look up the existing row at the canonical `(userId, medicationId, scheduledFor)` ignoring source and update it in place — mirroring the status-toggle route — instead of inserting a sibling. The bulk per-entry response gains an additive `updated` status. - The reminder worker's missed-dose mint now skips a slot that already carries an actioned row (taken or skipped) from any source, not only an existing pending REMINDER row. PRN / as-needed writes are unaffected. Regression tests pin the collapse (exact and one-minute drift), the PRN exemption, and the worker guard. |
||
|
|
fcb517df87 |
fix(medications): fan out the today-tile projector over every time-of-day
The today-window projector minted a single pending intake row per schedule, anchored at `windowStart`, dropping a schedule's first-class `timesOfDay`. A twice-daily medication stored as one schedule row with `timesOfDay = ["07:00","19:00"]` therefore surfaced only its morning dose in the today tile and the "Erfassen" sheet, and the event-count compliance rollup recorded one expected dose per day instead of two — a perfectly adherent user read 50% the moment the second dose was logged, and deleting then re-adding one dose left the rate stuck at 50%. Fan the projection out over every `timesOfDay` entry, mirroring the reminder worker's per-slot mint and dedup against the `(userId, medicationId, scheduledFor, source)` unique index. Absent first-class `timesOfDay` the projector still emits one slot at `windowStart`, byte-stable against the worker's legacy single-window row. Adds regression coverage across the projector (dashboard summary), the legacy compliance walker, and the cadence expansion pinning the single-row twice-daily case at the correct two-dose-per-day shape. |
||
|
|
013ad5d967 |
fix(compliance): expand multi-time legacy schedules through the canonical engine
A medication whose schedule row carried multiple timesOfDay plus a legacy daysOfWeek (and no rrule / rollingIntervalDays) reported 50% compliance for a fully-adherent 2x/day dose. The expected-slot denominator always ran the canonical recurrence engine and counted both daily slots, but the numerator only delegated to the engine for rrule / rolling / one-shot / non-SCHEDULED rows; a plain-legacy row fell to the local cadence walker, which emitted a single windowStart slot per day and ignored timesOfDay. 1 taken / 2 expected read as 50 percent. Route expandScheduleSlots through the engine for every schedule shape whenever a medication context is supplied, so the numerator and denominator read the same source of truth. Harden the context-less legacy walker to iterate timesOfDay as well, mirroring the engine's legacy branch, so the single remaining non-engine path stays correct for multi-time rows. Drop the now-dead expander gate helper. Add regression guards: a 2x/day legacy row reports 2/2 through calculateCompliance, and expectedSlotCountForDay agrees with buildCadenceTimeline on the slot count for an identical schedule. |
||
|
|
50e0a65228 |
chore(release): v1.7.0
v1.7.0 — health-record export (PDF + FHIR), flexible medication schedules, first-paint dashboard snapshot, full HealthKit coverage, offline sync delta feed, Coach data clustering. See CHANGELOG. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
8ee7aaac44 |
chore(release): v1.6.0
Medication editor overhaul, route of administration, today-tile read-flip. - Route-of-administration column (ORAL | INJECTION | OTHER) decoupled from treatmentClass; injection-site picker surfaces for any injection. Migration 0088 backfills ORAL via a constant column default. - One-time injection (oneShot + deliveryForm = INJECTION) editor path. - Profile-photo upload card on Settings → Account. - Today-tile read-flip: /api/medications/intake?scope=today and /api/dashboard/summary gate through the canonical recurrence engine, matching the reminder worker for bi-weekly, rolling, RRULE, and one-time cadences. - Measurement note cap 25 → 200; dashboard range colors on semantic tokens; admin sidebar icons + shared-helper consolidation; API-tokens multi-language snippets restored. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
c7e839f97a |
fix(meds): close the legacy-tier startsOn gap in the recurrence engine
The legacy fallback now honours medication.startsOn the way every other dispatch tier does, so a legacy-shape schedule with a future startsOn no longer emits historical slots. Adds a MAX_CHUNKS cap on the forward walk for defence-in-depth, surfaces RRULE parse errors through annotate, and stops the engine from compounding the user's UNTIL/COUNT with its own UNTIL suffix. The header doc-comment is rewritten to reflect that the read-flip for the legacy walkers is the v1.5.1 release, not this one. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
344d1c33b0 |
feat(meds): route the reminder worker through the canonical recurrence engine
Two changes that ship as one because they share a single rewrite of the worker's schedule-resolution site: ### The bi-weekly fix `grep intervalWeeks src/lib/jobs/reminder-worker.ts` used to return zero hits. The worker iterated `recurrence.daysOfWeek.includes( todayDow)` and called it good — a bi-weekly Wednesday schedule fired EVERY Wednesday, regardless of "on" vs "off" week. The cadence chart respected the interval; the worker did not. This is the single line at `reminder-worker.ts:514` and it's been wrong since `intervalWeeks` was introduced. The fix routes the same predicate through the new canonical engine (`src/lib/medications/scheduling/recurrence.ts`). The engine honours INTERVAL natively for RRULE schedules and honours the legacy `intervalWeeks > 1` arithmetic on the fallback path. Both paths now agree with the chart. ### New cadence types The same rewrite picks up monthly / quarterly / yearly / rolling / one-shot for free because the engine dispatches on the schedule's shape. The worker doesn't special-case anything — it just asks the engine. ### Rolling needs a `lastIntakeAt` Rolling schedules anchor next-due on the latest `MedicationIntakeEvent.takenAt`. The worker now does a conditional findFirst on the medication's intake stream when the schedule list contains a rolling row. The lookup is gated on `med.schedules.some(s => s.rollingIntervalDays !== null)` so the calendar-cadence common case keeps its single-query hot path. ### The seam — `worker-helpers.ts` A small module exports `buildCanonicalSchedule`, `buildRecurrenceContext`, `scheduleEmitsInWindow`. Keeps the worker file focused on phase math and dispatch (it's 2347 LOC; a deeper rewrite is for another release) and gives the integration tests a clean place to exercise the schedule-resolution path with real Postgres rows. ### Dead code retired - `todayDow` (line 492) — replaced by the engine's per-instant check. - `getDayOfWeekInTz` alias (line 355) — last caller was `todayDow`. - `parseScheduleRecurrence` import — the worker no longer touches the legacy decoder directly; the engine handles the fallback. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
65b923ad53 |
feat(medications): canonical recurrence engine + Zod validation
A single source of truth for "does this schedule fire at this moment?" — replaces the three duplicate engines that grew up alongside each other (`expandScheduleSlots` in scheduling/cadence, `getNextOccurrenceTimestamp` on the medication card, `getNextRecurrenceDate` in the medication form). The retirement of the three legacy walkers is a follow-up wire-up step; this commit ships the engine standalone with no callers so the foundation can land on its own. ### `src/lib/medications/scheduling/recurrence.ts` Three public functions: - `occurrencesBetween(schedule, from, to, ctx)` — emit every slot in `[from, to]` inclusive, time-of-day applied, in chronological order. - `nextOccurrenceAfter(schedule, after, ctx)` — strict-after; null when the schedule has terminated. - `matchesInstant(schedule, instant, ctx)` — 1-minute-tolerance predicate for the reminder-worker fan-in. The engine dispatches on the schedule's shape: - One-shot → emit one slot per `timesOfDay` at the course anchor. - Rolling → next-due = `lastIntakeAt + rollingIntervalDays * day`, fall back to `startsOn` / `createdAt` when never taken; emit only the immediately-next slot (past rolling occurrences are historical intake events, not predictable future slots). - RRULE → delegate to the `rrule` library with `dtstart = startsOn ?? createdAt` and an optional `until = endsOn`. - Legacy fallback (rrule + rolling both null, oneShot false) → decode the existing `daysOfWeek` string and emit weekly slots, **now correctly honouring `intervalWeeks > 1`** — the existing `expandTodayIntakes` skipped multi-week schedules; the engine emits them anchored at `startsOn` / `createdAt`. Time-of-day application uses the canonical `wallClockInTz` helper so a `08:00` schedule fires at Berlin 06:00 / 07:00 UTC depending on DST, and a Tokyo 08:00 schedule fires at the correct UTC instant regardless of the host clock's zone. The DST spring-forward case (02:30 on the transition day in Europe/Berlin) forwards to 03:30 wall-clock — matches macOS / iOS / Google Calendar behaviour. Grace window is computed from `reminderGraceMinutes` when set, otherwise from the legacy `windowEnd - windowStart` span, with a 60-minute default for legacy single-time windows. DoS protection: `nextOccurrenceAfter` walks forward in 90-day chunks with a 10-year hard cap so a broken / pathological RRULE can't spin the worker. ### Tests 28 cases pinning the contract for every dispatch branch: - RRULE DAILY / WEEKLY / MONTHLY / QUARTERLY / YEARLY across multi-month windows. - Bi-weekly Wed anchored — emits weeks 1/3/5, skips weeks 2/4/6. Pins the pre-existing `intervalWeeks` worker bug closed for the legacy fallback path. - Rolling: last-intake anchor + null-intake fallback + endsOn cap. - One-shot: emit + nextOccurrenceAfter returns null past it. - DST spring-forward (Europe/Berlin) + cross-TZ (Asia/Tokyo). - endsOn inclusive of full UTC day (matches `@db.Date` semantics). - Empty `timesOfDay` falls back to `[windowStart]`. - Grace window: explicit, legacy span, default 60 min. ### Zod validation `scheduleSchema` extended with `timesOfDay` (HH:mm entries, max 8), `reminderGraceMinutes` (1..1440 minutes), `rrule` (length-bounded + regex against the RRULE properties HealthLog mints), and `rollingIntervalDays` (1..365). A `.refine` enforces the rrule-xor-rolling invariant at the validation layer (the DB CHECK constraint is the second line of defence). `createMedicationSchema` + `updateMedicationSchema` gain the medication-level `startsOn`, `endsOn`, `oneShot` triplet. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
67207d725e |
chore(release): v1.4.41 — iOS perf hotfix, soft-delete completeness, tree hygiene
Eight touch-disjoint waves landed on develop before this release: - W-INSIGHTS-HOT + W-RECONCILE-INSIGHTS — extract the timeout-stub persist helper and wire all seven *-status routes through it, closing the recurring ~14 s warm response the iOS client sees on dashboard open once the AI provider has stalled once that day. - W-DELETED-2 — close the remaining three soft-delete reader-tier gaps (export bundle, gamification achievements, doctor-report aggregator) with a five-route integration-test pin. - W-ORG — types consolidation into src/types/analytics.ts and src/types/backups.ts; prompt directory unification. - W-FRONTEND-FACTORY — queryKey factory expansion + ESLint rule lift. - W-IOS-COORD — POST /api/auth/check-user four-branch onboarding discovery, identifier matched verbatim, per-IP rate-limited. - W-SIMPLIFIER — today-intake projection helper extract; unused tx? params dropped; 13 knip-flagged dead exports trimmed. - W-PERF-OPS — v1.4.39 W-SUM legacy-NULL UNION discovery arm retired. - W-PROCESS-DOCS — pg.Pool sizing operator doc; ESLint rule formalisation; knip CI gate staged for v1.4.42 flip. No migration, no env-var change, no API contract break for iOS v0.5.4. The new check-user endpoint is an additive surface. AP-2 .p8 key is installed; SB-5 time-sensitive APNs is live as of this deploy. pnpm test --run green at 4732 passing / 1 skipped. pnpm typecheck, pnpm lint, pnpm knip green. |
||
|
|
1114cf7e63 |
chore(release): v1.4.40 — comprehensive Critical+High architecture closure plus iOS PB30 enablement
Eleven touch-disjoint waves landed on develop plus a six-axis QA reconcile round before tagging. See CHANGELOG.md for the user-facing prose; this commit message documents the wave + report inventory for release-management traceability. Waves shipped (each with a phase report under .planning/): - phase-W-POOL-v1440-report.md — p-limit(4) wrapper around the analytics 15-way fan-out + pg.Pool max raised 10 -> 20. Closes the v1.4.39 empirical-trace finding #1 (Prisma pool starvation). - phase-W-DELETED-v1440-report.md — 11 reader-tier helpers + 3 integration contracts close audit Critical Finding #3 (soft-delete invisibility) across dashboard, analytics, summaries, rollup tiers, and the Coach snapshot path. - phase-W-INSIGHTS-v1440-report.md — mood-rollup swap on the three /api/insights/{features,targets,cards} routes plus the compliance-rollup hook gap closure for bulk-projection mints; the post-QA reconcile patch closes the six remaining measurement.findMany sites in the cluster that still leaked tombstoned rows. - phase-W-INFRA-v1440-report.md — rollup helper umbrella consolidation under src/lib/rollups/* with zero orphan re-exports; lint, typecheck, knip, and 93/93 rollup tests green post-restructure. - phase-W-RSC-v1440-report.md — per-tile Suspense boundaries plus the queryKey factory-bypass walker test (extended to comparison/ in the reconcile pass). - phase-W-PRIVACY-v1440-report.md — bilingual /privacy page with 17 paired-section tests pinning the 9 SB-3 disclosure requirements. - phase-W-AASA-v1440-report.md — /.well-known/apple-app-site-association endpoint pinned to S8WDX4W5KX.dev.healthlog.app with app-ID parity assertions guarding against split rotation. - phase-W-APNS-NOTIFY-v1440-report.md — MEDICATION_REMINDER time-sensitive APNs payload (priority 10 + interruption-level) scoped via a parameterised test that pins all 6 other event-types do not bypass Focus. AP-2 .p8 install gates real delivery. - phase-W-CONSENT-v1440-report.md — AI consent receipts CRUD with append-only invariant pinned in test; revoke-then-regrant leaves both rows; idempotent DELETE returns 200 + receipt: null. - phase-W-WMY-WIRE-v1440-report.md — three previously-dead WMY readers (week/month/year) wired through summaries-slice and health-score-fast-path with a linear-composability parity test pinning the cross-consumer routing contract. - phase-W-GHOSTS-v1440-report.md — ~1 177 lines of dead code removed across 9 atomic commits; startOfUtcDay + wallClockInTz consolidation eliminates a sibling-drift risk; knip whitelist trimmed to three files pending follow-up. QA reconcile patches applied per the v1.4.40 QA round (six reports under .planning/round-v1440-QA-*-findings.md): - senior C1 — dashboard-suspense-boundaries regex aligned with the post-W-INFRA Thread 2 userTimezone-local lift. - senior H1 — soft-delete filter added to the six remaining insights measurement.findMany sites. - specialist H1 — Promise.allSettled around bulk-projection compliance recompute on both /api/medications/intake and /api/dashboard/summary. - ux H1 — compare-toggle migrated to queryKeys.dashboardWidgets factory; walker test extended to src/components/comparison/. - security M1 — consent artefact 64 KB cap enforced via Buffer.byteLength (UTF-8 bytes, not UTF-16 code units). Quality gates green at tag: pnpm typecheck, pnpm lint, pnpm knip --include files,dependencies,binaries,unlisted, pnpm test --run (4726 passing / 1 skipped). Tests 4525 -> 4726 unit + 1 skipped over the v1.4.39 -> v1.4.40 span. User-facing prose: see CHANGELOG.md. |
||
|
|
affede31a4 |
v1.4.34 — apple-health import + reliability + web-freeze
The final functional web release before the iOS native client lands.
Headline work: a streaming Apple Health `export.zip` importer for
prospective iOS-migrating accounts, a server-side aggregation cache
that collapses the three hottest dashboard reads onto in-process LRU
slots with single-flight coalescing and per-user invalidation, a
broader compliance classifier with a dedicated `early` bucket so
ahead-of-window doses count as compliant, the Coach launch surface
hoisted onto every authed page with a dashboard-hero CTA, and a
trimmer Settings shelf that folds Sources into Targets. The release
also lights up the `cache.<name>.outcome` annotation on the active
wide event so production logs carry the cache hit-ratio signal
without leaking userIds.
### Added
- **Server-side aggregation cache.** A new `ServerCache<T>` primitive
(`src/lib/cache/server-cache.ts`) extends the v1.4.33 Coach snapshot
LRU shape into a reusable per-route layer with TTL expiry,
capacity-bounded LRU eviction, single-flight read coalescing, and
per-instance hit / miss / eviction / stampede counters. Wires the
three hottest dashboard reads — `/api/analytics` (slim + default),
`/api/gamification/achievements`, `/api/medications/intake?scope=compliance`
— and bolts per-user invalidation onto every measurement / mood /
medication / workout / dashboard-widget write endpoint so the next
read paints fresh data instead of waiting out the TTL. Every cache
hit / miss surfaces on the active wide event as
`cache.<name>.outcome` + `cache.<name>.key_hash` so production logs
carry the hit-ratio signal without leaking userIds.
- **Apple Health `export.zip` import.** New endpoint
`POST /api/import/apple-health-export` (synchronous multipart
upload, asynchronous ingest via a dedicated pg-boss
`apple-health-import` worker, per-`MeasurementType` ingestion
stats). Streams the upload straight to disk so a multi-gigabyte
export never lands in V8 heap, hashes the bytes inline for
content-based idempotency, and unpacks `apple_health_export/export.xml`
with a hand-rolled ZIP central-directory walker that handles Zip64
for archives past the 4 GB barrier. The parser folds every
`<Record>`, `<Workout>`, `<Correlation>`, and `<ClinicalRecord>`
into the existing `Measurement` and `Workout` row shapes — spot
rows keyed by `HKMetadataKeyExternalUUID` (or a deterministic
`sample:<sha256>` fallback), cumulative HK types collapsed into
one `stats:<HKType>:<YYYY-MM-DD>` row per user-local day to match
the iOS daily-aggregation convention. Live per-stage progress
surfaces through `GET /api/import/apple-health-export/{jobId}/status`.
An admin variant at `POST /api/admin/import-apple-health-export`
imports on behalf of a target user (cookie-only `requireAdmin()`
gate; Bearer tokens never elevate).
- **`ImportJob` schema model + migration.** New Prisma model captures
the per-upload state machine (`queued | unpacking | parsing |
upserting | done | failed`), the content-hash for idempotency
short-circuits, and the per-`MeasurementType` ingestion counters
the status route surfaces back to the client.
- **`lastSeenByType` on `/api/analytics`.** Both the slim
(`?slice=summaries`) and default slices return a per-type
`{ lastSeenAt, daysAgo }` map. The dashboard trend tiles wire 12
mounts to a new `tileStaleDays()` helper so an "X days / weeks /
months ago" hint paints under any per-metric tile whose last
sample crosses the 7-day floor. Six locales gained additive
week / month plural keys; Polish uses the genitive-plural form
that covers every non-1 count the bucket math can produce.
- **Dashboard "Ask the coach" hero CTA.** A new pill next to the
existing "Hinzufügen" / "Add" launches the Coach drawer directly
from the dashboard hero. The `<CoachLaunchProvider>` hoisted from
the insights layout to the auth shell so the drawer is reachable
from every authed route; the floating action button stays scoped
to `/insights/**` so it cannot distract on the dashboard.
- **Shared achievements query hook.** `useAchievementsQuery()`
centralises the three previous consumers — recent-achievements
card, the `/achievements` mother page, and the unlock notifier —
onto one TanStack queryKey + cache slot so dashboard cold mount
fires the endpoint once instead of twice.
- **Typed authed Cache-Control presets.** New
`src/lib/http/cache-headers.ts` module exports
`NO_STORE_BUT_BFCACHE = "private, max-age=0, must-revalidate"`,
`SHORT_LIVED_PUBLIC`, and an `applyAuthedHeaders()` helper. The
presets land at the framework level via a `next.config.ts`
`headers()` rule that stamps the bfcache-friendly directive on
every authed HTML response, restoring Chromium bfcache eligibility
for in-app back / forward navigation.
- **`scripts/print-bundle-report.mjs`.** Restores the at-a-glance
"top client chunks by parsed size" signal Turbopack dropped from
`next build`; reads `.next/analyze/client.json` (written by
`@next/bundle-analyzer` when `pnpm analyze` runs with `ANALYZE=1`)
and prints a sorted table plus totals.
### Changed
- **Settings sidebar: "Sources" folded into "Targets & Sources".**
Per-metric threshold ranges and per-metric source priority now
share one `/settings/thresholds` page so the same metric's
threshold and device-source preference sit together instead of
one sidebar entry away. `/settings/sources` keeps a
`permanentRedirect` so external bookmarks and docs links follow
through unchanged. Section count: 11 → 10.
- **Insights tab strip: vital pills collapse under a "Vitals"
parent.** Five vital pills (HRV, Resting HR, Oxygen, Body
Temperature, Active Energy) hide behind one parent pill that
opens a popover sub-list. Parent-pill active state mirrors the
URL so spatial orientation survives the collapse; each sub-page
keeps its own URL and bookmark resolves unchanged. Strip
footprint: 14 → 10 entries when every metric has data.
- **Coolify env-var audit.** `mcp__coolify-apps01__env_vars`
inspection captured the section-1 / section-2 duplicates that
have accumulated under apps-01 since v1.3.1. Audit pinned at
`.planning/round-v1434-iwa-coolify-env-audit.md`; no env-var
deletes performed (operator action).
### Fixed
- **Compliance classifier: early intakes count as compliant.** The
classifier picked up a dedicated `early` bucket (window-start
minus three hours through window-start), the `on_time` post-window
tolerance widened from one hour to three hours, and the `late`
band sits between the new `on_time` ceiling and the configurable
`lateMinutes` knob. Heatmap consumers route the new bucket
through the compliant path; the dedicated `early` counter rides
on `DailyComplianceEntry` for downstream consumers that want to
distinguish ahead-of-window from on-window intakes.
- **Compliance heatmap fallback retired.** The v1.4.33 defensive
`looksClassifierBug` fallthrough is gone now that the underlying
classifier widening removes the every-dose-very-late mode the
fallback covered.
### Performance
- **`/api/gamification/achievements` consumer collapse.** Two of
three previous consumers shared the same TanStack queryKey
literal; the third carried a per-user discriminator so the cache
treated it as a fresh slot. Dashboard cold mount fired the
endpoint twice. Collapsing onto the shared hook trims that to a
single request; with the new server-side cache slot warm, the
duplicate-mount worst case rides single-flight coalescing.
- **GHCR build fires once per release tag.** The
`docker-publish.yml` workflow lost its `push.branches: [main]`
trigger; the `:latest` raw-tag enable rule moved onto the tag
ref so each release produces exactly one multi-arch build that
refreshes both the semver tags and the `:latest` alias.
- **NFT-trace warnings silenced.** `next.config.ts` gained an
`outputFileTracingExcludes` block that narrows the Turbopack
tracer away from the `MAXMIND_LICENSE_KEY` env-access path so
the trace-report no longer warns on every dependent route file.
### Refactor
- **Dashboard analytics consumers.** The two cards that previously
decided their own freshness copy now lean on the typed
`tileStaleDays()` helper and the additive `lastSeenByType` field
on the analytics response. Mood and BD-Zielbereich tiles keep the
default `null` because they have no underlying per-type freshness
signal.
### Accessibility
- **Dashboard hero CTA hits the WCAG 2.5.5 touch-target floor.**
The new "Ask the coach" pill carries `min-h-11` on mobile and
the matching `sm:min-h-9` desktop floor so the touch target
stays above 44 px on the Pixel 5 boundary.
- **Insights tab-strip Vitals parent reads correctly to assistive
tech.** Parent pill carries `aria-current="page"` whenever the
current URL matches one of its child vital sub-pages, plus a
`data-slot="insights-tab-strip-group"` hook for visual-regression
testing.
### Internal
- **Two e2e flake windows tightened.** `onboarding-flicker` swapped
its 12-sample 50 ms poll loop for a single Playwright
auto-retrying `toBeHidden({ timeout: 700 })` assertion so the
1-2 ms race window between the analytics-pending shell and
`useAuth().user` resolving collapses to a single retry slot.
`mobile-viewport` dropped `nav a[href]` from the touch-target
sweep (the bottom-nav owns its own WCAG spec) and gated the
44-px floor on `matchMedia('(min-width: 640px)').matches === false`
so the Pixel 5 viewport never tripped into the `sm:` tier during
WebKit render commits.
- **Server-cache observability.** Every `cached()` invocation passes
an `annotate` callback that lands two keys on the wide event:
`cache.<name>.outcome` ∈ `{ hit | miss | stampede }` and
`cache.<name>.key_hash` (non-reversible djb2 32-bit hash). Ops
can grep `cache.analytics.outcome` over any time window to
compute the hit ratio per deployment.
- **AASA followups verified.** The v1.4.33 `/.well-known/apple-app-site-association`
handler serves a direct 200 on every fronting origin; Apple's
CDN has ingested matching bodies for all three domains.
### Web freeze
v1.4.34 marks the last functional release of the web codebase before
the iOS native client launches. Subsequent v1.4.x tags carry security
fixes, dependency bumps, and hotfix-only corrections. New feature work
is paused until the iOS app clears Apple review, at which point a
v1.5.0 version-bump-only release tags the milestone. The Prisma
schema head comment and `.planning/v15-strategic-plan.md` §5
decision-log row pin the freeze trigger in-tree.
|
||
|
|
4f09c3f862 |
chore(release): v1.4.27
v1.4.27 — Mobile capability and maintainer-finding cleanup. ResponsiveSheet primitive (bottom-sheet on narrow viewports, centred dialog on desktop) applied to BD, Weight, Glucose, Mood, Activity forms. Maintainer-finding cleanups across Coach, Insights, Reports, Privacy. GeoLite2 offline geocoding with resilience layer (graceful fallback when EULA not yet propagated). E2E gap-fill coverage. 450-line release notes attached to the GitHub Release. |
||
|
|
17b8d8d2c2 |
chore(release): v1.4.25
Largest feature delta in the v1.4.x line. Insights expands into seven dedicated metric sub-pages; GLP-1 medication tracking lands end-to-end (drug-level chart with Research Mode acknowledgment, EMA titration ladder, cadence + compliance, side-effect taxonomy, pen/vial inventory); cross-source priority becomes a two-axis resolver; per-user timezone threads through ten analytics surfaces; Withings activity + sleep v2 sync; onboarding rebuilt as a nested-route wizard; Personal Records ship end-to-end; Health Score provenance accordion; Coach runs native first-party prompts across six locales with a 1800-assertion refusal-probe matrix; OpenAPI drift gate hard-fails; multi-arch GHCR image. Migrations 0043 through 0060 are additive and forward-only. PROMPT_VERSION 4.24.0 → 4.25.0 with GROUND RULE 9 (refuses dose recommendations) and GROUND RULE 15 (refuses drug-level estimates with MDR + MDCG 2021-24 cites). See CHANGELOG.md for the full per-section delta. |