Commit Graph
1852 Commits
Author SHA1 Message Date
Marc-André Bombeck cb601fcadd docs(planning): W5-IOS-WORKOUTS-DEDUP + DESIGN-POLISH v1.4.42 phase report 2026-05-21 18:55:53 +02:00
Marc-André Bombeck a4f28fdc0f style(dashboard): tile-strip placeholder parity with live trend-card chrome
The v1.4.41 W-FRONTEND-FACTORY placeholder rendered as the per-tile
Suspense fallback shipped without the trend-card's flex column or
min-height. The all-suspend edge case (every tile suspending
simultaneously, e.g. a future RSC hoist of every cell) collapsed the
grid row to zero height and the placeholder chrome diverged from the
live tile shell by a couple of layout utilities.

Match the trend-card's container classes byte-for-byte: add flex /
min-w-0 / flex-col for chrome parity and min-h-[6rem] so the fallback
holds the row open during a synchronous all-suspend transition.
Structural Suspense test pin keys on the aria-hidden marker, not the
className, so it stays green without modification.
2026-05-21 18:55:53 +02:00
Marc-André Bombeck 6e119ed47b feat(workouts): write-time canonical-row dedup for cross-source batches
iOS HealthKit observer queue routinely carries the same logical workout
from two paired sensors (Apple Watch + Withings ScanWatch) in a single
ingest batch. Without write-time dedup both rows persist (their
externalIds differ, so the (userId, source, externalId) unique index
never fires) and the read-time picker has to carry the duplicate
forward on every dashboard render.

Add pickCanonicalWorkoutRows() at src/lib/workouts/canonical-rows.ts as
a pure pre-createMany pass invoked by POST /api/workouts/batch. Groups
by (userId, activityType, startedAt +-90 s); prefers the canonical
source ladder (APPLE_HEALTH > WITHINGS > MANUAL > IMPORT) shared with
the read-time helper; breaks ties on calories > earliest createdAt >
input order. Losers surface to the iOS client as duplicate so the sync
cursor advances past them identically to the externalId case.
2026-05-21 18:55:53 +02:00
Marc-André Bombeck 43f10118b7 docs(planning): W4-ARCH-HYGIENE v1.4.42 phase report 2026-05-21 18:55:14 +02:00
Marc-André Bombeck 702afe5d49 fix(personal-records): exclude soft-deleted measurements from PR detection
pr-detection-worker.ts ran its warm-up count and best-measurement scan
across every Measurement row including soft-deleted ones. A user who
deleted a row that happened to be their PR would not get the next-best
row promoted on the next detection pass. Add `deletedAt: null` to both
where clauses to align with the v1.4.40 soft-delete completeness sweep.

Also document the offhost-backup DR-intent at the matching findMany —
that path deliberately includes soft-deleted rows because the offhost
upload is a disaster-recovery snapshot, not a user-facing export.
2026-05-21 18:55:14 +02:00
Marc-André Bombeck 6af9e1afff chore(doctor-report): escape literal control bytes in sanitiser regex
src/lib/doctor-report-data.ts was checked in as raw bytes (file(1)
reported "data", git diff reported "Binary files differ") because the
control-character regex carried literal NUL + US + DEL bytes inside the
character class. Rewrite the class as `[\x00-\x1F\x7F]` so the file is
UTF-8 clean and future diffs are readable. Same runtime behaviour — the
existing 18-case test suite still passes.
2026-05-21 18:55:14 +02:00
Marc-André Bombeck b5ef81a01b refactor(dashboard): consolidate Suspense double-comment in tile strip
The trend-card row in src/app/page.tsx carried two adjacent comment
blocks describing the same `<Suspense>` boundary — one from the v1.4.40
W-RSC seed and a second from the v1.4.41 W-FRONTEND-FACTORY fallback
hoist. Collapse into one block keyed to current behaviour with a
one-line history trailer. The sibling chart-row Suspense stayed in
single-block shape so no second consolidation was needed.
2026-05-21 18:55:14 +02:00
Marc-André Bombeck 1ea0321da7 refactor(insights): dedup BERLIN_DAY_FORMATTER across seven status helpers
Each of the seven src/lib/insights/*-status.ts files carried an identical
20-LOC block defining BERLIN_DAY_FORMATTER plus toBerlinDayKey. Extract
the helper into src/lib/tz/resolver.ts (next to dayKeyForScheduledFor and
friends) and import it everywhere. Same runtime behaviour, 100-LOC drop.
2026-05-21 18:55:14 +02:00
Marc-André Bombeck bc50d3ce8c docs(planning): W2-ZOD-MULTI-ISSUE v1.4.42 phase report
Records the helper landing + widgets-route swap and stages the
v1.4.43 rollout queue (41 sites in src/app/api/** still on the
issues[0].message pattern). Includes the rewrite recipe + iOS-contract
prioritisation so the follow-up wave can pick up without re-discovery.
2026-05-21 18:52:41 +02:00
Marc-André Bombeck 876a545d9c feat(api/dashboard): return every Zod issue on widgets PUT 422
The PUT /api/dashboard/widgets route surfaced only the first Zod issue
on 422, which forced iOS clients debugging the widget-layout contract
into one round-trip per wrong field. The route now wires the shared
returnAllZodIssues helper so every issue lands in details.issues at
once.

Adds an append-only audit-ledger breadcrumb keyed
dashboard.widgets.validation-failed so the operator can grep
/api/admin/audit for the same trail outside the iOS dev console. The
write is fire-and-forget — the validation response is the contract,
the audit row is best-effort.

Tests cover 2 + 3 simultaneous issues, audit-row shape, params-leak
guard, and audit-write-rejection survival on both the unit and
integration tiers.
2026-05-21 18:52:41 +02:00
Marc-André Bombeck 098ca4aed0 feat(api): add returnAllZodIssues helper for multi-issue 422 envelopes
Historic pattern was apiError(parsed.error.issues[0].message, 422) which
dropped every issue past the first. Mobile callers debugging a contract
needed one round-trip per wrong field. The new helper returns every
issue under details.issues, additive to the existing envelope so any
client that only reads `error` keeps working.

Sanitises issues to {path, code, message} — issue.params can carry the
raw rejected user input for some Zod codes and must not leak.
2026-05-21 18:52:41 +02:00
Marc-André Bombeck d3d6010407 docs(planning): v1.4.41 QA round findings reports
Carry-over from the v1.4.41 marathon reconcile — the six W10 reviewer
reports (code-reviewer, security, design, senior-dev, product-lead,
simplifier-residual) were not committed before the squash-merge to
main. Lands them on develop so the next marathon's audit-trail has
the inputs that gated the v1.4.41 tag in one place.
2026-05-21 18:42:55 +02:00
Marc-André Bombeck 9e775aa374 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.
2026-05-21 18:21:41 +02:00
Marc-André Bombeck 182d15747d docs(planning): W-RECONCILE-INSIGHTS v1.4.41 phase report
Captures the helper extract + 6 sibling-route wire + cache-shape
reconcile + test pins. Notes the medication-compliance stub-row
recogniser fix and the pulse-status-timeout assertion flip as
risk callouts.
2026-05-21 18:18:53 +02:00
Marc-André Bombeck 134566466d perf(insights): wire six sibling status routes to the shared timeout-stub helper
Bring blood-pressure, weight, general, pulse, mood, and
medication-compliance into parity with bmi-status. On a 20 s
provider stall every route now persists a sentinel auditLog row
keyed to today's Berlin day so the next mount short-circuits at
the cache lookup instead of re-racing the same provider call on
every cold visit. Eliminates the ~14 s warm response on every
dashboard open after a one-off provider hiccup.

The seven routes share one persist path through
`persistTimeoutStubAndReturn`; ~120 LOC of duplicate
`auditLog.create` calls collapse into the helper.

medication-compliance returns a richer `{summary, medications}`
envelope rather than the standard `{text}` shape, so it calls
the helper for the persist side-effect and maps `summary` ←
`text` on the way out. Its cache-read also gains a stub-row
recogniser so the second-mount short-circuit fires on the
helper's `text` + `timeout: true` payload.

Tests cover both arms per route: the persist-on-timeout path
asserts a single auditLog.create with `timeout: true`, model
`timeout-stub`, and today's Berlin dateKey; the
short-circuit-on-stub path asserts a subsequent mount returns
the cached stub text without invoking the provider.
2026-05-21 18:18:53 +02:00
Marc-André Bombeck e4d46de22d refactor(insights): extract shared timeout-stub persist helper
Pull the 40-line auditLog.create block out of bmi-status into a
dedicated `persist-timeout-stub.ts` helper so every InsightStatus
route can share one persist path instead of copy-pasting the
sentinel-row shape. The bmi route now calls the helper in a
6-line return; behaviour and persisted body are byte-equivalent
to the inline form.

Sets up the next commit, which wires the six remaining sibling
routes (blood-pressure, weight, general, pulse, mood,
medication-compliance) to the same helper and closes the
last bare-fallback shape on the dashboard hot path.
2026-05-21 18:18:53 +02:00
Marc-André Bombeck cd2a579cc3 Revert "perf(insights): persist timeout stub for blood-pressure and weight status"
This reverts commit 27f3bec1f4.
2026-05-21 18:18:48 +02:00
Marc-André Bombeck 812a8f287e chore(lint): ignore .claude/** worktrees and align check-user mock with RateLimitResult
Two small follow-ups to the v1.4.41 inline-QA reconcile:

- eslint.config.mjs gains `.claude/**` in the globalIgnores list so a
  mid-marathon Claude Code worktree on an older base commit can no
  longer poison `pnpm lint` locally with pre-fix warnings. CI never
  walks that path; the change is purely for the dev environment.

- The check-user route test mock objects for `checkRateLimit` carried
  a stray `limit: 30` field that does not exist on `RateLimitResult`
  (the real type is `{ allowed, remaining, resetAt }`). The literal
  was harmless at runtime but flagged by `tsc --noEmit` on the
  test-file declarations. Drops the field at all three mock sites.
2026-05-21 18:15:59 +02:00
Marc-André Bombeck 9d8e0d7a07 test(soft-delete): pin gamification/achievements and doctor-report/availability
The W-DELETED-2 integration-test file header promises coverage for five
reader tiers; v1.4.41 shipped pin assertions for three (`/api/export`,
`/api/export/full-backup`, `/api/export/measurements`) but never asserted
the two routes that the W-DELETED-2 fix actually touched:

- `/api/gamification/achievements` — reads recent measurements via
  `findMany` to compute streak / badge progress. A tombstoned row must
  never count toward a milestone.
- `/api/doctor-report/availability` — four parallel `measurement.count`
  probes drive the section-availability switch. A soft-deleted history
  must not light up a section the user has since wiped.

Adds one `it()` block per route asserting that every measurement
read scopes to `deletedAt: null`. Mocks already in place; no
test-infra work needed.
2026-05-21 18:15:50 +02:00
Marc-André Bombeck 92753a7096 refactor(types): drop duplicate DataSummary import alias and lift W-ORG imports to file head
Two clarity regressions surfaced by the v1.4.41 QA round.

1. `src/types/analytics.ts:37-38` imported `DataSummary` twice from the
   same module — once bare, once aliased as `DataSummaryType` — with
   the alias used on a single line. The duplicate shape was carried
   verbatim from `src/app/page.tsx` where both names existed
   historically; in a fresh module there's no reason for two import
   lines. Collapses to a single import; `glucoseByContext` now uses
   the canonical `DataSummary`. Same fix replayed in `src/app/page.tsx`.

2. `src/app/insights/page.tsx:100` and
   `src/components/onboarding/getting-started-checklist.tsx:75` carried
   their W-ORG alias-back-import in the middle of the file, after
   non-import statements. Lifts both into the top-of-file import block
   alongside their peers; the aliased name (`as AnalyticsData`) stays
   for call-site stability, the W-ORG header comment moves with the
   import.
2026-05-21 18:15:40 +02:00
Marc-André Bombeck fdd73c711b fix(eslint): expand queryKey-factory rule whitelist to mirror test-guard guardedRoots
The v1.4.41 W-PROCESS-DOCS promotion of the test-guard substitute to a
real ESLint rule shipped with a whitelist (`charts`, `comparison`,
`page.tsx`, `use-auth.ts`) narrower than the companion test-guard's
`guardedRoots` (which also covers `app/auth`, `app/notifications`, and
`components/settings/about-section.tsx` — the three surfaces W-FRONTEND-
FACTORY migrated in the same release).

Without the mirror, a bare-literal `queryKey: [ ... ]` regression in any
of the three v1.4.41-migrated dirs would slip past IDE / `pnpm lint`
and only be caught by `pnpm test`. The lint rule and the test-guard
should fail at the same boundary.

Extends GUARDED_DIRECTORIES + GUARDED_FILES to match the test-guard
list, with an inline comment cross-referencing the migration wave.
2026-05-21 18:15:29 +02:00
Marc-André Bombeck 2f52f66879 fix(auth-check-user): match identifier verbatim and gate behind per-IP rate-limit
Two correctness gaps on the v1.4.41 onboarding-discovery endpoint,
caught in the v1.4.41 QA round:

1. The route called `identifier.toLowerCase()` before the OR-match on
   `username` / `email`, but `registerSchema` applies no transform on
   write — both columns are stored exactly as typed. A user registered
   as `MixedCase@Example.com` would never resolve through this route,
   and iOS onboarding would route them to the sign-up branch despite
   an existing account.

2. The route header claimed an edge-level limit on `/api/auth/*`
   covered brute-force enumeration; no such middleware exists. Sibling
   `/api/auth/passkey/login-options` carries a per-route throttle. We
   mirror that shape — `checkRateLimit("auth:check-user:<ip>", 30,
   15 * 60 * 1000)` — and rewrite the header comment so the rationale
   matches reality.

Tests pin both invariants: a `MixedCase@Example.com` probe hits
`findFirst` with the case preserved, and a 429 short-circuits the
`findFirst` call entirely.
2026-05-21 18:09:35 +02:00
Marc-André Bombeck f2a1e8cec8 test(dashboard): update Suspense fallback pin to the placeholder-div contract
v1.4.41 W-FRONTEND-FACTORY (UX M1) swapped the tile-strip Suspense
fallback from `null` to an `aria-hidden` placeholder div that mirrors
the trend-card chrome, preventing CLS when a future RSC hoist makes
the tile body suspend. The literal regex pin in the boundary test was
not updated alongside, leaving a red on develop tip.

Updates the regex to match the new structural contract and refreshes
the surrounding comment so future contributors see why the fallback is
no longer `null`.
2026-05-21 17:55:11 +02:00
Marc-André Bombeck 0aa2f14935 docs(planning): W-SIMPLIFIER v1.4.41 phase report 2026-05-21 17:52:01 +02:00
Marc-André Bombeck 70ff3eef73 chore(cleanup): trim 13 dead exports surfaced by knip
Narrow each helper's visibility to its actual reach instead of leaving
it exported "just in case":

  - Drop the `export` keyword on file-local helpers / constants:
    `getTrendSentiment`, `isPRWithin30Days`, `buildCoachMetricSourceType`,
    `countPassedSchedules`, `getGithubConfig`, `isComparisonBaseline`,
    `DASHBOARD_LAYOUT_VERSION`, `INTL_LOCALE_MAP`, `SIDE_EFFECT_NOTES_MAX`,
    `MEDICATION_CATEGORIES`, `openApiBase`, `ALL_MOOD_GRANULARITIES`.
  - Remove never-used dead code:
    `CodexOAuthNotConfiguredError` (declared as a backwards-compat shim
    no caller ever consumed), `editMessageReplyMarkup` (Telegram method
    nothing on the bot dispatch tree calls), and the stale
    `DISPLAY_TIMEZONE` re-export from `src/lib/format.ts`.

Knip drops from 48 -> 35 unused exports. Pure narrowing / deletion;
no behaviour change.
2026-05-21 17:52:01 +02:00
Marc-André Bombeck 1b0bcadb50 refactor(rollups): drop unused optional tx params from recompute helpers
`recomputeMoodBucketsForEntry`, `recomputeMedicationComplianceForDay`,
and `recomputeMedicationComplianceForEvent` all declared an optional
`tx?` Prisma transaction client but no call site has ever passed one —
every caller (routes, jobs, worker, tests) invokes them outside a
`$transaction` block. The dead surface area kept dragging a
`PrismaLike` / `PrismaTxOrClient` alias plus a top-level `Prisma`
import along with it. With the param gone the helpers simply close
over the singleton `prisma` client; the alias and the
type-only import follow.

No call-site changes needed — the param was optional everywhere.
2026-05-21 17:52:01 +02:00
Marc-André Bombeck 54ad5cdb69 refactor(medications): extract shared today-intake projection helper
Both `/api/medications/intake?scope=today` and `/api/dashboard/summary`
carried their own copy of the v1.4.39 projection + idempotent
`createMany` + per-`(med, day)` compliance recompute. The duplicate
implementations had already drifted twice; fold them into one tested
location at `src/lib/medications/scheduling/project-today-intakes.ts`
so future changes (new IntakeSource literal, new schedule cadence,
audit metadata) only land once.

The helper stays read-shape-neutral — the two routes return different
projections of the resulting events, so the caller still owns its
typed re-read. Returns `{ projected, backfilled }` for the existing
`annotate` telemetry.

Net: ~200 lines collapsed into 145 (helper) + two short call sites.
2026-05-21 17:52:01 +02:00
Marc-André Bombeck 3c73ef5c6f chore(cleanup): drop five unused imports flagged by eslint
The insights page kept `CorrelationResult` + `DataSummary` type imports
left over from an earlier refactor, and the slim summaries slice still
referenced `RollupGranularity`, `aggregateWmyBuckets`, and
`RollupBucketRow` after the v1.4.37.2 GROUP BY rewrite folded that work
into the narrow aggregate. Pure deletions — both helpers stay exported
for the test suite that still exercises them.
2026-05-21 17:52:01 +02:00
Marc-André Bombeck 27f3bec1f4 perf(insights): persist timeout stub for blood-pressure and weight status
Mirror the bmi-status (v1.4.37) timeout-stub persist into the two
sibling endpoints. On a 20 s provider stall the route now writes a
sentinel auditLog row keyed to today's Berlin day so the next mount
short-circuits at the cache lookup instead of re-racing the same
provider call for the rest of the day.

This eliminates the ~14 s warm response on every iOS dashboard open
when the provider has stalled once that day. Response envelope
unchanged; iOS v0.5.4 contract preserved.

Tests cover both arms: the persist-on-timeout path (one create with
timeout:true, model:"timeout-stub", today's dateKey) and the
short-circuit-on-stub path (subsequent mount returns cached text,
provider never invoked).
2026-05-21 17:38:20 +02:00
Marc-André Bombeck 9d2901aaf9 refactor(rollups): retire v1.4.39 W-SUM legacy-NULL UNION discovery arm
The `sum_value IS NULL` UNION arm in `enqueueBootTimeRollupBackfill`
was added in v1.4.39 W-SUM to converge DAY rollup rows that pre-dated
the writer change. Production data has since converged, so the arm is
a permanent no-op seq scan over `measurement_rollups`. Per-day missing
coverage remains the sole discovery anchor.

Drops the legacy text-anchor unit test. The read-side `mean * count`
fallback in `/api/dashboard/summary` retains legacy-row readability
and stays covered by its dedicated route test.
2026-05-21 17:35:10 +02:00
Marc-André Bombeck a1bfc3b461 docs(planning): v1.4.41 marathon handoff for fresh session 2026-05-21 17:17:53 +02:00
Marc-André Bombeck ac5ecd39f1 docs(planning): W-FRONTEND-FACTORY + W-ORG v1.4.41 phase reports 2026-05-21 17:17:13 +02:00
Marc-André BombeckandClaude Opus 4.7 70c5026812 docs(operator): pg.Pool max scaling guidance for multi-container deploys
Append a Postgres connection-pool sizing section to the self-hosting
scaling guide. Documents the v1.4.40 W-POOL default (20 slots per
container), the container_count × DATABASE_POOL_MAX × max_connections
envelope (with a 1-5 container ready-reckoner table), the env-var
override path, and PgBouncer as the escape hatch for deployments that
outgrow the per-process pool model. Cross-references src/lib/db.ts and
the empirical trace that motivated the bump.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 17:16:04 +02:00
Marc-André Bombeck 8a56f48259 refactor(prompts): unify src/lib/insights/prompt*.ts into src/lib/ai/prompts/
Pre-v1.4.41 prompts lived in two homes — `src/lib/ai/prompts/` (per-
metric system prompts + safety contracts) and `src/lib/insights/prompt
*.ts` (user-prompt builder + comparison snapshot + the `compactSections`
helper). A new reader could not tell from filenames which file to
extend; both directories looked equally authoritative. Audit rec #3
flagged the split as the only undiscoverable seam in the AI layer.

Move both files into `src/lib/ai/prompts/`:
  - `lib/insights/prompt.ts` → `lib/ai/prompts/insight-system-prompt.ts`
  - `lib/insights/prompt-compact.ts` → `lib/ai/prompts/compact-sections.ts`
  - co-located tests follow

Three importers updated: `app/api/insights/generate/route.ts`,
`lib/ai/coach/snapshot.ts`, the generate route test (the
`vi.mock('@/lib/insights/prompt')` path moved too). Prompts now have
ONE home and ONE mental model.
2026-05-21 17:14:01 +02:00
Marc-André Bombeck d0bdc4b8d1 test(integration): pin soft-delete invisibility in remaining reader tiers
v1.4.41 W-DELETED-2 — assert that /api/export, /api/export/full-backup,
and /api/export/measurements all scope the measurement read to
deletedAt: null. Shape-level guard so a future refactor cannot silently
drop the filter and resurrect deleted rows in user-downloaded files.
2026-05-21 17:14:00 +02:00
Marc-André Bombeck 0bf07abd9d refactor(query-keys): expand factory and migrate auth, notifications, about
Routes the registration-status, auth invalidation, notifications
preferences, and Settings about-section api-version reads through
the centralised queryKeys factory. Adds factory entries for the
remaining settings/admin surfaces a follow-up will migrate, and
extends the walker test to fail on any future bare-literal
queryKey in src/app/auth, src/app/notifications, and the
about-section. Also swaps the dashboard tile Suspense fallback
from null to a layout-stable card placeholder so a future RSC
hoist of any tile slot can't trigger CLS.
2026-05-21 17:13:57 +02:00
Marc-André Bombeck 59befdca73 docs(planning): W-IOS-COORD v1.4.41 closure report
Captures SB-7 follow-up (check-user endpoint shipped), SB-8 (merge
semantics documented, no code change), SB-9 (already retired, no
streak surface exists), and the dashboard-widgets PUT 422 root cause:
the Zod validator is correct and additive-safe; the live 422s from
iOS v0.5.4 are an iOS-side payload bug (likely an unknown widget id
or an out-of-range order value). No server fix viable.
2026-05-21 17:13:49 +02:00
Marc-André Bombeck dde79b041c chore(streak): formalise deprecation status per SB-9
ls src/app/api/streak returns No such file or directory. No web
frontend code paths reference /api/streak/...; the only streak
references in the API tree are derived fields inside
/api/insights/targets (streakDays, streakHighlight).

Decision: nothing to deprecate. The route family either never existed
or was removed before the audit. iOS can safely treat /api/streak/*
as 404. Document filed so a future audit does not re-open the
question.
2026-05-21 17:13:49 +02:00
Marc-André Bombeck 6c2eadb342 docs(dashboard-layout): document merge semantics for SB-8 audit gap
The dashboard layout resolver in src/lib/dashboard-layout.ts is
append-only on read: new widget ids added to DASHBOARD_WIDGET_IDS
automatically appear for every existing user on next GET, with
visible / tileVisible / order taken from DEFAULT_DASHBOARD_LAYOUT. No
database migration is ever required when introducing a new widget.

Documents the merge contract so a future widget-introduction does not
ship a one-shot SQL migration that would clobber every user's
customisation. PUT preservation rules captured: chartOverlayPrefs is
preserved-on-omit, comparisonBaseline is not. Investigation-only — no
code change.
2026-05-21 17:13:49 +02:00
Marc-André Bombeck 99a801f993 feat(auth-check-user): four-branch discovery endpoint for iOS onboarding
Closes SB-7 follow-up. POST /api/auth/check-user accepts
{ identifier: string } (username or email, case-insensitive) and returns
{ branch, hasPasskey, hasPassword } where branch is one of:

- not_found       no account
- passkey_only    passkey present, no password
- email_fallback  password present (passkey optional)
- exists          neither credential (recovery path)

The booleans let the iOS client render a "Sign in with Passkey"
affordance alongside the password field without a second round-trip.

Five-case test pin covers every branch plus the 422 identifier-required
guard. The endpoint mirrors the envelope shape of /api/auth/passkey/
login-options and adds no new enumeration surface beyond that route.
2026-05-21 17:13:34 +02:00
Marc-André Bombeck cb8f74e4fa fix(gamification): exclude soft-deleted measurements in achievement queries
v1.4.41 W-DELETED-2 — achievement progress now scopes the measurement
read to deletedAt: null so deleting a row immediately rolls back any
streak or count badge it had earned, matching the analytics + dashboard
sweeps from v1.4.40.
2026-05-21 17:13:07 +02:00
Marc-André Bombeck 5296a6122f fix(doctor-report): exclude soft-deleted measurements in PDF aggregator
v1.4.41 W-DELETED-2 — the doctor-report-data aggregator (shared by
/api/doctor-report JSON + /api/doctor-report/pdf server render) and the
section-availability probe now filter deletedAt: null so deleted rows
never appear in the rendered PDF or trigger an empty section toggle.
2026-05-21 17:12:53 +02:00
Marc-André Bombeck dc66dfcfdc refactor(types): consolidate AnalyticsData into src/types/analytics.ts
Three structurally-distinct `interface AnalyticsData {…}` declarations
shared a name across `src/app/page.tsx` (dashboard), `src/app/insights/
page.tsx` (insights mother), and `src/components/onboarding/
getting-started-checklist.tsx` (checklist). The collision made the
shapes un-discoverable from any one site and forced every iOS-contract
addition to land in three places.

Hoist all three into `src/types/analytics.ts` as named exports:
`DashboardAnalyticsData`, `InsightsAnalyticsData`, `ChecklistAnalytics
Data`. Each call site re-imports its shape under the original alias to
keep downstream code readable; the slim `SubPageAnalyticsData` that was
already there stays put. We deliberately keep the four shapes distinct
(rather than collapsing to one with everything optional) so call sites
can't cross-read fields they shouldn't reach for — closes v1.4.39 org-
audit recommendation #2.
2026-05-21 17:12:38 +02:00
Marc-André Bombeck a62b94983b fix(export): exclude soft-deleted measurements in export bundle reads
v1.4.41 W-DELETED-2 — full-backup JSON, per-type CSV, and the legacy
/api/export endpoint now scope reads to deletedAt: null so iOS undo
or pending-sync rows never reach the user's downloaded file or the
admin restore round-trip.
2026-05-21 17:12:31 +02:00
Marc-André Bombeck bba38b8c66 refactor(types): move BackupRow and BackupsList out of route handler into src/types/backups.ts
Resolves the single component → route-handler import in the codebase
(`components/admin/backups-section.tsx ← app/api/admin/backups/route.ts`)
flagged by the v1.4.39 org audit (recommendation #2). The DTOs now live
in `src/types/backups.ts`; the route handler keeps owning the HTTP
contract and re-imports the shared types from there.
2026-05-21 17:10:38 +02:00
Marc-André Bombeck 4cca62dce9 docs(planning): v1.4.40 marathon closure row, QA findings, perf-verify
Adds the v1.4.40 row + the four prior v1.4.39.x stacked rows to
.planning/round-audit-marathon-closure.md (v1.4.39.1/.2/.3/.4 were
documented inline in the corresponding memory files but the table
hadn't picked them up).

Commits the six v1.4.40 QA reviewer findings files (senior, security,
specialist, UX, product-lead, simplifier) so the audit trail stays
self-contained.

Adds round-v1440-perf-verify.md anchored on the live deploy commit
1114cf7e (squash-merge), Coolify deploy timestamp 2026-05-21T12:55:02Z,
docker workflow 26221332323. Includes the AP-2 .p8 install runbook for
SB-5 live effect.
2026-05-21 13:00:03 +02:00
Marc-André Bombeck 32c73bddc7 Merge branch 'main' into develop 2026-05-21 12:55:11 +02:00
Marc-André Bombeck 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.
v1.4.40
2026-05-21 12:48:02 +02:00
Marc-André Bombeck 203373dcef chore(release): v1.4.40 — Critical+High architecture closure plus iOS PB30 enablement
Eleven touch-disjoint waves landed on develop plus the post-QA reconcile
patches:

- W-POOL: p-limit(4) wrapper around the analytics 15-way fan-out and
  pg.Pool max raised 10 -> 20 closes the v1.4.39 empirical-trace pool
  starvation root cause. Wave-C chart-tile first-paint moves from +7.3 s
  to +1.6 s on the empirical fixture.
- W-DELETED: 11 reader-tier helpers + 3 integration contracts close
  audit Critical Finding #3 (soft-delete invisibility) across the
  user-facing dashboard, analytics, and Coach paths.
- W-INSIGHTS: mood-rollup swap on the three target routes plus the
  compliance-rollup hook gap closure; the post-QA reconcile patch
  closes the six remaining measurement.findMany sites in the cluster
  that still leaked tombstoned rows.
- W-INFRA: rollup umbrella consolidation under src/lib/rollups/ with
  zero orphan re-exports; lint and knip CI gates green.
- W-RSC: per-tile Suspense boundaries plus the queryKey factory-bypass
  walker test extended to comparison/.
- W-PRIVACY: bilingual /privacy page with 17 paired-section tests.
- W-AASA: /.well-known/apple-app-site-association endpoint pinned to
  S8WDX4W5KX.dev.healthlog.app with app-ID parity assertions.
- W-APNS-NOTIFY: MEDICATION_REMINDER time-sensitive payload (priority 10
  with interruption-level) scoped via parameterised test that pins all
  6 other event-types do not bypass Focus.
- W-CONSENT: AI consent receipts CRUD with append-only invariant and
  byte-bounded artefact cap.
- W-WMY-WIRE: three previously-dead WMY readers (week/month/year) wired
  through summaries-slice and health-score-fast-path.
- W-GHOSTS: ~1 177 lines of dead code removed across 9 atomic commits.

Reconcile patches applied per the v1.4.40 QA round (.planning/round-v1440-QA-*-findings.md):
- senior C1 — dashboard-suspense-boundaries regex aligned with W-INFRA Thread 2
- senior H1 — soft-delete filter added to the six remaining insights findMany sites
- specialist H1 — Promise.allSettled around bulk-projection compliance recompute
- ux H1 — compare-toggle migrated to queryKeys.dashboardWidgets factory
- security M1 — consent artefact cap enforced via Buffer.byteLength

Wave reports under .planning/phase-W-*-v1440-report.md; full release
prose in CHANGELOG.md.

pnpm typecheck / pnpm lint / pnpm knip / pnpm test --run all green.
Tests 4525 -> 4726 unit + 1 skipped over the v1.4.39 -> v1.4.40 span.
2026-05-21 12:45:58 +02:00
Marc-André Bombeck 2c3eeee39b fix(consent): enforce artefact 64 KB cap via Buffer.byteLength (not char-count)
`z.string().max()` counts JavaScript string units (UTF-16 code
units), not bytes. The audit-table guarantee for SB-10 consent
artefacts is byte-bounded — a UTF-8 artefact full of multi-byte code
points (CJK, emoji) would otherwise slip past the 64 KB row budget.
Replace the `.max()` with a `.refine()` that uses
`Buffer.byteLength(value, "utf8")`.

Closes security M1 from the v1.4.40 QA round.
2026-05-21 12:43:28 +02:00